diff --git "a/4699.jsonl" "b/4699.jsonl"
new file mode 100644--- /dev/null
+++ "b/4699.jsonl"
@@ -0,0 +1,2095 @@
+{"seq_id":"42207001736","text":"#!/usr/bin/env python3\n#coding=utf-8\n\n#udp编程\n#使用UDP协议时,不需要建立连接,只需要知道对方的IP地址和端口号,\n# 就可以直接发数据包。但是,能不能到达就不知道了\n#速度快\nimport socket\n#SOCK_DGRAM指定了这个Socket的类型是UDP\ns = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)\nfor data in [b'Michael', b'Tracy', b'Sarah']:\n s.sendto(data,('127.0.0.1',9999))\n print(s.recv(1024).decode('utf-8'))\ns.close()\n","repo_name":"pythongitproject/python-project","sub_path":"basics/udp-client.py","file_name":"udp-client.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"36482313376","text":"import json\nimport requests\nimport os\nimport sys\nimport time\nfrom core.data import *\npath_parent = os.path.dirname(os.getcwd()) #pega diretório pai para realizar operações dentro das pastas\n\n\ndef get(option,endpoint = endpoint,tokenAPI = tokenAPI,cryptKey = cryptKey, pg = \"1\"):\n url = endpoint + \"/\" + option + \"?tokenAPI=\" + tokenAPI + \"&cryptKey=\" + cryptKey + \"&pg=\" +pg\n if requests.get(url).status_code == 200:\n response = requests.get(url).json()\n #with open(\"response.txt\",\"w\") as file: #para gravar arquivo, evitar puxar muitos calls na API\n #json.dump(response,file)\n return response #json.dumps(response, sort_keys=True, indent=4,ensure_ascii=False)\n else:\n print(requests.get(url).status_code)\n return 0\n\n\ndef getDownloadURL(uuidDoc, option = \"documents\",endpoint = endpoint,tokenAPI = tokenAPI,cryptKey = cryptKey):\n url = endpoint + \"/\" + option + \"/\"+ uuidDoc+ \"/download\" +\"?tokenAPI=\" + tokenAPI + \"&cryptKey=\" + cryptKey\n if requests.post(url).status_code == 200:\n response = requests.post(url,data={\t\"type\": \"PDF\",\t\"language\": \"pt\"})\n return response.json()['url']\n else:\n print(requests.post(url).status_code)\n return 0\n\ndef createBackupDir(timestamp):\n try:\n os.mkdir(path_parent+\"/backup/backup\"+timestamp)\n except OSError:\n print(\"Creation of the backup directory failed\")\n else:\n print(\"Successfully created the backup directory\")\n\ndef backupProcess():\n downloadFromBackup(backupFile)\n\ndef backupFile():\n data = get(\"documents\")\n if data == 0:\n sys.exit(\"Erro ao executar backup!\")\n linhaInfo = data[0].copy() #copia o primeiro elemento com os dados dos documentos\n if linhaInfo[\"total_pages\"] != linhaInfo[\"current_page\"]: #se tiver mais de uma página, roda a call novamente para pegar os dados das prox paginas\n i = linhaInfo[\"current_page\"]\n j = linhaInfo[\"total_pages\"]\n while j != i:\n newData = get(\"documents\", i+1)\n for item in range(1, newData[0][\"total_documents\"]+1):\n data.update(item)\n i += 1\n timestamp = str(round(time.time()))\n #busca as URLs de download e adiciona no dicionário por documento\n for i in range(1, linhaInfo[\"total_documents\"]+1):\n data[i][\"downloadURL\"] = getDownloadURL(data[i][\"uuidDoc\"])\n data[i][\"timestamp\"] = timestamp\n print(data[i])\n print(\"URLs de download obtidas com sucesso\")\n\n #gera um arquivo com os dados finalizados para conferência\n with open(path_parent+\"/backup/\" +\"backup\"+ timestamp +\".txt\", \"w\") as fileBkp:\n json.dump(data, fileBkp)\n print(\"Arquivo de backup salvo com sucesso\")\n return \"backup\" + timestamp\n\n\ndef downloadFromBackup(filename):\n #fazer o backup direto do arquivo salvo anteriormente. para não fazer o processo novamente.\n with open(path_parent+\"/backup/\" + filename) as json_file:\n data = json.load(json_file)\n createBackupDir(data[1][\"timestamp\"])\n for i in range(1,data[0][\"total_documents\"]+1):\n print(data[i])\n print(\"Baixando PDFs\")\n requestsURL = requests.get(data[i][\"downloadURL\"])\n with open(path_parent+\"/backup/\" +\"backup\"+ data[i][\"timestamp\"] +\"/\"+ data[i][\"nameDoc\"] + \"-\" + data[i][\"statusId\"]+\".pdf\",\"wb+\") as pdf:\n pdf.write(requestsURL.content)","repo_name":"dekken201/d4sign-api-tools","sub_path":"core/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":3394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"9805774199","text":"from . import nlp\r\n#from nlp import token\r\nfrom . import compare_nlp\r\n#from . import ht_scraper as ht\r\nfrom django.shortcuts import render\r\nfrom django.http import HttpResponse\r\nfrom . import scraping\r\nfrom . import file_handle as fh\r\n\r\n\r\ndef main(request):\r\n\tscraping.content.clear()\r\n\tscraping.heading.clear()\r\n\tcompare_nlp.lst.clear()\r\n\tcompare_nlp.decision.clear()\r\n\t#search = input(\"Enter Search String: \")\r\n\tsearch = request.POST['search']\r\n\tn = nlp.text_processing(search)\r\n\t#print(\"Final Search String: \\n\", n)\r\n\tscraping.it_scraping(n)\r\n\tscraping.ie_scraping(n)\r\n\r\n\r\n\t#print(\"Enter Compare Block in main\")\r\n\tif len(scraping.heading) == 0:\r\n\t\treturn render(request, \"Search.html\", {'Heading': 'Result Not Found', 'Content': 'Result Not Found', 'Decision': 'Result Not Found'})\r\n\telse: \r\n\t\tfor i in range(len(scraping.heading)):\r\n\t\t\t#nlp.lst.clear\r\n\t\t\tprint(\"Heading len: \",len(scraping.heading))\r\n\t\t\tkey_out = nlp.text_processing(scraping.heading[i])\r\n\t\t\t#print(\"Final Out Put String: \\n\", key_out)\r\n\t\t\tcompare_nlp.compare(n, key_out)\r\n\t\tprint(\"Exit Compare Block\")\r\n\tif len(compare_nlp.lst) == 0:\r\n\t\treturn render(request, \"Search.html\", {'Heading': scraping.heading[0], 'Content': scraping.content[0], 'Decision': \"News You Searched was not True\", 'percent':0})\r\n\r\n\telse:\t\r\n\t\tcomp = compare_nlp.avrg()\r\n\t\tfh.handle(search, comp)\r\n\t\treturn render(request, \"Search.html\", {'Heading': scraping.heading[0], 'Content': scraping.content[0], 'Decision': compare_nlp.decision[0], 'percent':comp})\r\n\t'''try:\r\n\t\tcompare_nlp.avrg()\r\n\r\n\t\treturn render(request, \"result.html\", {'Heading': ie.heading[0], 'Content': ie.content[0], 'Decision': compare_nlp.decision[0]})\r\n\r\n\texcept IndexError:\r\n\t\treturn render(request, \"result.html\", {'Heading': 'Result Not Found', 'Content': 'Result Not Found', 'Decision': 'Result Not Found'})\r\n\texcept ZeroDivisionError:\r\n\t\treturn render(request, \"result.html\", {'Heading': 'Result Not Found', 'Content': 'Result Not Found', 'Decision': 'Result Not Found'})\r\n\r\n\t\t#print(\"Could Not Find Result Search Again\")'''\r\n#main()\r\n","repo_name":"Himrocks29/News-detection","sub_path":"news_detector/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2053,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"36606483695","text":"inp = [line.split() for line in open(\"input\").readlines()]\npos = sum(int(line[1]) if line[0] == \"forward\" else 0 for line in inp)\ndepth = sum(int(line[1]) if line[0] == \"down\" else -int(line[1]) if line[0] == \"up\" else 0 for line in inp)\nprint(\"Part 1:\", pos * depth)\n\ndepth = 0\naim = 0\n\nfor line in inp:\n if line[0] == \"forward\":\n depth += aim * int(line[1])\n else:\n aim += int(line[1]) if line[0] == \"down\" else -int(line[1])\n\nprint(\"Part 2:\", pos * depth)\n","repo_name":"evanphoward/AdventOfCode","sub_path":"AOC_21/Day2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"}
+{"seq_id":"5838885081","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 11 21:46:07 2019\n\n@author: aquib\n\"\"\"\n\n# Enter your code here. Read input from STDIN. Print output to STDOUT\nx=input()\nlowchar=[]\nuppchar=[]\nodddigit=[]\nevendigit=[]\nfor i in x:\n if i.isalpha():\n if i.isupper():\n uppchar.append(i)\n else:\n lowchar.append(i)\n elif i.isdigit():\n if int(i)%2==0:\n evendigit.append(i)\n else:\n odddigit.append(i)\ny=''.join(sorted(lowchar)+sorted(uppchar)+sorted(odddigit)+sorted(evendigit))\nprint(y)\n","repo_name":"aquibjamal/hackerrank_solutions","sub_path":"ginorts.py","file_name":"ginorts.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"7100973992","text":"'''\nSource: AlgoExpert\nWrite a function that takes in a \"special\" array and returns its product sum. \nA \"special\" array is a non-empty array that contains either integers or other \"special\" arrays.\nThe product sum of a \"special\" array is the sum of its elements, where \"special\" arrays inside it are summed themselves and then multiplied by their level of depth. \nThe depth of a \"special\" array is how far nested it is. For instance, the depth of [] is 1\nThe depth of the inner array in [[]] is 2\nThe depth of the innermost array in [[[]]] is 3\nInput = [5, 2, [7, -1], 3, [6, [-13, 8], 4]] \nOutput = 12\n'''\n\n\ndef product_sum(array, level=1):\n sum = 0\n for i in range(len(array)):\n if type(array[i]) is int:\n sum += array[i]\n continue\n\n sum += product_sum(array[i], level + 1)\n\n return sum * level\n\n\nif __name__ == \"__main__\":\n print(product_sum([5, 2, [7, -1], 3, [6, [-13, 8], 4]]))\n","repo_name":"contactshadab/data-structure-algo-python","sub_path":"data_structure/array/product_sum.py","file_name":"product_sum.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"}
+{"seq_id":"70320576089","text":"contadorJogadas = 0\n\narray = [[\"#\", \"#\", \"#\"], [\"#\", \"#\", \"#\"], [\"#\", \"#\", \"#\"]]\narrayBola = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]\narrayX = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]\n\npossibilidadesX = []\npossibilidadesO = []\n\npertoGanharX = []\npertoGanharO = []\n\nposicoes = []\njogadas = ['11', '00', '02', '22', '20']\n\ndef scanBola():\n print(\"digite a posicao do valor que voce quer inserir a bola O\")\n n1 = int(input())\n n2 = int(input())\n if array[n1][n2] == \"#\":\n array[n1][n2] = \"O\"\n arrayBola[n1][n2] = 1\n else:\n print(\"esse lugar ja tem elemento\")\n scanBola()\n \n\ndef scanX():\n n1 = int(jogadas[0][0])\n n2 = int(jogadas[0][1])\n array[n1][n2] = 'X'\n jogadas.pop(0)\n arrayX[n1][n2] = 1\n\ndef verificarJogadas():\n for i in jogadas:\n if array[int(i[0])][int(i[1])] != '#':\n jogadas.remove(i)\n\ndef prestesGanharX():\n pertoGanharX.clear()\n for i in posicoes:\n hashtag = 0\n for j in i:\n if j == '#':\n hashtag = 1\n if hashtag == 1:\n index = i.index('#')\n contador = 0\n for j in i:\n if j == 'X':\n contador+=1\n if contador == 2 and hashtag == 1:\n value = i[index+3]\n pertoGanharX.append([i[0], i[1], i[2], array[int(value[0])][int(value[1])]])\n jogadas.insert(0, value)\n\ndef prestesGanharO():\n pertoGanharO.clear()\n for i in posicoes:\n hashtag = 0 \n for j in i:\n if j == '#':\n hashtag = 1\n if hashtag == 1:\n index = i.index('#')\n contador = 0\n for j in i:\n if j == 'O':\n contador+=1\n if contador == 2 and hashtag == 1:\n value = i[index+3]\n pertoGanharO.append([i[0], i[1], i[2], array[int(value[0])][int(value[1])]])\n jogadas.insert(0, value)\n\ndef colocarPosicao():\n posicoes.clear()\n posicoes.append([array[0][0], array[1][0], array[2][0], '00', '10', '20'])\n posicoes.append([array[0][1], array[1][1], array[2][1], '01', '11', '21'])\n posicoes.append([array[0][2], array[1][2], array[2][2], '02', '12', '22'])\n\n posicoes.append([array[0][0], array[0][1], array[0][2], '00', '01', '02'])\n posicoes.append([array[1][0], array[1][1], array[1][2], '10', '11', '12'])\n posicoes.append([array[2][0], array[2][1], array[2][2], '20', '21', '22'])\n\n posicoes.append([array[0][0], array[1][1], array[2][2], '00', '11', '22'])\n posicoes.append([array[0][2], array[1][1], array[2][0], '02', '11', '20'])\n\ndef printar():\n for fileira in array:\n print(fileira[0], \"|\", fileira[1], \"|\", fileira[2])\n\ndef verificar(list):\n if list[0][0] and list[1][0] and list[2][0]:\n return True\n elif list[0][1] and list[1][1] and list[2][1]:\n return True\n elif list[0][2] and list[1][2] and list[2][2]:\n return True\n elif list[0][0] and list[0][1] and list[0][2]:\n return True\n elif list[1][0] and list[1][1] and list[1][2]:\n return True\n elif list[2][0] and list[2][1] and list[2][2]:\n return True\n elif list[0][0] and list[1][1] and list[2][2]:\n return True\n elif list[0][2] and list[1][1] and list[2][0]:\n return True\n return False\n\ndef computadorComeca(jogadas):\n contadorJogadas = 0\n while contadorJogadas < 9:\n scanX()\n if contadorJogadas == 0:\n printar()\n contadorJogadas = contadorJogadas + 1\n colocarPosicao()\n if verificar(arrayX):\n printar()\n print(\"X GANHOU\")\n break\n scanBola()\n contadorJogadas = contadorJogadas + 1\n if (contadorJogadas == 9):\n if verificar(arrayX) is False and verificar(arrayBola) is False:\n print('deu velha')\n printar()\n break\n colocarPosicao()\n verificarJogadas()\n prestesGanharO()\n prestesGanharX()\n if verificar(arrayBola):\n printar()\n print(\"BOLA GANHOU\")\n break\n printar()\n jogadas = list(set(jogadas))\n verificarJogadas()\n\ndef jogadorComeca(jogadas):\n contadorJogadas = 0\n while contadorJogadas < 9:\n scanBola()\n contadorJogadas = contadorJogadas + 1\n if (contadorJogadas == 9):\n if verificar(arrayX) is False and verificar(arrayBola) is False:\n print('deu velha')\n printar()\n break\n colocarPosicao()\n verificarJogadas()\n prestesGanharO()\n prestesGanharX()\n if verificar(arrayBola):\n print(\"BOLA GANHOU\")\n printar()\n break\n scanX()\n contadorJogadas = contadorJogadas + 1\n printar()\n colocarPosicao()\n if verificar(arrayX):\n print(\"X GANHOU\")\n printar()\n break\n jogadas = list(set(jogadas))\n verificarJogadas()\n\ndef menu(jogadas):\n print('[1]: Jogador comeca\\n[2]: Computador comeca')\n val = int(input())\n if val == 1:\n jogadorComeca(jogadas)\n elif val == 2:\n computadorComeca(jogadas)\n\nmenu(jogadas)","repo_name":"eduardoddmg/tic-tac-toe-ia","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":5179,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"7739668668","text":"from configuration import Configuration\nimport selenium_bot as bot\n\n\ndef main():\n config = Configuration()\n driver = bot.init_driver(config.browser_name, config.driver_path)\n if bot.execute_actions(driver, config.actions):\n print(\"purchased item\")\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"uwais-ix/selenium_bot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"29614861650","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom functions import l2norm\n\n\nclass SGD:\n def __init__(self, learning_rate=.1, threshold=float('inf')):\n self.lr = learning_rate\n self.threshold = threshold\n self.grad_norm = [[], [], [], [], [], []]\n\n def update(self, params, grads):\n assert len(params) == len(grads), \"The shapes of parameters et gradients do not match !\"\n for i in range(len(params)):\n grad = grads[i]\n norm = l2norm(grad)\n self.grad_norm[i].append(norm)\n if norm > self.threshold:\n grad = grad * self.threshold / norm\n params[i] -= self.lr * grad\n import pprint\n # pprint.pprint(grad)\n # print(np.sum(grad > 1e-3))\n # after the update step, set the gradients to zero\n grads[i][...] = np.zeros_like(grad)\n\n def plot_norm(self, save_path='results/'):\n for i in range(5):\n plt.plot(self.grad_norm[i], label='gradient l2 norm')\n plt.xlabel('steps')\n plt.ylabel('norm')\n plt.legend()\n plt.savefig(save_path+'grad_norm_l2_'+str(i)+'.jpg')\n plt.show()\n","repo_name":"jordane95/MachineLearning","sub_path":"nn/optimizer.py","file_name":"optimizer.py","file_ext":"py","file_size_in_byte":1210,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"28311992521","text":"\"\"\"\n@Time : 2019/12/7 2:38 PM \n@Author : bjjoy2009\nrnn类,实现前向和反向传播,构建rnn模型\n主要参数:\nT_x:cell数\nn_a:每个cell计算后输出->输入到下一层的a的维度\nn_x:每个cell输入x的维度\nn_y:每个cell输出y的维度,也就是多分类类别数\nm:每个batch的大小,也就是每个batch是m个输入序列,每个序列是T_x个输入\n\n总结:每次输入m个字符串(或句子),每个字符串T_x个字符(或单词),每个字符(或单词)是n_x维向量表示,\n每个cell对应一个输出n_y(做文本生成实验n_y=n_x,做文本分类实验n_y是分类数)\n\"\"\"\n\nimport numpy as np\n\n\ndef softmax(x):\n \"\"\"\n softmax函数,减去最大值防止爆炸\n 下面公式等价于 e_x=np.exp(x), e_x/e_x.sum(axis=0)\n :param x:\n :return:\n \"\"\"\n e_x = np.exp(x - np.max(x))\n return e_x / e_x.sum(axis=0)\n\n\ndef smooth(loss, cur_loss):\n \"\"\"\n loss平滑公式,相当于取1000次平均损失\n :param loss:\n :param cur_loss:\n :return:\n \"\"\"\n return loss * 0.999 + cur_loss * 0.001\n\n\ndef print_sample(sample_ix, ix_to_char):\n txt = ''.join(ix_to_char[ix] for ix in sample_ix)\n print('----\\n %s \\n----' % (txt, ))\n\n\ndef get_initial_loss(vocab_size, seq_length):\n \"\"\"\n 初始化损失,个人理解:softmax损失函数L=-sum(yi * log(yi_hat)),i=0,1,...,vocab_size\n 在预测下一个字符实验,下面公式相当于每个cell预测每个字符概率相等,都是1/vocab_size。\n y是vocab_size维向量,第i个位置是标记正确的是1,其余位置是0。\n 有seq_length个cell。\n :param vocab_size: 字符(或单词)数量\n :param seq_length: cell数量\n :return:\n \"\"\"\n return -np.log(1.0/vocab_size)*seq_length\n\n\nclass RNN:\n def __init__(self, epochs=20, n_a=16, alpha=0.01, batch_size=32):\n \"\"\"\n :param epochs: 迭代次数\n :param n_a: 隐藏层节点数\n :param alpha: 梯度下降参数\n :param batch_size: 每个batch大小\n \"\"\"\n self.epochs = epochs\n self.n_a = n_a\n self.alpha = alpha\n self.parameters = {}\n self.loss = 0.0\n self.n_x = 2\n self.n_y = 2\n self.m = batch_size\n\n def initialize_parameters(self, n_a, n_x, n_y):\n \"\"\"\n Initialize parameters with small random values\n :param n_a: 每个cell输出a的维度\n :param n_x: 每个cell输入xi的维度\n :param n_y: 每个cell输出yi的维度\n\n Returns:\n parameters -- python dictionary containing:\n Wax -- Weight matrix multiplying the input, numpy array of shape (n_a, n_x)\n Waa -- Weight matrix multiplying the hidden state, numpy array of shape (n_a, n_a)\n Wya -- Weight matrix relating the hidden-state to the output, numpy array of shape (n_y, n_a)\n b -- Bias, numpy array of shape (n_a, 1)\n by -- Bias relating the hidden-state to the output, numpy array of shape (n_y, 1)\n \"\"\"\n np.random.seed(1)\n Wax = np.random.randn(n_a, n_x)*0.01 # input to hidden\n Waa = np.random.randn(n_a, n_a)*0.01 # hidden to hidden\n Wya = np.random.randn(n_y, n_a)*0.01 # hidden to output\n ba = np.zeros((n_a, 1)) # hidden bias\n by = np.zeros((n_y, 1)) # output bias\n self.parameters = {\"Wax\": Wax, \"Waa\": Waa, \"Wya\": Wya, \"ba\": ba, \"by\": by}\n self.n_x = n_x\n self.n_y = n_y\n\n def rnn_cell_forward(self, xt, a_prev):\n \"\"\"\n Implements a single forward step of the RNN-cell as described in Figure (2)\n\n Arguments:\n xt -- your input data at timestep \"t\", numpy array of shape (n_x, m).\n a_prev -- Hidden state at timestep \"t-1\", numpy array of shape (n_a, m)\n parameters -- python dictionary containing:\n Wax -- Weight matrix multiplying the input, numpy array of shape (n_a, n_x)\n Waa -- Weight matrix multiplying the hidden state, numpy array of shape (n_a, n_a)\n Wya -- Weight matrix relating the hidden-state to the output, numpy array of shape (n_y, n_a)\n ba -- Bias, numpy array of shape (n_a, 1)\n by -- Bias relating the hidden-state to the output, numpy array of shape (n_y, 1)\n Returns:\n a_next -- next hidden state, of shape (n_a, m)\n yt_pred -- prediction at timestep \"t\", numpy array of shape (n_y, m)\n cache -- tuple of values needed for the backward pass, contains (a_next, a_prev, xt, parameters)\n \"\"\"\n\n # Retrieve parameters from \"parameters\"\n Wax = self.parameters[\"Wax\"]\n Waa = self.parameters[\"Waa\"]\n Wya = self.parameters[\"Wya\"]\n ba = self.parameters[\"ba\"]\n by = self.parameters[\"by\"]\n\n # compute next activation state using the formula given above\n a_next = np.tanh(np.dot(Waa, a_prev) + np.dot(Wax, xt) + ba)\n # compute output of the current cell using the formula given above\n yt_pred = softmax(np.dot(Wya, a_next) + by)\n\n # store values you need for backward propagation in cache\n cache = (a_next, a_prev, xt)\n\n return a_next, yt_pred, cache\n\n def rnn_forward(self, x, a_prev):\n \"\"\"\n Arguments:\n x -- Input data for every time-step, of shape (n_x, m, T_x).\n a_prev -- Initial hidden state, of shape (n_a, m)\n parameters -- python dictionary containing:\n Waa -- Weight matrix multiplying the hidden state, numpy array of shape (n_a, n_a)\n Wax -- Weight matrix multiplying the input, numpy array of shape (n_a, n_x)\n Wya -- Weight matrix relating the hidden-state to the output, numpy array of shape (n_y, n_a)\n ba -- Bias numpy array of shape (n_a, 1)\n by -- Bias relating the hidden-state to the output, numpy array of shape (n_y, 1)\n\n Returns:\n a -- Hidden states for every time-step, numpy array of shape (n_a, m, T_x)\n y_pred -- Predictions for every time-step, numpy array of shape (n_y, m, T_x)\n caches -- tuple of values needed for the backward pass, contains (list of caches, x)\n \"\"\"\n\n # Initialize \"caches\" which will contain the list of all caches\n caches = []\n\n # Retrieve dimensions from shapes of x and parameters[\"Wya\"]\n n_x, m, T_x = x.shape\n n_y, n_a = self.parameters[\"Wya\"].shape\n\n # initialize \"a\" and \"y\" with zeros\n a = np.zeros((n_a, m, T_x))\n y_pred = np.zeros((n_y, m, T_x))\n\n # Initialize a_next (≈1 line)\n a_next = a_prev\n\n # loop over all time-steps\n for t in range(T_x):\n # Update next hidden state, compute the prediction, get the cache\n a_next, yt_pred, cache = self.rnn_cell_forward(xt=x[:, :, t], a_prev=a_next)\n # Save the value of the new \"next\" hidden state in a (≈1 line)\n a[:, :, t] = a_next\n # Save the value of the prediction in y (≈1 line)\n y_pred[:, :, t] = yt_pred\n\n # Append \"cache\" to \"caches\" (≈1 line)\n caches.append(cache)\n\n # store values needed for backward propagation in cache\n caches = (caches, x)\n\n return a, y_pred, caches\n\n def compute_loss(self, y_hat, y):\n \"\"\"\n 计算损失函数\n :param y_hat: (n_y, m, T_x),经过rnn正向传播得到的值\n :param y: (n_y, m, T_x),标记的真实值\n :return: loss\n \"\"\"\n n_y, m, T_x = y.shape\n for t in range(T_x):\n self.loss -= 1/m * np.sum(np.multiply(y[:, :, t], np.log(y_hat[:, :, t])))\n return self.loss\n\n def rnn_cell_backward(self, dz, gradients, cache):\n \"\"\"\n Implements the backward pass for the RNN-cell (single time-step).\n\n Arguments:\n dz -- 由这两个公式计算出,cell输出y_hat = softmax(z), z=np.dot(Wya, z) + by\n gradients -- Gradient of loss with respect to next hidden state\n cache -- python dictionary containing useful values (output of rnn_cell_forward())\n\n Returns:\n gradients -- python dictionary containing:\n dx -- Gradients of input data, of shape (n_x, m)\n da_prev -- Gradients of previous hidden state, of shape (n_a, m)\n dWax -- Gradients of input-to-hidden weights, of shape (n_a, n_x)\n dWaa -- Gradients of hidden-to-hidden weights, of shape (n_a, n_a)\n dba -- Gradients of bias vector, of shape (n_a, 1)\n \"\"\"\n\n # Retrieve values from cache\n (a_next, a_prev, xt) = cache\n\n # Retrieve values from parameters\n Wax = self.parameters[\"Wax\"]\n Waa = self.parameters[\"Waa\"]\n Wya = self.parameters[\"Wya\"]\n ba = self.parameters[\"ba\"]\n by = self.parameters[\"by\"]\n\n gradients['dWya'] += np.dot(dz, a_next.T)\n gradients['dby'] += np.sum(dz, axis=1, keepdims=True)\n # cell的da由两部分组成,\n da = np.dot(Wya.T, dz) + gradients['da_next']\n\n # compute the gradient of tanh with respect to a_next (≈1 line)\n dtanh = np.multiply(da, 1 - np.square(a_next))\n # compute the gradient of the loss with respect to Wax (≈2 lines)\n gradients['dxt'] = np.dot(Wax.T, dtanh)\n gradients['dWax'] += np.dot(dtanh, xt.T)\n\n # compute the gradient with respect to Waa (≈2 lines)\n gradients['dWaa'] += np.dot(dtanh, a_prev.T)\n\n # compute the gradient with respect to b (≈1 line)\n gradients['dba'] += np.sum(dtanh, axis=1, keepdims=True)\n\n # 前一个cell的da_next\n gradients['da_next'] = np.dot(Waa.T, dtanh)\n\n return gradients\n\n def rnn_backward(self, y, y_hat, caches):\n \"\"\"\n Implement the backward pass for a RNN over an entire sequence of input data.\n :param y: label,shape(n_y, m, T_x)\n :param y_hat: softmax rnn forward output ,shape(n_y, m, T_x)\n :param caches: tuple containing information from the forward pass (rnn_forward)\n\n Returns:\n gradients -- python dictionary containing:\n dx -- Gradient w.r.t. the input data, numpy-array of shape (n_x, m, T_x)\n da0 -- Gradient w.r.t the initial hidden state, numpy-array of shape (n_a, m)\n dWax -- Gradient w.r.t the input's weight matrix, numpy-array of shape (n_a, n_x)\n dWaa -- Gradient w.r.t the hidden state's weight matrix, numpy-arrayof shape (n_a, n_a)\n dba -- Gradient w.r.t the bias, of shape (n_a, 1)\n dWya -- Gradient w.r.t the output's state's weight matrix, numpy-arrayof shape (n_y, n_a)\n dby -- Gradient w.r.t the output's bias, of shape (n_y, 1)\n \"\"\"\n\n # Retrieve values from the first cache (t=1) of caches\n (caches, x) = caches\n n_x, m, T_x = x.shape\n # initialize the gradients with the right sizes\n gradients = {}\n dx = np.zeros((n_x, m, T_x))\n gradients['dWax'] = np.zeros((self.n_a, self.n_x))\n gradients['dWaa'] = np.zeros((self.n_a, self.n_a))\n gradients['dba'] = np.zeros((self.n_a, 1))\n gradients['da_next'] = np.zeros((self.n_a, self.m))\n gradients['dWya'] = np.zeros((self.n_y, self.n_a))\n gradients['dby'] = np.zeros((self.n_y, 1))\n dz = y_hat - y # y_hat=softmax(z), dz=dl/dy_hat * dy_hat/dz\n\n # Loop through all the time steps\n for t in reversed(range(T_x)):\n gradients = self.rnn_cell_backward(dz=dz[:, :, t], gradients=gradients, cache=caches[t])\n dx[:, :, t] = gradients[\"dxt\"]\n\n return gradients\n\n def update_parameters(self, gradients):\n \"\"\"\n 梯度下降\n :param gradients:\n :return:\n \"\"\"\n self.parameters['Wax'] += -self.alpha * gradients['dWax']\n self.parameters['Waa'] += -self.alpha * gradients['dWaa']\n self.parameters['Wya'] += -self.alpha * gradients['dWya']\n self.parameters['ba'] += -self.alpha * gradients['dba']\n self.parameters['by'] += -self.alpha * gradients['dby']\n\n def clip(self, gradients, maxValue=5):\n \"\"\"\n Clips the gradients' values between minimum and maximum.\n\n Arguments:\n gradients -- a dictionary containing the gradients \"dWaa\", \"dWax\", \"dWya\", \"db\", \"dby\"\n maxValue -- everything above this number is set to this number, and everything less than -maxValue is set to -maxValue\n\n Returns:\n gradients -- a dictionary with the clipped gradients.\n \"\"\"\n\n dWaa, dWax, dWya, dba, dby = gradients['dWaa'], gradients['dWax'], gradients['dWya'], gradients['dba'], gradients['dby']\n\n # clip to mitigate exploding gradients, loop over [dWax, dWaa, dWya, db, dby]. (≈2 lines)\n for gradient in [dWax, dWaa, dWya, dba, dby]:\n np.clip(gradient, -1*maxValue, maxValue, out=gradient)\n\n gradients = {\"dWaa\": dWaa, \"dWax\": dWax, \"dWya\": dWya, \"dba\": dba, \"dby\": dby}\n\n return gradients\n\n def optimize(self, X, Y, a_prev):\n \"\"\"\n Execute one step of the optimization to train the model.\n\n Arguments:\n X -- 输入数据序列,维度(n_x, m, T_x),n_x是每个step输入xi的维度,m是一个batch数据量,T_x一个序列长度\n Y -- 每个输入xi对应的输出yi (n_y, m, T_x),n_y是输出向量(分类数,只有一位是1)\n a_prev -- previous hidden state.\n\n Returns:\n loss -- value of the loss function (cross-entropy)\n gradients -- python dictionary containing:\n dWax -- Gradients of input-to-hidden weights, of shape (n_a, n_x)\n dWaa -- Gradients of hidden-to-hidden weights, of shape (n_a, n_a)\n dWya -- Gradients of hidden-to-output weights, of shape (n_y, n_a)\n db -- Gradients of bias vector, of shape (n_a, 1)\n dby -- Gradients of output bias vector, of shape (n_y, 1)\n a[len(X)-1] -- the last hidden state, of shape (n_a, 1)\n \"\"\"\n\n # 正向传播\n a, y_pred, caches = self.rnn_forward(X, a_prev)\n # 计算损失\n loss = self.compute_loss(y_hat=y_pred, y=Y)\n\n gradients = self.rnn_backward(Y, y_pred, caches)\n\n gradients = self.clip(gradients=gradients, maxValue=5)\n\n self.update_parameters(gradients)\n\n return loss, gradients, a[:, :, -1]\n","repo_name":"ConstellationBJUT/Coursera-DL-Study-Notes","sub_path":"class5_week1_sequence/rnn/rnn.py","file_name":"rnn.py","file_ext":"py","file_size_in_byte":14608,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"31"}
+{"seq_id":"8100825467","text":"import os\nimport requests\nfrom bs4 import BeautifulSoup\n\n\ndef scrapproduit(url,nomDeFichier):\n r = requests.get(url)\n html = r.text\n soup = BeautifulSoup(html, 'lxml')\n imgProduct = soup.find('div', {\"class\": \"item active\"})\n img = imgProduct.find('img')\n src = img.get('src')\n\n image_url = \"https://books.toscrape.com/\" + src\n titleProduct = soup.find('li', {\"class\": \"active\"}).get_text()\n descriptionProduct = soup.find('p',{\"class\": \"\"})\n if descriptionProduct:\n descriptionProduct = soup.find('p', {\"class\": \"\"}).get_text()\n else:\n descriptionProduct=\"\"\n\n tableInfo = soup.find('table',{\"class\": \"table table-striped\"})\n rows=list()\n for row in tableInfo.findAll(\"tr\"):\n rows.append(row)\n UPC = rows[0].find('td').get_text()\n price_including_tax=rows[3].find('td').get_text()\n price_excluding_tax=rows[2].find('td').get_text()\n number_available=rows[5].find('td').get_text()\n tableInfo1 = soup.find('ul',{\"class\": \"breadcrumb\"})\n aFind = tableInfo1.findAll('a')\n category = aFind[2].string\n if not os.path.isdir('csv'):\n os.mkdir('csv')\n with open('csv/'+nomDeFichier+'.csv','a') as result:\n #result.write('product_page_url,upc,title,price_including_tax,price_excluding_tax,number_available,product_description,category,review_rating,image_url \\n')\n result.write(url+','+UPC+','+titleProduct+','+price_including_tax+','+price_excluding_tax+','+number_available+','+descriptionProduct+','+category+','+'0'+','+image_url+'\\n')\n downloadImage(image_url,titleProduct,nomDeFichier)\n\ndef downloadImage(urlImage,NomProduit,catgorie):\n\n image_url = urlImage\n if not os.path.isdir(catgorie+'Images'):\n os.mkdir(catgorie+'Images')\n path = catgorie+'Images'+'/'+NomProduit+\".jpg\"\n r = requests.get(image_url, stream=True)\n if r.status_code == 200:\n with open(path, 'wb') as f:\n for chunk in r.iter_content(1024):\n f.write(chunk)\n\ndef scarpProduitParCategorie(urlCat,NomDeCSV):\n r = requests.get(urlCat)\n html = r.text\n soup = BeautifulSoup(html)\n NbrDelivre = soup.find('form', {\"class\": \"form-horizontal\"}).find('strong').get_text()\n nomfichier = NomDeCSV\n\n if int(NbrDelivre) <= 20:\n linkProduit = soup.find_all('div', {\"class\": \"image_container\"})\n for i in linkProduit:\n linkp = i.find('a').get('href')\n linkp1 = \"https://books.toscrape.com/catalogue/\" + linkp[9:len(linkp)]\n scrapproduit(linkp1,nomfichier)\n else:\n codePage = soup.find_all('li', {\"class\": \"current\"})\n textNbredePage = codePage[0].get_text()\n nombreDepage = int(textNbredePage.lstrip()[10:11])\n for j in range(1, nombreDepage + 1):\n j1 = str(j)\n url2 = urlCat + \"page-\" + j1 + \".html\"\n r1 = requests.get(url2)\n html1 = r1.text\n soup2 = BeautifulSoup(html1)\n linkProduit2 = soup2.find_all('div', {\"class\": \"image_container\"})\n for i1 in linkProduit2:\n link = i1.find('a').get('href')\n linkProduitdePlusieurPage = \"https://books.toscrape.com/catalogue/\" + link[9:len(link)]\n scrapproduit(linkProduitdePlusieurPage,nomfichier)","repo_name":"massouathyassine/p2","sub_path":"fonction.py","file_name":"fonction.py","file_ext":"py","file_size_in_byte":3239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"37071243151","text":"import colored_traceback.always\n\nfrom sandbox.rocky.tf.algos.ppo import PPO\nfrom sandbox.rocky.tf.algos.vpg import VPG\n\nfrom rllab.baselines.linear_feature_baseline import LinearFeatureBaseline, LinearFeatureBaselineTranspose\nfrom rllab.envs.gym_env import GymEnv\nfrom sandbox.rocky.tf.envs.base import TfEnv\nfrom rllab.envs.normalized_env import normalize\nfrom rllab.misc.instrument import run_experiment_lite\nfrom sandbox.rocky.tf.policies.gaussian_mlp_policy import SimpleGaussianMLPPolicy, GaussianMLPPolicy, GaussianMLP2Policy\nfrom sandbox.rocky.tf.policies.gaussian_conv_policy import GaussianConvPolicy\nimport tensorflow as tf\ntf.enable_eager_execution()\nfrom OverApprox.relu_approximations import relu_tanh, linearized_tanh\n\n\ndef run_task(*_):\n # Please note that different environments with different action spaces may require different\n # policies. For example with a Box action space, a GaussianMLPPolicy works, but for a Discrete\n # action space may need to use a CategoricalMLPPolicy (see the trpo_gym_cartpole.py example)\n env = TfEnv(GymEnv(\"MyPendulum-v1\", record_video=False))\n #\n policy = GaussianConvPolicy(\n name=\"policy\",\n env_spec=env.spec,\n conv_filters = [3], # how many conv layers. e.g. this is one layer with 3 fitlers (I think)\n conv_filter_sizes = [5, 5, 5],\n conv_strides = [3, 3, 3],\n conv_pads = ['SAME', 'SAME', 'SAME'],\n # The neural network policy should have two hidden layers, each with 32 hidden units.\n hidden_sizes= (16,4), #(128, 128, 128, 128, 128, 128),\n hidden_nonlinearity=tf.nn.relu, #linearized_tanh\n output_nonlinearity=None,\n )\n #\n baseline = LinearFeatureBaseline(env_spec=env.spec)\n #\n algo = PPO(\n env=env,\n policy=policy,\n baseline=baseline,\n batch_size=5, #4000,\n max_path_length=env.horizon,\n n_itr=2, #1000,\n discount=0.99,\n step_size=0.0075, # 0.01\n # Uncomment both lines (this and the plot parameter below) to enable plotting\n # plot=True,\n )\n algo.train()\n\n# profiling code\n# import cProfile, pstats, io\n# pr = cProfile.Profile()\n# pr.enable()\nrun_experiment_lite(\n run_task,\n # Number of parallel workers for sampling\n n_parallel=5,\n # Only keep the snapshot parameters for the last iteration\n snapshot_mode=\"last\",\n exp_name=\"convnet_ppo_\"+str(np.ceil(np.random.rand()*1000)),\n # Specifies the seed for the experiment. If this is not provided, a random seed\n # will be used\n seed=0,\n # plot=True,\n)\n# pr.disable()\n# s = io.StringIO()\n# sortby = 'cumulative'\n# ps = pstats.Stats(pr, stream=s).sort_stats(sortby)\n# ps.print_stats()\n# print(s.getvalue())","repo_name":"chelseas/OVERT","sub_path":"depreciated/Pre_Amir_files/train_pendulum_from_images.py","file_name":"train_pendulum_from_images.py","file_ext":"py","file_size_in_byte":2722,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"4293458480","text":"class Cadena:\r\n def __init__(self, cadena):\r\n self.cadena= cadena\r\n self.__listaMinuscula= [\"a\",\"b\",\"c\",\"d\",\"e\",\"f\",\"g\",\"h\",\"i\",\"j\",\"k\",\"l\",\"m\",\"n\",\"o\",\"p\",\"q\",\r\n \"r\",\"s\",\"t\",\"u\",\"v\",\"w\",\"x\",\"y\",\"z\"]\r\n self.__listaMayuscula= [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\", \"P\", \"Q\",\r\n \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\", \"Z\"]\r\n \r\n def fin_encontrar(self,buscar):\r\n for i,v in enumerate(self.cadena):\r\n if v==buscar:\r\n return i #\"ERROR\"-->Como busca posición debe ir [i], porque [v] es valor\r\n return -1\r\ncadena= input(\"Ingrese un cadena: \")\r\nc=Cadena(cadena)\r\nbuscar= input(\"Ingrese el caracter a buscar: \")\r\nprint(c.fin_encontrar(buscar))","repo_name":"Evelyn-agv/Ejercicios.Extra-POO","sub_path":"examen/pregunta 1.py","file_name":"pregunta 1.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"pms","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"39124883127","text":"import re\n\ndef parse_line(line):\n parent = re.search(r'^(\\w+ \\w+)', line).group()\n children = re.findall(r'(\\d+) (\\w+ \\w+)', line)\n rule = {}\n for nbr_of, child in children:\n rule[child] = int(nbr_of)\n return {parent:rule}\n\ndef may_contain(color, parent, rules):\n if color in rules[parent]:\n return True\n for child in rules[parent]:\n if may_contain(color, child, rules):\n return True\n return False\n\ndef nbr_of_bags_within(parent, rules):\n count = 0\n for child, nbr_of in rules[parent].items():\n count += nbr_of * (1 + nbr_of_bags_within(child, rules))\n return count\n\nwith open('input.txt', 'r') as f:\n data = f.read()\n\nrules = {}\nfor line in data.split('\\n'):\n rules |= parse_line(line)\n\nsum1 = sum(may_contain('shiny gold', r, rules) for r in rules)\nsum2 = nbr_of_bags_within('shiny gold', rules)\n\nprint(\"Part 1: \", sum1)\nprint(\"Part 2: \", sum2)\n\n#Part 1: 238\n#Part 2: 82930\n","repo_name":"yoggi-yalla/aoc2020","sub_path":"07/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"15512211081","text":"\"\"\"\nAnalysis of motor movement\nInput is csv file (motorFile) output is also csv file\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\n\nfrom matplotlib import pyplot as plt\n\n# making a mini dataframe with fake data\n# fake_motor_data = {'command':[0,10,15,-5,-10,-15,0], 'time':[0,1,2,3,4,5,6]}\n# motor_df = pd.DataFrame(fake_motor_data, columns = ['command','time' ])\n# print(motor_df)\n\n\ndef motor_direction(commandfile):\n \"\"\"\n Determines the direction (clockwise/counterclockwise)\n of visual stimuli delivered using a command signal\n\n :param pd.DataFrame commandfile:\n :return:\n \"\"\"\n # save the array containing commandvalues as a new column\n command_column = commandfile['command']\n print(command_column)\n cmd = command_column.values\n print(cmd)\n\n # calculate the direction by determining the change from current command to the next command\n\n direction = np.zeros((cmd.size - 1)) # -1 because diff\n direction[cmd[:-1] < cmd[1:]] = 1\n direction[cmd[:-1] > cmd[1:]] = -1\n print(direction)\n\n # add a time array\n length_direction_array = np.size(direction)\n print(\"length of direction array is:\", length_direction_array)\n time = np.arange(length_direction_array)\n print(time)\n\n # make a dataframe of all the data\n real_motor_df = pd.DataFrame({\"command\": cmd[:-1],\n \"direction\": direction,\n \"time\": time})\n\n plt.plot(real_motor_df['command'])\n plt.plot(real_motor_df['direction'])\n plt.show()\n\n print(real_motor_df)\n\n real_motor_df.to_csv(\"direction_motor.csv\", sep=\",\")\n return real_motor_df\n\n\n# fake test data\ntest_cmd_df = pd.DataFrame({'command': np.array([0, 1, 2, 3, 7, -7, 8, 9, -2, -20, -25])})\n\n\n# actual data\nif __name__ == '__main__':\n command_df = pd.read_csv('studentCourse_command.csv')\n motor_direction(command_df)\n","repo_name":"Timothysit/swc_invivo_analysis","sub_path":"motor.py","file_name":"motor.py","file_ext":"py","file_size_in_byte":1882,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"28447291362","text":"import re\nimport uvicore\nimport inspect\nimport asyncio\nfrom uvicore.typing import Dict, List, Any, Union, Callable, Tuple\nfrom uvicore.support.dumper import dump, dd\nfrom types import SimpleNamespace as obj\nfrom collections import namedtuple\nfrom uvicore.contracts import Dispatcher as DispatcherInterface\nfrom uvicore.support import module\nfrom uvicore.support.concurrency import run_in_threadpool\n\n#from uvicore.contracts import Event as EventInterface\n# from prettyprinter import pretty_call, register_pretty\n# class EventInfo(EventInterface):\n# \"\"\"Event Definition\"\"\"\n# # These class level properties for for type annotations only.\n# # They do not restrict of define valid properties like a dataclass would.\n# # This is still a fully dynamic SuperDict!\n# name: str\n# description: str\n# dynamic: bool\n# is_async: bool\n# options: Dict\n\n\n# @register_pretty(EventInfo)\n# def pretty_entity(value, ctx):\n# \"\"\"Custom pretty printer for my SuperDict\"\"\"\n# # This printer removes the class name uvicore.types.Dict and makes it print\n# # with a regular {. This really cleans up the output!\n\n# #return pretty_call(ctx, 'Dict', **value)\n# #return pretty_call(ctx, 'Dict', value.to_dict()) # Does show nested dicts as SuperDicts\n# return pretty_call(ctx, 'EventInfo', dict(**value))\n\n@uvicore.service('uvicore.events.dispatcher.Dispatcher',\n aliases=['Dispatcher', 'dispatcher', 'Event', 'event'],\n singleton=True,\n)\nclass Dispatcher(DispatcherInterface):\n \"\"\"Event Dispatcher private class.\n\n Do not import from this location.\n Use the uvicore.events singleton global instead.\"\"\"\n\n # @property\n # def events(self) -> Dict[str, EventInfo]:\n # \"\"\"Dictionary of all registered events in uvicore and all packages\"\"\"\n # return self._events\n\n @property\n def listeners(self) -> Dict[str, List]:\n \"\"\"Dictionary of all listeners for each event\"\"\"\n return self._listeners\n\n @property\n def wildcards(self) -> List:\n \"\"\"List of all wildcard listeners\"\"\"\n return self._wildcards\n\n def __init__(self) -> None:\n self._events: Dict[str, EventInfo] = Dict()\n self._listeners: Dict[str, List] = Dict()\n self._wildcards: List = []\n\n @property\n def registered_events(self) -> List:\n \"\"\"Get all registered events from IOC bindings and manual registrations\"\"\"\n # FIXME, need to merge in manual registrations, which I don't have yet\n event_bindings = uvicore.ioc.binding(type='event')\n events = []\n for binding in event_bindings.values():\n events.append({\n 'name': binding.path,\n 'description': binding.object.__doc__,\n 'is_async': binding.object.is_async,\n })\n return events\n\n\n # def event(self, event: Union[str, Callable]) -> EventInfo:\n # \"\"\"Get one known (pre-registered) EventInfo by str name or class\"\"\"\n # if type(event) == str:\n # # Get event by a string name\n # name = event\n # else:\n # # Get event by a class, use the class name as the event string name\n # #name = str(event.__class__).split(\"'\")[1]\n # name = event.name\n # if name in self.events:\n # return self.events.get(name)\n # else:\n # # This event is NOT registered, but we still want it to work\n # # because of all the dynamic events like ORM makes\n # # So create a fake event meta\n # return Dict({\n # 'name': name\n # })\n\n @property\n def expanded_sorted_listeners(self) -> List:\n \"\"\"Get all listeners with expanded wildcards, sorted by priority ASC\"\"\"\n\n # WELL, this doesn't really work because it only merged wildcards into\n # events that are already explicitly listened too\n # like uvicore.foundation.events.app.* only shows up under Booted\n # not Registered because no other event has explicitly listened to\n # Registered. I could look up self.registered_events as well\n # but this is really only for the CLI event listeners, so maybe Ill skip\n\n listeners = {}\n for event, listener in self.listeners.items():\n if '*' not in event:\n listeners[event] = listener\n\n for wildcard in self.wildcards:\n if re.search(wildcard, event):\n if event not in listeners:\n listeners[event] = []\n listeners[event].extend(self.listeners[wildcard])\n break\n\n return listeners\n\n def event_listeners(self, event: str) -> List:\n \"\"\"Get all listeners for an event including wildcard, sorted by priority ASC\"\"\"\n\n # Get all listeners for this particular event\n listeners = [x for x in self.listeners.get(event) or []]\n\n # Add in wildcard events\n for wildcard in self.wildcards:\n regex = wildcard\n if re.search(regex, event):\n listeners.extend(self.listeners[wildcard])\n\n # Sort listeners by priority\n listeners = sorted(listeners, key = lambda i: i['priority'])\n\n # Get just the listener handler strings/methods as List\n handlers = [x['listener'] for x in listeners]\n\n # Return these event handlers\n return handlers\n\n def listen(self, events: Union[str, List], listener: Union[str, Callable] = None, *, priority: int = 50) -> None:\n \"\"\"Decorator or method to append a listener (string or Callable) callback to one or more events.\"\"\"\n def handle(events, listener):\n if type(events) != list: events = [events]\n\n # Expand all wildcards\n for event in events:\n # Get the string name of this event\n if type(event) != str: event = event.name\n\n # If event not registered yet, ensure empty []\n if event not in self.listeners:\n self._listeners[event] = []\n\n # Append new listener to event\n self._listeners[event].append({'listener': listener, 'priority': priority})\n\n # If event contains a *, add it to our wildcard list for use later\n if '*' in event:\n self._wildcards.append(event)\n\n # Method access\n if listener: return handle(events, listener)\n\n # Decorator access\n def decorator(func):\n handle(events, func)\n return func\n return decorator\n\n def handle(self, events: Union[str, List], listener: Union[str, Callable] = None, *, priority: int = 50) -> None:\n \"\"\"Decorator or method to append a listener (string or Callable) callback to one or more events. Alias to listen().\"\"\"\n return self.listen(events, listener)\n\n def subscribe(self, listener: Union[str, Callable]) -> None:\n \"\"\"Add a subscription class which handles both registration and listener callbacks\"\"\"\n try:\n if type(listener) == str:\n module.load(listener).object().subscribe(uvicore.events)\n else:\n listener.subscribe(uvicore.events)\n except ModuleNotFoundError:\n pass\n\n def dispatch(self, event: Union[str, Callable], payload: Dict = {}) -> None:\n \"\"\"Fire off an event and run all listener callbacks\"\"\"\n\n # Get dispatcher method for this event\n dispatch_method, params = self._get_dispatcher(event, payload, is_async=False)\n\n # Dispatch this event\n dispatch_method(*params)\n\n async def dispatch_async(self, event: Union[str, Callable], payload: Dict = {}) -> None:\n \"\"\"Async fire off an event and run all async listener callbacks\"\"\"\n\n # Get dispatcher method for this event\n dispatch_method, params = self._get_dispatcher(event, payload, is_async=True)\n\n # Dispatch this event\n await dispatch_method(*params)\n\n async def codispatch(self, event: Union[str, Callable], payload: Dict = {}) -> None:\n \"\"\"Alias for dispatch_async().\"\"\"\n return await self.dispatch_async(event, payload)\n\n def _dispatch(self, event: Union[str, Callable], payload: Dict = {}) -> None:\n \"\"\"Dispatch an event by fireing off all listeners/handlers\"\"\"\n (event, handlers) = self._get_handlers(event, payload)\n for handler in handlers:\n handler(event)\n\n async def _dispatch_async(self, event: Union[str, Callable], payload: Dict = {}) -> None:\n \"\"\"Dispatch an event by fireing off all listeners/handlers\"\"\"\n (payload, handlers) = self._get_handlers(event, payload)\n for handler in handlers:\n if asyncio.iscoroutinefunction(handler) or asyncio.iscoroutinefunction(handler.__call__):\n await handler(event)\n else:\n # Listener/handler is NOT async but was called from await, lets throw in thread pool\n await run_in_threadpool(handler, event)\n\n def _get_dispatcher(self, event: Union[str, Callable], payload: Dict = {}, is_async: bool = False) -> Tuple:\n \"\"\"Get dispatcher method for this event\"\"\"\n # This function determines the proper dispatching method for this event.\n # If event is a string, we use self._dispatch\n # If event is a class we call that classes .dispatch method\n method = None\n params = [event, payload]\n if type(event) == str:\n if '-' in event or '{' in event:\n # String event (we know because classes can't have dashes or {.\n # This is how we name dynamic string based events like per model or table...\n method = self._dispatch_async if is_async else self.dispatch\n else:\n # See if string event has a matching class. If so, import and dispatch it\n try:\n event = module.load(event).object(**payload)\n params = []\n method = event.dispatch_async if is_async else event.dispatch\n except:\n # No class found for this string. This is OK because events can\n # be strings without matching classes. Dispatch it anyway\n method = self._dispatch_async if is_async else self._dispatch\n else:\n # Event is an event class INSTANCE. Call the actual classes dispatch method\n # in case the user overrode it, we still execute it\n params = []\n method = event.dispatch_async if is_async else event.dispatch\n\n # Return tuple of dispatcher method and params\n return (method, params)\n\n def _get_handlers(self, event: Union[str, Callable], payload: Dict = {}) -> Tuple:\n \"\"\"Get all listener/handlers and fix up payload\"\"\"\n # Get event by string name or class inspection\n #event_meta = self.event(event)\n\n if type(event) == str:\n # String based event, merge payload with default event\n event = Dict(payload).merge({\n 'name': event,\n 'description': 'String based dynamic event.'\n })\n\n # Payload default is a SuperDict\n #payload = Dict(payload)\n\n # If event is a class, payload is the class instance\n #if type(event) != str: payload = event\n\n # Get listener methods (dynamic import if string)\n listeners = self.event_listeners(event.name)\n handlers = []\n for handler in listeners:\n if type(handler) == str:\n # handler is a string to a listener class with handle() method\n try:\n #cls = module.load(listener).object(uvicore.app)\n cls = module.load(handler).object()\n handlers.append(cls)\n #handlers.append(cls.handle)\n except ModuleNotFoundError:\n # Bad handler, handler will never fire\n continue\n else:\n # handler is a Class\n if inspect.isclass(handler): handler = handler()\n\n # Listener is a Callable (if was a class, NOW its callable)\n handlers.append(handler)\n\n # Return tuple of event and handlers\n #return (event_meta, payload, handlers)\n return (event, handlers)\n\n\n# IoC Class Instance\n# **Not meant to be imported from here**. Use the uvicore.events singleton global instead.\n# Only here because uvicore bootstrap needs to import it without a service provider.\n# By using the default bind and make feature of the IoC we can swap the implimentation\n# at a high bootstrap level using our app configs 'bindings' dictionary.\n# The only two classes that do this are Application and the event Dispatcher.\n#Dispatcher: _Dispatcher = uvicore.ioc.make('Dispatcher', _Dispatcher, singleton=True, aliases=['dispatcher', 'Event', 'event', 'Events', 'events'])\n","repo_name":"uvicore/framework","sub_path":"uvicore/events/dispatcher.py","file_name":"dispatcher.py","file_ext":"py","file_size_in_byte":13029,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"31"}
+{"seq_id":"7835970589","text":"counter = 0\nanswersList = []\n\nwith open('input.txt') as file:\n data = file.read().split('\\n\\n')\n for line in data:\n line = line.split()\n answersSets = []\n for answer in line:\n answersSets.append(set(answer))\n answersList.append(answersSets)\n\nfor answers in answersList:\n counter += len(set.intersection(*answers))\n\nprint(counter)","repo_name":"Kijek3/AoC-2020","sub_path":"6/script2_intersection.py","file_name":"script2_intersection.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"13687896201","text":"import heapq\nimport numpy as np\n\nfrom umap import UMAP\n\nfrom bertopic import BERTopic\nfrom bertopic.vectorizers import ClassTfidfTransformer\n\nfrom sklearn.feature_extraction.text import CountVectorizer\n\nfrom utils.tools import get_score\nfrom topic.segmenter import SegmenterInterface\n\n\nclass BERTopicModel(SegmenterInterface):\n def __init__(self, max_len, doc_len_threshold, n_gram_range=(3, 5)):\n self.max_len = max_len\n self.doc_len_threshold = doc_len_threshold\n\n self.umap_model = UMAP(random_state=42)\n self.vectorizer_model = CountVectorizer(stop_words=\"english\")\n self.ctfidf_model = ClassTfidfTransformer(reduce_frequent_words=True)\n self.topic_model = BERTopic(\n nr_topics=\"auto\",\n umap_model=self.umap_model,\n vectorizer_model=self.vectorizer_model,\n ctfidf_model=self.ctfidf_model,\n n_gram_range=n_gram_range)\n self.subtopic_model = BERTopic(\n nr_topics=None, \n vectorizer_model=self.vectorizer_model,\n ctfidf_model=self.ctfidf_model, \n n_gram_range=n_gram_range)\n\n def get_topic_df(self, data):\n \"\"\"\n Returns the topics and their information for the given data.\n\n Args:\n data: A list of strings representing the input data.\n\n Returns:\n A dataframe containing the topics for each turn and its specific information.\n \"\"\"\n topics, _ = self.topic_model.fit_transform(data)\n try:\n _ = self.topic_model.reduce_outliers(data, topics)\n except ValueError:\n pass\n topic_df = self.topic_model.get_document_info(data)\n return topic_df\n \n def get_subtopic_df(self, data):\n \"\"\"\n Returns the subtopics and their information for the give topic turns.\n\n Args:\n data: A list of strings representing the topic.\n\n Returns:\n A dataframe containing the subtopics for each turn and its specific information.\n \"\"\"\n self.subtopic_model.fit_transform(data)\n subtopic_df = self.subtopic_model.get_document_info(data)\n return subtopic_df\n \n def get_topic_len(self, df):\n return df.groupby('Topic')['utter_speaker'].apply(lambda x: sum(len(t.split()) for t in x)).sort_values(ascending=False)\n\n def iterative_recluster(self, df):\n skipped_idx = []\n topic_len = self.get_topic_len(df)\n exc_idx = topic_len[topic_len > self.max_len].index.tolist()\n \n while exc_idx and exc_idx != skipped_idx:\n for idx in exc_idx:\n if idx not in skipped_idx:\n topic_df = df[df['Topic'] == idx]\n text = topic_df['Document'].values.tolist()\n try:\n subtopic_df = self.get_subtopic_df(text)\n subtopics = subtopic_df['Topic'].unique().tolist()\n except (TypeError, ValueError) as e:\n skipped_idx.append(idx)\n continue\n if len(subtopics) == 1:\n skipped_idx.append(idx)\n else:\n subtopic_df.index = topic_df.index\n subtopic_df['Topic'] = subtopic_df['Topic'] + topic_len.index.max() + 2\n df.loc[subtopic_df.index, 'Topic'] = subtopic_df['Topic']\n topic_len = self.get_topic_len(df)\n exc_idx = topic_len[topic_len > self.max_len].index.tolist()\n break\n \n for topic in exc_idx:\n rows = df[df['Topic'] == topic]\n subtopics = []\n subtopic_len = 0\n subtopic_buffer = []\n \n for idx, row in rows.iterrows():\n # compute score for the row\n score = get_score(row['Document'])\n \n # if adding the row to the subtopic buffer exceeds the max_len, \n # assign a new topic to the subtopic buffer and add it to the dataframe\n if subtopic_len + score > self.max_len:\n new_topic = topic_len.index.max() + 2\n df.loc[subtopic_buffer, 'Topic'] = new_topic\n subtopics.append(new_topic)\n subtopic_buffer = [idx]\n subtopic_len = score\n else:\n subtopic_buffer.append(idx)\n subtopic_len += score\n \n # assign a new topic to the final subtopic buffer if it exists\n if subtopic_buffer:\n new_topic = topic_len.index.max() + 2\n df.loc[subtopic_buffer, 'Topic'] = new_topic\n subtopics.append(new_topic)\n\n return df\n \n def remove_noise_topic(self, df):\n # iterate through each topic and compute average document length\n for topic in df['Topic'].unique():\n topic_docs = df[df['Topic'] == topic]['Document']\n \n # remove stopwords from documents and compute their length\n doc_lengths = [get_score(doc) for doc in topic_docs]\n \n # compute average document length\n avg_doc_len = sum(doc_lengths) / len(doc_lengths)\n \n # remove rows belonging to topic if average document length is below threshold\n if avg_doc_len < self.doc_len_threshold:\n df = df[df['Topic'] != topic]\n \n return df\n \n def rearrange_topic_value(self, df):\n unique_topics = df['Topic'].unique()\n topic_map = {topic: idx for idx, topic in enumerate(sorted(unique_topics))}\n df['Topic'] = df['Topic'].map(topic_map)\n\n return df\n \n def segmentize(self, input_data, **kwargs):\n df = self.get_topic_df(input_data['utter'])\n df['utter_speaker'] = input_data['utter_speaker']\n\n df = self.iterative_recluster(df)\n \n remove_noise = kwargs.get('remove_noise', True)\n if remove_noise:\n df = self.remove_noise_topic(df)\n df = self.rearrange_topic_value(df)\n\n topics = df['Topic'].unique() # get unique topics in the dataframe\n topic_order = [] # initialize list to store the order of topics\n\n # iterate over rows in the dataframe to determine topic order\n for _, row in df.iterrows():\n if row['Topic'] not in topic_order: # if topic not yet in order list, add it\n topic_order.append(row['Topic'])\n\n # create list of texts joined by '\\n' for each unique topic in the order determined above\n texts = []\n for topic in topic_order:\n topic_df = df[df['Topic']==topic]\n text = '\\n'.join(topic_df['utter_speaker'].tolist())\n texts.append(text)\n \n return texts\n","repo_name":"faizghifari/summ-twice","sub_path":"topic/bertopic.py","file_name":"bertopic.py","file_ext":"py","file_size_in_byte":6896,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"44473797658","text":"class Node(object):\n def __init__(self, data, next=None):\n self.data = data\n self.next = next\n\n\nclass Stack(object):\n def __init__(self, top=None):\n self.top = top\n\n def push(self, data):\n self.top = Node(data, self.top)\n\n def pop(self):\n if self.top is None:\n return None\n data = self.top.data\n self.top = self.top.next\n return data\n\n def peek(self):\n return self.top.data if self.top is not None else None\n\n def is_empty(self):\n return self.peek() is None\n\n\nclass MyStack(Stack):\n def sort(self):\n buff = MyStack()\n while not self.is_empty():\n temp = self.pop()\n if buff.is_empty() or temp >= buff.peek():\n buff.push(temp)\n else:\n while not buff.is_empty() and temp < buff.peek():\n self.push(buff.pop())\n buff.push(temp)\n return buff\n\n\nclass MyStackSimplified(Stack):\n def sort(self):\n buff = MyStack()\n while not self.is_empty():\n temp = self.pop()\n while not buff.is_empty() and temp < buff.peek():\n self.push(buff.pop())\n buff.push(temp)\n return buff\n","repo_name":"labex-labs/open-source-labs","sub_path":"python/interactive-coding-challenges/challenge-sort-stack/solutions/sort_stack.py","file_name":"sort_stack.py","file_ext":"py","file_size_in_byte":1248,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"}
+{"seq_id":"16835701843","text":"# Ask for your weight\r\nimport math\r\n\r\nweight = input(\"What's your weight? \")\r\n\r\n# Ask for measure\r\nunit = input(\"Select unit: Pounds(L) or Kilograms(K) \")\r\n\r\n# Conditional structure\r\nif unit.upper() == \"L\":\r\n print(f'You are {math.floor(float(weight)*0.45)} kg')\r\nelif unit.upper() == \"K\":\r\n print(f'You are {math.floor(float(weight) / 0.45)} lbs')\r\nelse:\r\n print(\"No measure selected.\")\r\n","repo_name":"Darthpaul0/Python","sub_path":"Exercises/weightConverter.py","file_name":"weightConverter.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"5530274830","text":"# TODO:\n# add list score\n# add restart after loose\n# add possibility to decide how many ball in the Game\n\n\n# needed for the tkinter party and creating balls\n# import tkinter\nfrom tkinter import *\nimport random\nimport time\n\n# constant for widget hight and width\nWIDTH = 700\nHIGHT = 600\n\n# crating the tkinter canvas with high and width\ntk = Tk()\ncanvas = Canvas(tk, width=WIDTH, height=HIGHT)\ntk.title(\"Avoid Game\")\ncanvas.pack()\n\n# Timer\nfrom timeit import default_timer\n\n\ndef updateTime():\n now = default_timer() - start\n minutes, secondes = divmod(now, 60)\n houres, minutes = divmod(minutes, 60)\n str_time = \" %d : %02d : %02d \" % (houres, minutes, secondes)\n canvas.itemconfigure(text_clock, text=str_time)\n # tk.after(1000,updateTime)\n\n\nstart = default_timer()\ntext_clock = canvas.create_text(500, 20)\n\n# creating ball class that create an oval with size color etc\n\n\nclass Ball:\n # kind of constructor\n def __init__(self, color, size):\n self.shape = canvas.create_oval(10, 10, size, size, fill=color)\n self.xSpeed = random.uniform(-3.5, 3.5)\n self.ySpeed = random.uniform(-3.5, 3.5)\n # avoid geting a deth ball that don't move\n if self.xSpeed == 0:\n self.xSpeed = random.uniform(-3.5, 3.5)\n if self.ySpeed == 0:\n self.ySpeed = random.uniformu(-3.5, 3.5)\n # method that move the ball\n\n def move(self):\n canvas.move(self.shape, self.xSpeed, self.ySpeed)\n pos = canvas.coords(self.shape)\n if pos[3] >= HIGHT or pos[1] <= 0:\n self.ySpeed = -self.ySpeed\n if pos[2] >= WIDTH or pos[0] <= 0:\n self.xSpeed = -self.xSpeed\n return pos\n\n\n# Ball color that will be in the list colors\ncolors = ['red', 'green', 'orange', 'yellow', 'red', 'cyan', 'magenta',\n 'dodgerblue', 'turquoise', 'grey', 'gold', 'pink']\n\n# creating ball list emty\nballs = []\n\n# filling the ball list with multiple ball\nfor i in range(40):\n balls.append(Ball(random.choice(colors), 45))\n\n# Cord of mouse\nx = tk.winfo_pointerx()\ny = tk.winfo_pointery()\nabs_coord_x = tk.winfo_pointerx() - tk.winfo_rootx()\nabs_coord_y = tk.winfo_pointery() - tk.winfo_rooty()\n\n# Creation of rec\nrec = canvas.create_rectangle(\n abs_coord_x - 15, abs_coord_y - 15, abs_coord_x + 15, abs_coord_y + 15, fill='black')\n\n# Moving the balls and updating the canvas to have a smooth view\n\n\ndef moveBall():\n A = True\n while A:\n # updating mouse cords\n x = tk.winfo_pointerx()\n y = tk.winfo_pointery()\n abs_coord_x = tk.winfo_pointerx() - tk.winfo_rootx()\n abs_coord_y = tk.winfo_pointery() - tk.winfo_rooty()\n # moving rec\n rectCord = canvas.coords(\n rec, abs_coord_x - 15, abs_coord_y - 15, abs_coord_x + 15, abs_coord_y + 15)\n # moving balls\n for ball in balls:\n cordOval = ball.move()\n if cordOval[3] <= abs_coord_y + 47 and cordOval[1] >= abs_coord_y - 47 and cordOval[2] <= abs_coord_x + 47 and cordOval[0] >= abs_coord_x - 47:\n # print('touched at :\\n \\t cursor in : \\n \\t\\t x1 = ', abs_coord_x - 15, ' x2 = ', abs_coord_x + 15, ' y1 = ', abs_coord_y - 15, ' y2 = ', abs_coord_y +\n # 15, ' \\n \\t ball in :\\n \\t\\t cordOval[0] = ', cordOval[0], 'cordOval[1] = ', cordOval[1], 'cordOval[2] = ', cordOval[2], 'cordOval[3] = ', cordOval[3])\n A = False\n\n # updating the canvas\n tk.update()\n updateTime()\n time.sleep(0.01)\n\n\nmoveBall()\ntk.mainloop()\n","repo_name":"IsmailMAJBAR/AvoidGame","sub_path":"avoidGame.py","file_name":"avoidGame.py","file_ext":"py","file_size_in_byte":3529,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"11916049782","text":"import os\nimport subprocess\n\nimport pytest\n\nfrom click_odoo_contrib.gitutils import commit_if_needed\n\n\n@pytest.fixture\ndef gitdir(tmpdir):\n subprocess.check_call([\"git\", \"init\"], cwd=str(tmpdir))\n subprocess.check_call([\"git\", \"config\", \"user.name\", \"tester\"], cwd=str(tmpdir))\n subprocess.check_call(\n [\"git\", \"config\", \"user.email\", \"tester@example.com\"], cwd=str(tmpdir)\n )\n yield tmpdir\n\n\ndef _git_ls_files(cwd):\n output = subprocess.check_output(\n [\"git\", \"ls-files\"], cwd=str(cwd), universal_newlines=True\n )\n return output.strip().split(\"\\n\")\n\n\ndef _git_staged_files(cwd):\n output = subprocess.check_output(\n [\"git\", \"diff\", \"--cached\", \"--name-only\"],\n cwd=str(cwd),\n universal_newlines=True,\n )\n return output.strip().split(\"\\n\")\n\n\ndef _git_add(paths, cwd):\n cmd = [\"git\", \"add\", \"--\"] + paths\n subprocess.check_call(cmd, cwd=str(cwd))\n\n\ndef test_git_commit_if_needed(gitdir):\n assert \"file1\" not in _git_ls_files(gitdir)\n file1 = gitdir / \"file1\"\n file1.ensure(file=True)\n assert commit_if_needed([str(file1)], \"msg\", cwd=str(gitdir))\n assert \"file1\" in _git_ls_files(gitdir)\n # no change, commit_if_needed returns False\n assert not commit_if_needed([str(file1)], \"msg\", cwd=str(gitdir))\n # some change\n file1.write(\"stuff\")\n assert commit_if_needed([str(file1)], \"msg\", cwd=str(gitdir))\n # some unrelated file not in git\n file2 = gitdir / \"file2\"\n file2.ensure(file=True)\n assert not commit_if_needed([str(file1)], \"msg\", cwd=str(gitdir))\n assert \"file2\" not in _git_ls_files(gitdir)\n # some unrelated file in git index\n _git_add([str(file2)], gitdir)\n assert not commit_if_needed([str(file1)], \"msg\", cwd=str(gitdir))\n assert \"file1\" not in _git_staged_files(gitdir)\n assert \"file2\" in _git_staged_files(gitdir)\n # add subdirectory\n dir1 = gitdir / \"dir1\"\n dir1.ensure(dir=True)\n file3 = dir1 / \"file3\"\n file3.ensure(file=True)\n assert commit_if_needed([str(file3)], \"msg\", cwd=str(gitdir))\n assert \"dir1/file3\" in _git_ls_files(gitdir)\n\n\ndef test_commit_git_ignored(gitdir):\n file1 = gitdir / \"file1.pot\"\n file1.ensure(file=True)\n gitignore = gitdir / \".gitignore\"\n gitignore.write(\"*.pot\\n\")\n assert commit_if_needed([str(file1)], \"msg\", cwd=str(gitdir))\n assert \"file1.pot\" in _git_ls_files(gitdir)\n\n\ndef test_commit_reldir(gitdir):\n with gitdir.as_cwd():\n os.mkdir(\"subdir\")\n file1 = \"subdir/file1\"\n with open(file1, \"w\"):\n pass\n assert commit_if_needed([file1], \"msg\", cwd=\"subdir\")\n","repo_name":"acsone/click-odoo-contrib","sub_path":"tests/test_gitutils.py","file_name":"test_gitutils.py","file_ext":"py","file_size_in_byte":2615,"program_lang":"python","lang":"en","doc_type":"code","stars":83,"dataset":"github-code","pt":"31"}
+{"seq_id":"36278107406","text":"#!/usr/bin/env python3\n#\n# WIP: copy this file in wrapping/src directory of the build tree\n# then execute it (python3 ./wrapping/src/test_make_geometry\n# path_to_data_directory)\n\nimport os.path as op\nimport numpy as np\nfrom optparse import OptionParser\n\nimport openmeeg as om\n\n\ndef python_mesh(name, path):\n mesh = om.Mesh(path)\n mesh_vertices = mesh.geometry().vertices()\n vertices = np.array([vertex.array() for vertex in mesh_vertices])\n mesh_triangles = mesh.triangles()\n triangles = np.array([mesh.triangle(triangle).array() for triangle in mesh_triangles])\n return vertices, triangles\n\ndata_path = op.dirname(op.abspath(__file__))\nparser = OptionParser()\nparser.add_option(\"-p\", \"--path\", dest=\"data_path\",\n help=\"path to data folder\", metavar=\"FILE\",\n default=data_path)\n\noptions, args = parser.parse_args()\ndata_path = options.data_path\n\n# Load mesh data to mimic Head1.geom + Head1.cond\n\nsubject = \"Head1\"\ndirpath = op.join(data_path, subject)\n\nmeshes = dict()\nmeshes[\"cortex\"] = python_mesh(\"cortex\", op.join(dirpath, \"cortex.1.tri\"))\nmeshes[\"skull\"] = python_mesh(\"skull\", op.join(dirpath, \"skull.1.tri\"))\nmeshes[\"scalp\"] = python_mesh(\"scalp\", op.join(dirpath, \"scalp.1.tri\"))\n\n# It should be possible to have multiple oriented meshes per interface. e.g.\n# interface1 = [(m1,om.OrientedMesh.Normal), (m2,om.OrientedMesh.Opposite), (m3,om.OrientedMesh.Normal)]\n# It should also be possible to have a name added at the beginning of the\n# tuple.\n\ninterfaces = {\n \"interface1\": [('cortex', om.OrientedMesh.Normal)],\n \"interface2\": [('skull', om.OrientedMesh.Normal)],\n \"interface3\": [('scalp', om.OrientedMesh.Normal)]\n}\n\ndomains = {\n \"Scalp\": ([('interface2', om.SimpleDomain.Outside), ('interface3', om.SimpleDomain.Inside)], 1.0),\n \"Brain\": ([('interface1', om.SimpleDomain.Inside)], 1.0),\n \"Air\": ([('interface3', om.SimpleDomain.Outside)], 0.0),\n \"Skull\": ([('interface2', om.SimpleDomain.Inside), ('interface1', om.SimpleDomain.Outside)], 0.0125)\n}\n\ng1 = om.make_geometry(meshes, interfaces, domains)\ng2 = om.Geometry(op.join(dirpath, subject + \".geom\"), op.join(dirpath, subject + \".cond\"))\n\nassert g1.is_nested()\nassert g2.is_nested()\nassert g1.__class__ == g2.__class__\n","repo_name":"packeted/openmeeg","sub_path":"wrapping/src/test_make_geometry.py","file_name":"test_make_geometry.py","file_ext":"py","file_size_in_byte":2260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"31"}
+{"seq_id":"26223818062","text":"class Solution:\n def leastBricks(self, wall: List[List[int]]) -> int:\n count = {}\n max_hole = 0\n for line in wall:\n brick = 0\n sum_all = sum(line)\n for i in line:\n brick += i\n if brick < sum_all:\n count[brick] = count.get(brick, 0) + 1\n max_hole = max(max_hole, count[brick])\n return len(wall) - max_hole","repo_name":"ljyou001/Leetcode-Problems-in-Python","sub_path":"554-brick-wall.py","file_name":"554-brick-wall.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"33955440190","text":"n = int(input())\na = list(map(int, input().strip().split()))\nmax_sums = set()\nfor i in range(n):\n max_sum = float('-inf')\n total = 0\n for j in range(i, n):\n total += a[j]\n max_sum = max(max_sum, total)\n total = max(total, 0)\n if max_sum not in max_sums:\n max_sums.add(max_sum)\nprint(sum(max_sums))\n","repo_name":"HBinhCT/Q-project","sub_path":"hackerearth/Data Structures/Hash Tables/Basics of Hash Tables/Maximum Sum/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"}
+{"seq_id":"19988032308","text":"# liste_1 contient tous les noms des départements\nliste_1 = [nom for nom in departements]\n\n# liste_2 contient toutes les surfaces des départements\nliste_2 = [departements[nom] for nom in departements]\n\n# liste_3 contient les noms des départements \n# strictement mesurant moins de 1000 km²\nliste_3 = [nom for nom in departements if departements[nom] < 1000]\n\n# liste_4 contient les surfaces des départements\n# dont le nom contient la chaîne \"Seine\"\nliste_4 = [departements[nom] for nom in departements if \"Seine\" in nom]\n\n# liste_5 contient les noms des départements\n# dont le nom débute par un \"S\"\n# et la surface est comprise entre 5 000 et 7 000 km²\nliste_5 = [departements[nom] for nom in departements if nom[0] == \"S\" and 5000 <= departements[nom] <= 7000]","repo_name":"Lycee-Experimental/nsi-lxp","sub_path":"docs/premiere/data/1_tables/1_depart/pythons/departements/exo_corr.py","file_name":"exo_corr.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"34361124466","text":"import athletemodel\nimport yate\nimport cgi\n\n# 以下两行启用Python的CGI跟踪技术\nimport cgitb \ncgitb.enable()\n\n# 获取所有表单数据,并放在一个字典中\nform_data = cgi.FieldStorage()\n\nathlete_name = form_data['which_athlete'].value\n\nathlete = athletemodel.get_athlete_from_id(athlete_name)\n\nprint(yate.start_response())\nprint(yate.include_header(\"NUAC's Timing Data\"))\nprint(yate.header('Athlete: ' + athlete['Name'] +\n ' DOB: ' + athlete['DOB'] + '.'))\nprint(yate.para('The top times for this athlete are:'))\nprint(yate.u_list(athlete['top3']))\nprint(yate.para('The entire set of timing data is: ' + str(athlete['data']) \\\n + '(duplicates removed).'))\nprint(yate.include_footer({'Home':'/index.html',\\\n 'Selecte another athlete':'generate_list.py', \\\n 'Add time data':'test_form.py'}))\n","repo_name":"MingoSue/webapp_athlete","sub_path":"cgi-bin/generate_timing_data.py","file_name":"generate_timing_data.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"40912689488","text":"# -- Peace of cake -- #\r\ndef get_recipe_price(prices, optionals=None, **ingredients):\r\n \"\"\"\r\n :param prices: A dictionary of ingredients needed to make a certain recipe.\r\n :param optionals: A list of components that we will ignore, meaning - we will not buy from them at all.\r\n :param ingredients: The name of the ingredient and the amount of the ingredient in grams that we would like to buy\r\n for the recipe.\r\n :return: Return the final price for buying all ingredients\r\n \"\"\"\r\n final_price = 0\r\n for product, amount in ingredients.items():\r\n if not optionals or product not in optionals:\r\n product_price = prices.get(product)\r\n total_product_price = product_price * (amount / 100)\r\n final_price += total_product_price\r\n return int(final_price)\r\n\r\n\r\nif __name__ == '__main__':\r\n # -- Peace of cake -- #\r\n print(get_recipe_price({'chocolate': 18, 'milk': 8}, chocolate=200, milk=100))\r\n print(get_recipe_price({'chocolate': 18, 'milk': 8}, optionals=['milk'], chocolate=300))\r\n print(get_recipe_price({}))\r\n","repo_name":"Lev-Excellenteam-2023/exercise1-yammesika-week-5-odelya1999","sub_path":"5.2.Peace_of_cake.py","file_name":"5.2.Peace_of_cake.py","file_ext":"py","file_size_in_byte":1089,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"3356485920","text":"N = input()\nnums = [1 for i in range(10)]\ncnt = 1\nfor i in N:\n if i == '9' and not nums[9] and nums[6]:\n i = 6\n elif i == '6' and not nums[6] and nums[9]:\n i = 9 \n i = int(i)\n if nums[i]:\n nums[i] -= 1\n else:\n cnt += 1\n nums[i] -= 1\n for n in range(10):\n nums[n] += 1\nprint(cnt)\n","repo_name":"SSAFY-algamza/ssafy-algorithm-study","sub_path":"f1rstf1y9/BOJ/BOJ_1475_방 번호.py","file_name":"BOJ_1475_방 번호.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"29057453306","text":"#!/usr/bin/env python3\nimport os\n\n\"\"\"\nThe height of a binary tree is the number of edges between the tree's root and its furthest leaf.\nFor example, the following binary tree is of height 2:\n\n 4\n / \\\n / \\\n 2 6\n / \\ / \\\n 1 3 5 7\n \nFunction Description\n\nComplete the getHeight or height function in the editor. It must return the height of a binary tree as an integer.\n\ngetHeight or height has the following parameter(s):\n\nroot: a reference to the root of a binary tree.\n\nNote -The Height of binary tree with single node is taken as zero.\n\nInput Format\n\nThe first line contains an integer n, the number of nodes in the tree.\nNext line contains n space separated integer where i-th integer denotes node[i].data.\n\nNote: Node values are inserted into a binary search tree before a reference to the tree's root\nnode is passed to your function. In a binary search tree, all nodes on the left branch of a node \nare less than the node value. All values on the right branch are greater than the node value.\n\nConstraints\n\n1 <= node.data[i] <= 20\n1 <= n <= 20\n\nOutput Format\n\nYour function should return a single integer denoting the height of the binary tree.\n\nSample Input\n\n 3\n / \\\n / \\\n 2 5\n / / \\\n 1 4 6\n \\\n 7\n\nSample Output\n\n3\n\nExplanation\n\nThe longest root-to-leaf path is shown below:\n\n 3\n / \\ <--\n / \\ <--\n 2 5 <--\n / / \\ <--\n 1 4 6 <--\n \\ <--\n 7 <--\n\nThere are 4 nodes in this path that are connected by 3 edges, meaning our binary \ntree's height = 3.\n\"\"\"\n\n\nclass Node:\n def __init__(self, info):\n self.info = info\n self.left = None\n self.right = None\n\n def __str__(self):\n return str(self.info)\n\n\nclass BinarySearchTree:\n def __init__(self):\n self.root = None\n\n def create(self, val):\n if self.root is None:\n self.root = Node(val)\n else:\n current = self.root\n\n while True:\n if val < current.info:\n if current.left:\n current = current.left\n else:\n current.left = Node(val)\n break\n elif val > current.info:\n if current.right:\n current = current.right\n else:\n current.right = Node(val)\n break\n else:\n break\n\n\ndef height(root):\n def __height__(current_node, current_height):\n if current_node is None:\n return current_height\n left_height = __height__(current_node.left, current_height + 1)\n right_height = __height__(current_node.right, current_height + 1)\n return max(left_height, right_height)\n return __height__(root,-1)\n\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n expected_output = os.environ['OUTPUT_PATH'].replace('output', 'expected_output')\n\n tree = BinarySearchTree()\n\n t = int(input())\n\n arr = list(map(int, input().split()))\n\n for i in range(t):\n tree.create(arr[i])\n\n results = height(tree.root)\n\n fptr.write(str(results))\n fptr.write('\\n')\n\n fptr.close()\n expected_results = open(expected_output, 'r').read().rstrip()\n # print(\" Output: >>%s<< %s\" % (str(results), type(results)))\n # print(\"Expected output: >>%s<< %s\" % (str(expected_results), type(expected_results)))\n\n assert str(results) == str(expected_results)\n print(\"Tests passed for: %s\" % os.environ['OUTPUT_PATH'])\n","repo_name":"rjmarshall17/trees","sub_path":"hacker_rank_height_of_a_binary_tree.py","file_name":"hacker_rank_height_of_a_binary_tree.py","file_ext":"py","file_size_in_byte":3919,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"38666921391","text":"def change2(n):\n a = n\n b = []\n\n while True:\n b.append(a%3)\n a = a//3\n if a == 0:\n break\n b.reverse()\n return b\n\ndef solution(n):\n answer = ''\n b = change2(n)\n\n while 0 in b:\n print(b)\n index0 = b.index(0)\n if index0 == 0:\n b.remove(0)\n continue\n b[index0] = 4\n if b[index0 - 1] == 4:\n b[index0 -1] = 2\n else:\n b[index0 -1] -= 1\n\n\n for i in b:\n answer += str(i)\n return answer\n\n","repo_name":"joy961208/Programmers-Coding-Test","sub_path":"Level 2/124나라의숫자.py","file_name":"124나라의숫자.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"}
+{"seq_id":"20357245481","text":"import pandas as pd\nimport scipy\nimport matplotlib.pyplot as plt\nimport seaborn as sb\n\n\nseqtocountry_dict = {}\nseqtotemp_dict = {}\n\nseqtogenchange_dict = {}\nseqtopp1a_change_dict = {}\nseqtonsp2_change_dict = {}\nseqtorbd_change_dict = {}\nseqtospikes1_change_dict = {}\nseqtospikes2_change_dict = {}\n\nseqtogenchange_normalized_dict = {}\nseqtopp1a_change_normalized_dict = {}\nseqtonsp2_change_normalized_dict = {}\nseqtorbd_change_normalized_dict = {}\nseqtospikes1_change_normalized_dict = {}\nseqtospikes2_change_normalized_dict = {}\n\nseqtodate_dict = {}\nseqtorelativedate_dict = {}\ncountrytoseq_dict = {}\n\ncountrytolat_dict = {\"Australia\": -25.274398, \"Brazil\": -14.235004, \"Colombia\": 4.570868, \"China\": 35.86166, \"Finland\": 61.92411, \"India\": 20.593684, \"Italy\": 41.87194, \"Japan\": 36.204824,\n\"Nepal\": 28.39486, \"Pakistan\": 30.375321, \"Peru\": -9.189967, \"South Korea\": -1.940278, \"Spain\": 40.463667, \"Sweden\": 60.128161, \"Taiwan\": 23.69781, \"USA\": 37.09024, \"Vietnam\": 14.058324}\ncountrytolong_dict = {\"Australia\": 133.775136, \"Brazil\": -51.92528, \"Colombia\": -74.297333, \"China\": 104.195397, \"Finland\": 25.748151, \"India\": 78.96288, \"Italy\": 12.56738, \"Japan\": 138.252924,\n\"Nepal\": 84.124008, \"Pakistan\": 69.345116, \"Peru\": -75.015152, \"South Korea\": 29.873888, \"Spain\": -3.74922, \"Sweden\": 18.643501, \"Taiwan\": 120.960515, \"USA\": -95.712891, \"Vietnam\": 108.277199}\ncountrytotemp_dict = {\"Australia\": 69.8, \"Brazil\": 76.7, \"Colombia\": 65, \"China\": 57.3, \"Finland\": 39.5, \"India\": 96.8, \"Italy\": 54.5, \"Japan\": 58.1,\n\"Nepal\": 70, \"Pakistan\": 74.3, \"Peru\": 69.1, \"South Korea\": 62.6, \"Spain\": 66.2, \"Sweden\": 41.9, \"Taiwan\": 72.3, \"USA\": 52.9, \"Vietnam\": 94}\n\nwith open(\"/Users/prakruthiburra/Desktop/CPSC_567/CPSC567_COVID/dataset/meta_info_with_genetic_changes_no_isolation_source.csv\", \"r\") as f:\n\n#Skip index\n next(f)\n lines = f.readlines()\n for line in lines:\n line = line.strip().split(\",\")\n print(line)\n seq_id = line[0]\n\n# 364 sequences were isolated of which two sequences did not contain a country label and were excluded from the analysis.\n#Excluding sequences without a country label\n if(line[3] != \"NA\"):\n seqtocountry_dict[seq_id] = (line[3])\n\n seqtodate_dict[seq_id] = (line[4].strip())\n date = seqtodate_dict[seq_id].strip().split(\"-\")\n year = date[0]\n month = date[1]\n if(len(date)==3):\n day = date[2]\n else:\n day = 15\n\n if(year == '2019'):\n seqtorelativedate_dict[line[0]] = int(day) - 15\n elif(month == '01'):\n seqtorelativedate_dict[line[0]] = 16 + int(day)\n elif(month == '02'):\n seqtorelativedate_dict[line[0]] = 47 + int(day)\n elif(month == '03'):\n seqtorelativedate_dict[line[0]] = 76 + int(day)\n\n seqtogenchange_dict[seq_id] = int(line[6])\n seqtopp1a_change_dict[seq_id] = int(line[7])\n seqtonsp2_change_dict[seq_id] = int(line[8])\n seqtorbd_change_dict[seq_id] = int(line[9])\n seqtospikes1_change_dict[seq_id] = int(line[10])\n seqtospikes2_change_dict[seq_id] = int(line[11])\n\n if(seqtorelativedate_dict[seq_id] != 0):\n seqtogenchange_normalized_dict[seq_id] = float(seqtogenchange_dict[seq_id])/float(seqtorelativedate_dict[seq_id])\n seqtopp1a_change_normalized_dict[seq_id] = float(seqtopp1a_change_dict[seq_id])/float(seqtorelativedate_dict[seq_id])\n seqtonsp2_change_normalized_dict[seq_id] = float(seqtonsp2_change_dict[seq_id])/float(seqtorelativedate_dict[seq_id])\n seqtorbd_change_normalized_dict[seq_id] = float(seqtorbd_change_dict[seq_id])/float(seqtorelativedate_dict[seq_id])\n seqtospikes1_change_normalized_dict[seq_id] = float(seqtospikes1_change_dict[seq_id])/float(seqtorelativedate_dict[seq_id])\n seqtospikes2_change_normalized_dict[seq_id] = float(seqtospikes2_change_dict[seq_id])/float(seqtorelativedate_dict[seq_id])\n else:\n seqtogenchange_normalized_dict[seq_id] = 'NA'\n seqtopp1a_change_normalized_dict[seq_id] = 'NA'\n seqtonsp2_change_normalized_dict[seq_id] = 'NA'\n seqtorbd_change_normalized_dict[seq_id] = 'NA'\n seqtospikes1_change_normalized_dict[seq_id] = 'NA'\n seqtospikes2_change_normalized_dict[seq_id] = 'NA'\n\n# g = open(\"/Users/prakruthiburra/Desktop/CPSC_567/all_meta_data.csv\", \"w+\")\n# g.write(\"Accession,Geo Location,Collection Date,Relative Date,Temperature,Latitude,Longitude,gc,pp1a,nsp2,rbd,spike_s1,spike_s2,gc_normalized,pp1a_n,nsp2_n,rbd_n,spike_s1_n,spike_s2_n\\n\")\n#\n# for i in seqtocountry_dict.keys():\n# country = seqtocountry_dict[i]\n# g.write(i+\",\"+str(country)+\",\"+str(seqtodate_dict[i])+\",\"+str(seqtorelativedate_dict[i])+\",\"+\n# str(countrytotemp_dict[country])+\",\"+str(countrytolat_dict[country])+\",\"+str(countrytolong_dict[country])+\",\"+\n# str(seqtogenchange_dict[i])+\",\"+str(seqtopp1a_change_dict[i])+\",\"+str(seqtonsp2_change_dict[i])+\",\"+str(seqtorbd_change_dict[i])+\",\"+\n# str(seqtospikes1_change_dict[i])+\",\"+str(seqtospikes2_change_dict[i])+\",\"+\n# str(seqtogenchange_normalized_dict[i])+\",\"+str(seqtopp1a_change_normalized_dict[i])+\",\"+str(seqtonsp2_change_normalized_dict[i])+\",\"+str(seqtorbd_change_normalized_dict[i])+\",\"+\n# str(seqtospikes1_change_normalized_dict[i])+\",\"+str(seqtospikes2_change_normalized_dict[i])+\"\\n\")\n# Removed from correlations: NC_045512, MN908947 for they had relative date set to 0 and the sequences either corresponded to the reference or were identical to it.\n\ndata = pd.read_csv(\"/Users/prakruthiburra/Desktop/CPSC_567/all_meta_data.csv\")\nprint(data.head())\nTemperature = data['Temperature'].to_numpy()\nLatitude = data['Latitude'].to_numpy()\nLongitude = data['Longitude'].to_numpy()\ngc = data['gc'].to_numpy()\npp1a = data['pp1a'].to_numpy()\nnsp2 = data['nsp2'].to_numpy()\nrbd = data['rbd'].to_numpy()\nspike_s1 = data['spike_s1'].to_numpy()\nspike_s2 = data['spike_s2'].to_numpy()\ngc_n = data['gc_normalized'].to_numpy()\npp1a_n = data['pp1a_n'].to_numpy()\nnsp2_n = data['nsp2_n'].to_numpy()\nrbd_n = data['rbd_n'].to_numpy()\nspike_s1_n = data['spike_s1_n'].to_numpy()\nspike_s2_n = data['spike_s2_n'].to_numpy()\n\nfrom scipy.stats import pearsonr\npearsonr(Temperature, gc)\npearsoncorr = data.corr(method='pearson')\npearsoncorr = pearsoncorr[['Temperature', 'Latitude', 'Longitude']]\npearsoncorr = pearsoncorr.drop(['Temperature', 'Latitude', 'Longitude', 'Relative Date'])\nprint(pearsoncorr)\nsb.heatmap(pearsoncorr,\n xticklabels=pearsoncorr.columns,\n yticklabels=['Genomic Change', 'pp1a Change', 'nsp2a Change', 'RBD Change',\n 'Spike_s1 Change', 'Spike_s2 Change', 'Norm. Genomic Change', 'Norm. pp1a Change', 'Norm. nsp2 Change', 'Norm. RBD Change', 'Norm. Spike_s1 Change', 'Norm. Spike_s2 Change'],\n cmap='YlGnBu',\n annot=True,\n linewidth=0.5)\nplt.show()\n\nprint(\"TEMPERATURE\")\nprint(scipy.stats.pearsonr(gc, Temperature))\nprint(scipy.stats.pearsonr(pp1a, Temperature))\nprint(scipy.stats.pearsonr(nsp2, Temperature))\nprint(scipy.stats.pearsonr(rbd, Temperature))\nprint(scipy.stats.pearsonr(spike_s1, Temperature))\nprint(scipy.stats.pearsonr(spike_s2, Temperature))\nprint(scipy.stats.pearsonr(gc_n, Temperature))\nprint(scipy.stats.pearsonr(pp1a_n, Temperature))\nprint(scipy.stats.pearsonr(nsp2_n, Temperature))\nprint(scipy.stats.pearsonr(rbd_n, Temperature))\nprint(scipy.stats.pearsonr(spike_s1_n, Temperature))\nprint(scipy.stats.pearsonr(spike_s2_n, Temperature))\nprint(\"\\n\")\nprint(\"LATITUDE\")\nprint(scipy.stats.pearsonr(gc, Latitude))\nprint(scipy.stats.pearsonr(pp1a, Latitude))\nprint(scipy.stats.pearsonr(nsp2, Latitude))\nprint(scipy.stats.pearsonr(rbd, Latitude))\nprint(scipy.stats.pearsonr(spike_s1, Latitude))\nprint(scipy.stats.pearsonr(spike_s2, Latitude))\nprint(scipy.stats.pearsonr(gc_n, Latitude))\nprint(scipy.stats.pearsonr(pp1a_n, Latitude))\nprint(scipy.stats.pearsonr(nsp2_n, Latitude))\nprint(scipy.stats.pearsonr(rbd_n, Latitude))\nprint(scipy.stats.pearsonr(spike_s1_n, Latitude))\nprint(scipy.stats.pearsonr(spike_s2_n, Latitude))\nprint(\"\\n\")\nprint(\"LONGITUDE\")\nprint(scipy.stats.pearsonr(gc, Longitude))\nprint(scipy.stats.pearsonr(pp1a, Longitude))\nprint(scipy.stats.pearsonr(nsp2, Longitude))\nprint(scipy.stats.pearsonr(rbd, Longitude))\nprint(scipy.stats.pearsonr(spike_s1, Longitude))\nprint(scipy.stats.pearsonr(spike_s2, Longitude))\nprint(scipy.stats.pearsonr(gc_n, Longitude))\nprint(scipy.stats.pearsonr(pp1a_n, Longitude))\nprint(scipy.stats.pearsonr(nsp2_n, Longitude))\nprint(scipy.stats.pearsonr(rbd_n, Longitude))\nprint(scipy.stats.pearsonr(spike_s1_n, Longitude))\nprint(scipy.stats.pearsonr(spike_s2_n, Longitude))\nprint(\"\\n\")\n","repo_name":"ShawnCone/CPSC567_COVID","sub_path":"scripts/correlations.py","file_name":"correlations.py","file_ext":"py","file_size_in_byte":8871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"17183244457","text":"from skimage.metrics import structural_similarity, peak_signal_noise_ratio\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef plot_dataset(batch_speckle, batch_clean):\n n = batch_speckle.shape[0]\n\n for i in range(n):\n fig, axes = plt.subplots(\n nrows = 2,\n ncols = 2, \n figsize = (8, 8))\n\n axes[0,0].imshow(batch_speckle[i,...,0], cmap='gray')\n axes[0,0].set_title('Input with speckle')\n axes[0,1].imshow(batch_clean[i,...,0], cmap='gray')\n axes[0,1].set_title('Ground truth')\n\n axes[1,0].hist(batch_speckle[i,...,0].flatten(), bins=100, histtype='step')\n axes[1,0].set_title('Input with speckle')\n axes[1,1].hist(batch_clean[i,...,0].flatten(), bins=100, histtype='step')\n axes[1,1].set_title('Ground truth')\n\n plt.show()\n plt.close()\n\ndef plot_history(history):\n fig, ax = plt.subplots(\n nrows = 2,\n ncols = 1, \n figsize = (15,10))\n\n ax[0].plot(history.history['loss'], '-*', label='Training Loss')\n ax[0].plot(history.history['val_loss'], '-o', label='Validation Loss')\n ax[0].set_xlabel('Epochs')\n ax[0].set_ylabel('MAE')\n ax[0].set_title('Training VS Validation MAE')\n\n ax[1].plot(history.history['mse'], '-*', label='Training Loss')\n ax[1].plot(history.history['val_mse'], '-o', label='Validation Loss')\n ax[1].set_xlabel('Epochs')\n ax[1].set_ylabel('MSE')\n ax[1].set_title('Training VS Validation MSE')\n \n ax[0].legend()\n ax[0].grid()\n ax[1].legend()\n ax[1].grid()\n plt.show()\n\ndef plot_model_results(batch_speckle, batch_clean, batch_pred, n=False):\n n = batch_speckle.shape[0]\n\n for i in range(n):\n print('===========================================================================================================================================')\n print(' TEST %d ' % (i))\n fig, axes = plt.subplots(\n nrows = 2,\n ncols = 4, \n figsize = (16, 8))\n\n axes[0,0].imshow(batch_speckle[i,...,0], cmap='gray')\n axes[0,0].set_title('Input with speckle')\n axes[0,1].imshow(batch_clean[i,...,0], cmap='gray')#, vmin=0, vmax=1.0)\n axes[0,1].set_title('Ground truth')\n if n==True:\n axes[0,2].imshow(batch_pred[i,...,0], cmap='gray')\n else:\n axes[0,2].imshow(batch_pred[i,...,0], cmap='gray', vmin = np.min(batch_pred[i,...,0]), vmax =np.max(batch_pred[i,...,0]))#, vmin=0, vmax=1.0)\n axes[0,2].set_title('Model Prediction')\n diff = np.abs(batch_pred[i,...,0] - batch_clean[i,...,0])\n axes[0,3].imshow(diff, vmin=np.min(diff), vmax=np.max(diff), cmap='gray')\n axes[0,3].set_title('|Model Prediction - Ground Truth|')\n\n axes[1,0].hist(batch_speckle[i,...,0].flatten(), bins=100, histtype='step')\n axes[1,0].set_title('Input with speckle')\n axes[1,1].hist(batch_clean[i,...,0].flatten(), bins=100, histtype='step')\n axes[1,1].set_title('Ground truth')\n axes[1,2].hist(batch_pred[i,...,0].flatten(), bins=100, histtype='step')\n axes[1,2].set_title('Model Prediction')\n axes[1,3].hist(diff.flatten(), bins=100, histtype='step')\n axes[1,3].set_title('|Model Prediction - Ground Truth|')\n \n plt.show()\n plt.close()\n\ndef compute_metrics(batch_speckle, batch_clean, batch_pred):\n n = batch_speckle.shape[0]\n \n print('===========================================================================================================================================')\n print(' Test \\t\\t Metric\\t\\tGrount Truth VS Grount Truth \\t\\t Grount Truth VS Input \\t\\t Grount Truth VS Model Prediction')\n print('-------------------------------------------------------------------------------------------------------------------------------------------')\n for i in range(n):\n gt_vs_gt = peak_signal_noise_ratio(batch_clean[i, ...,0], batch_clean[i, ...,0], data_range=1.0)\n gt_vs_in = peak_signal_noise_ratio(batch_clean[i, ...,0], batch_speckle[i,...,0], data_range=1.0)\n gt_vs_pred = peak_signal_noise_ratio(batch_clean[i, ...,0], batch_pred[i,...,0], data_range=1.0)\n\n print(' %i \\t\\t PSNR \\t\\t %.2f \\t\\t %.2f \\t\\t %.2f' % (i, gt_vs_gt, gt_vs_in, gt_vs_pred))\n \n gt_vs_gt = structural_similarity(batch_clean[i, ...,0], batch_clean[i, ...,0], data_range=1.0)\n gt_vs_in = structural_similarity(batch_clean[i, ...,0], batch_speckle[i,...,0], data_range=1.0)\n gt_vs_pred = structural_similarity(batch_clean[i, ...,0], batch_pred[i,...,0], data_range=1.0)\n print(' %i \\t\\t SSIM \\t\\t %.2f \\t\\t %.2f \\t\\t %.2f' % (i, gt_vs_gt, gt_vs_in, gt_vs_pred))\n \n enl_gt = (np.mean(batch_clean[i, ...,0])**2)/(np.std(batch_clean[i, ...,0])**2)\n enl_in = (np.mean(batch_speckle[i,...,0])**2)/(np.std(batch_speckle[i,...,0])**2)\n enl_pre = (np.mean(batch_pred[i,...,0])**2)/(np.std(batch_pred[i,...,0])**2)\n \n print(' %i \\t\\t ENL \\t\\t %.2f \\t\\t %.2f \\t\\t %.2f' % (i, enl_gt, enl_in, enl_pre))\n print('-------------------------------------------------------------------------------------------------------------------------------------------')","repo_name":"alessandrosebastianelli/CNNSpeckleFilter","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5519,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"}
+{"seq_id":"18024047087","text":"from resource import Resource\n\n\nclass Campaign(Resource):\n\n _resource_ = 'campaigns'\n\n def __init__(self, **kwargs):\n super(Campaign, self).__init__(**kwargs)\n self.Claim._resource_ = 'campaigns/%s/claims' % self.id\n\n def __repr__(self):\n return self.name\n\n class Claim(Resource):\n _resource_ = None","repo_name":"inkmonk/api-client-python","sub_path":"inkmonk/campaign.py","file_name":"campaign.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"}
+{"seq_id":"42199246468","text":"\nfrom concurrent.futures import thread\nfrom pylibrnp.defaultpackets import processedsensorpacket\nimport cmd2\nimport sys\nfrom cmd2.argparse_custom import Cmd2ArgumentParser\nfrom cmd2.decorators import with_argparser\nfrom pylibrnp.defaultpackets import *\nfrom pylibrnp.rnppacket import *\nimport argparse\nimport time\nimport enum\n\nimport socketio\nimport threading\n\n\nflight_sensor_board_address = 7\nground_sensor_board_address = 16\n\nsensor_update_run = False\n\ndef get_sensor_update_thread(sio,source_address,dt):\n global sensor_update_run\n while sensor_update_run:\n get_sensor_values = SimpleCommandPacket(command=8,arg=0)\n get_sensor_values.header.source_service = 10\n get_sensor_values.header.destination_service = 2\n get_sensor_values.header.source = int(source_address)\n get_sensor_values.header.destination = flight_sensor_board_address\n\n sio.emit('send_data',{'data':get_sensor_values.serialize().hex()},namespace='/packet')\n \n get_sensor_values.header.destination = ground_sensor_board_address\n\n sio.emit('send_data',{'data':get_sensor_values.serialize().hex()},namespace='/packet')\n \n time.sleep(dt/1000)\n print('process killed')\n\n\nclass SI_Sensor_View(cmd2.Cmd):\n sio = socketio.Client(logger=False, engineio_logger=False)\n\n def __init__(self,host='localhost',port=1337):\n super().__init__(allow_cli_args=False) \n\n self.source_address = 4\n \n\n self.thread_handle = None\n self.sensor_data = {}\n \n\n self.sio.connect('http://' + host + ':' + str(port) + '/',namespaces=['/','/packet','/messages'])\n self.sio.on('response',self.on_response_handler,namespace='/packet') \n\n #setting up socketio client and event handler\n\n @sio.event\n def connect():\n print(\"I'm connected!\")\n\n\n # @sio.on('response',namespace='/packet')\n def on_response_handler(self,data):\n print(data)\n try:\n packet = bytes.fromhex(data['data'])\n header = RnpHeader.from_bytes(packet)\n except:\n print(\"Failed to decode header\")\n return\n \n print(header)\n if header.packet_type == 103 and header.destination_service==10:\n sensor_packet = processedsensorpacket.from_bytes(packet)\n if (header.source == ground_sensor_board_address):\n self.sensor_data[\"load\"] = sensor_packet.ch0sens\n self.sensor_data[\"temp1\"] = sensor_packet.ch2sens\n self.sensor_data[\"temp2\"] = sensor_packet.ch3sens\n self.sensor_data[\"hose_p\"] = sensor_packet.ch6sens\n self.sensor_data[\"fill_p\"] = sensor_packet.ch9sens\n\n if (header.source == flight_sensor_board_address):\n self.sensor_data[\"temp3\"] = sensor_packet.ch3sens\n self.sensor_data[\"cham_p\"] = sensor_packet.ch6sens\n self.sensor_data[\"tank_p\"] = sensor_packet.ch9sens\n\n print(self.sensor_data) \n \n \n\n start_ap = Cmd2ArgumentParser()\n start_ap.add_argument('rate',type=int) \n @with_argparser(start_ap)\n def do_start(self,opts):\n global sensor_update_run\n sensor_update_run = False\n time.sleep(0.1)\n sensor_update_run = True\n self.thread_handle = threading.Thread(target = get_sensor_update_thread,args = (self.sio,self.source_address,opts.rate)).start()\n\n def do_stop(self,opts):\n global sensor_update_run\n sensor_update_run= False\n\n @sio.event\n def connect_error(data):\n print(\"The connection failed!\")\n\n @sio.event\n def disconnect():\n print(\"I'm disconnected!\")\n\n #method for serializing and sending command and its argument\n def send_packet(self,packet,destination,source=None,destination_service = 1,source_service = 2,packet_type = 0):\n packet.header.source_service = source_service\n packet.header.destination_service = destination_service\n\n if (source is None):\n source = self.source_address\n\n packet.header.source = int(source)\n packet.header.destination = int(destination)\n packet.header.packet_type = int(packet_type)\n self.sio.emit('send_data',{'data':packet.serialize().hex()},namespace='/packet')\n \n \n def do_quit(self,opts):\n self.sio.disconnect()\n return True\n \n \n\nap = argparse.ArgumentParser()\nap.add_argument('-s',\"--source\",required=False,type=int,default=4,help='Soure Address of packets')\n\nargs = vars(ap.parse_args())\n\n\nif __name__ == \"__main__\":\n si_sensor_view = SI_Sensor_View()\n si_sensor_view.source_address = args['source']\n si_sensor_view.cmdloop()\n","repo_name":"icl-rocketry/Ricardo-Backend-Apps","sub_path":"si_sensors_view.py","file_name":"si_sensors_view.py","file_ext":"py","file_size_in_byte":4702,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"2515629489","text":"from scapy.all import *\nimport sys\nfrom optparse import OptionParser\n\nparser = OptionParser()\nparser.add_option(\"-r\", \"--reverse\", action=\"store_true\", dest=\"reverse\",\n default=False, help=\"Reverse destination and source addresses\")\nparser.add_option(\"\", \"--dest-port\", dest=\"dport\",\n help=\"Filter UDP destination port\")\noptions, args = parser.parse_args()\ninfile, outfile = args\n\npkts = rdpcap(infile)\nout = []\nfor p in pkts:\n if p.haslayer(IP) and p.haslayer(UDP):\n if options.dport is None or options.dport == p[UDP].dport:\n p[IP].chksum = 0\n p[IP].flags = 0\n p[UDP].chksum = 0\n if options.reverse:\n p[UDP].sport, p[UDP].dport = p[UDP].dport, p[UDP].sport\n p[IP].src, p[IP].dst = p[IP].dst, p[IP].src\n p[Ether].src, p[Ether].dst = p[Ether].dst, p[Ether].src\n if len(p) < 60:\n p = Ether(str(p) + '\\0' * (60 - len(p)))\n out.append(p)\n\nwrpcap(outfile, out)\n","repo_name":"acsl-technion/nica","sub_path":"nica/hls/tests/pad_small_packets.py","file_name":"pad_small_packets.py","file_ext":"py","file_size_in_byte":1003,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"31"}
+{"seq_id":"12342880065","text":"#%%\nimport pandas as pd\ndef format_date(date,n=8): # change format if n < 8\n date = str(date)\n formatted_date = date[:4]+\"/\"+date[4:6]+\"/\"+date[6:8]\n formatted_date = formatted_date.replace(\"X\",\"\")\n return formatted_date\n\ndef format_authors(authors):\n sorted_authors = \"\"\n for a in authors.split(\" and \"):\n try:\n last,first = a.split(\", \")\n sorted_authors += first + \" \" + last + \", \"\n except ValueError:\n sorted_authors += a + \", \"\n sorted_authors = sorted_authors[:-2] \n return sorted_authors\n\nfor LANG in [\"\",\"_JP\"]:\n df = pd.read_csv(f\"Patents{LANG}.csv\")\n out_html = \"
Patents
\"\n df = df.sort_values(by = \"Date\", ascending = False).fillna(\"\")\n N = df.shape[0]\n\n out_html += f\"\\n\\t\\n\"\n for i in range(N):\n data = df.iloc[i].astype(str)\n date, status, authors, title, ID = data\n date = format_date(date)\n authors = format_authors(authors)\n out_html += f'\\t\\t
')\n data = delete_tag_with_prarams(data, '')\n data = delete_tag_with_prarams(data, '')\n # data = delete_tag_with_prarams(data, '
')\n\n if '
')\n end_index = data.find('')\n data = data[start_index:end_index]\n data = clean(data)\n\n print('it ran...')\n\n if data == data_copy:\n break\n print('returning: ', data)\n return data\n\n\ndef process(lines):\n list_of_tables = []\n nested_array = []\n print('------------------------------------------------------------------------------------------------------')\n for line in lines:\n if '' in line:\n list_of_tables.append(nested_array)\n nested_array = []\n\n nest = ''\n\n if '
')\n end_index = line.find('')\n data = line[start_index:end_index]\n nest += clean(data)\n nested_array.append(nest)\n\n if '
')\n end_index = line.rfind('')\n\n print(start_index, \" | \", end_index)\n data = line[start_index + 1:end_index]\n nest += clean(data)\n nested_array.append(nest)\n\n # # next to create: list of tables\n # if len(nest) > 0:\n # nested_array.append(nest)\n\n return list_of_tables\n\n\nlist_of_nested_arrays = []\nnested_array = []\nlines = []\nflip = False\n\nfor line in htmlSplit:\n if '
' in line:\n flip = False\n nested_array = process(lines)\n list_of_nested_arrays.append(nested_array)\n for i in nested_array:\n print(i)\n # exit()\n\nprint('=========================================================')\nfor array in list_of_nested_arrays:\n print(pd.DataFrame(array).head())\n","repo_name":"alik604/cyber-security","sub_path":"Utilities/Get HTML tables/get HTML tables.py","file_name":"get HTML tables.py","file_ext":"py","file_size_in_byte":4157,"program_lang":"python","lang":"en","doc_type":"code","stars":150,"dataset":"github-code","pt":"31"}
+{"seq_id":"42314779362","text":"# Continuation of #108\n# For n = p1^a1 * p2^a2 * ..., obvious realization that a1 >= a2 >= ...\nsmall_primes = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43) # 3^14 > 4 million\npow_list = []\n\ndef gen_pow_list(l):\n if len(l) == 14:\n global pow_list\n pow_list.append(l)\n else:\n for i in range(l[-1] + 1):\n gen_pow_list(l + [i])\n\n\nfor i in range(1, 5):\n gen_pow_list([i])\n\nleast_n = 10**20\nfor l in pow_list:\n d = 1\n for a in l:\n d *= 2*a + 1\n if d > 2*4000000 - 1:\n n = 1\n for i in range(len(l)):\n n *= small_primes[i] ** l[i]\n least_n = min(least_n, n)\n\nprint(least_n)\n","repo_name":"jxu/PyPE","sub_path":"src/110.py","file_name":"110.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"13441473462","text":"import queue\ndef s(n,m,a,b,c)->list:\n d=[[0 for _ in range(m) ] for _ in range(n)]\n q=queue.Queue()\n q.put((a,b,c), )\n while not q.empty():\n a,b,c=q.get()\n if not (0<=a' and int(stack[-1]) > i):\n stack.append(str(i))\n bt(n+1)\n stack.pop()\n\nk = int(input())\nop = input().split()\nvisited = [0]*10\nmin_v = int('9'*(k+1))\nmax_v = 0\nstack = []\nbt(0)\nprint(max_v)\nprint(str(min_v).zfill(k+1))","repo_name":"SSAFY-algamza/ssafy-algorithm-study","sub_path":"f1rstf1y9/BOJ/BOJ_2529_부등호.py","file_name":"BOJ_2529_부등호.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"12679000945","text":"from PVG import *\r\n\r\nrender = Canvas(\"main_closure.png\").render()\r\n\r\n# polygon1 = square(P0,1.0)\r\npolygon1 = Circle(Point(0.0,0.0),1.0).polygon(4)\r\npolygon2 = Circle(Point(1.0,0.0),1.0).polygon(4)\r\n# polygon2 = square(Point(0.5,0.5),1.0)\r\nrender.drawpolygons([polygon1,polygon2],Color.red(0.5))\r\n\r\nrandom.seed(0.0)\r\nfor (spoly1,spoly2) in polygon2.closures(polygon1):\r\n render.drawpolygons([poly.reduce(0.9) for poly in [spoly1,spoly2]],Color.rand(0.5))\r\n\r\nrender.end()\r\n\r\n","repo_name":"JulienLeonard/PVG","sub_path":"examples/main_closure.py","file_name":"main_closure.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"31"}
+{"seq_id":"12386850802","text":"from bs4 import BeautifulSoup\nimport requests\nimport re\n\n\ndef WebScraping():\n \n URL = 'https://en.wikipedia.org/wiki/List_of_computer_scientists'\n\n response = requests.get(URL)\n\n soup = BeautifulSoup(response.text, 'html.parser')\n ul_elements = soup.find_all('ul')\n\n scientists_data = []\n\n # RE to match English letters only\n english_letters = re.compile(r'^[a-zA-Z\\s-]+$')\n \n valuable_data=1\n # Loop the
elements and extract scientist info\n for ul_element in ul_elements:\n # Find the li elements\n li_elements = ul_element.find_all('li')\n for li_element in li_elements:\n surname = \"\"\n awards = 0\n education = \"None\"\n \n text = re.sub(r'\\([^)]*\\)', '', li_element.get_text().strip())\n parts = text.split('–', 1)\n \n if len(parts) == 1:\n if(81 large:\n large = product\n product = 1\n for k in range(4):\n product *= grid[x + k][y]\n if product > large:\n large = product\nfor y in range(20 - 3):\n for x in range(20 - 3):\n product = 1\n for k in range(4):\n product *= grid[y + k][x + k]\n if product > large:\n large = product\n product = 1\n for k in range(4):\n product *= grid[y + k][x - k + 3]\n if product > large:\n large = product\nprint(large)\n","repo_name":"nsid10/Project-euler","sub_path":"problems/011.py","file_name":"011.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"33446166780","text":"# -*- coding: utf-8 -*-\n# @author: vuolter\n\nfrom __future__ import absolute_import, unicode_literals\n\nimport os\nimport re\nimport sys\n\nfrom future import standard_library\n\nstandard_library.install_aliases()\n\n\ndef chars(text, chars, repl=''):\n return re.sub(r'[{0}]+'.format(chars), repl, text)\n\n\n_UNIXBADCHARS = ('\\0', '/', '\\\\')\n_MACBADCHARS = _UNIXBADCHARS + (':',)\n_WINBADCHARS = _MACBADCHARS + ('<', '>', '\"', '|', '?', '*')\n_WINBADWORDS = (\n 'com1', 'com2', 'com3', 'com4', 'com5', 'com6', 'com7', 'com8', 'com9',\n 'lpt1', 'lpt2', 'lpt3', 'lpt4', 'lpt5', 'lpt6', 'lpt7', 'lpt8', 'lpt9',\n 'con', 'prn')\n\ndef name(text, sep='_', allow_whitespaces=False):\n \"\"\"\n Remove invalid characters.\n \"\"\"\n if os.name == 'nt':\n bc = _WINBADCHARS\n elif sys.platform == 'darwin':\n bc = _MACBADCHARS\n else:\n bc = _UNIXBADCHARS\n repl = r''.join(bc)\n if not allow_whitespaces:\n repl += ' '\n name = chars(text, repl, sep).strip()\n if os.name == 'nt' and name.lower() in _WINBADWORDS:\n name = sep + name\n return name\n\n\ndef pattern(text, rules):\n for rule in rules:\n try:\n pattr, repl, flags = rule\n except ValueError:\n pattr, repl = rule\n flags = 0\n text = re.sub(pattr, repl, text, flags)\n return text\n\n\ndef truncate(text, offset):\n maxtrunc = len(text) // 2\n if offset > maxtrunc:\n raise ValueError(\"String too short to truncate\")\n trunc = (len(text) - offset) // 3\n return \"{0}~{1}\".format(text[:trunc * 2], text[-trunc:])\n\n\ndef uniqify(seq):\n \"\"\"\n Remove duplicates from list preserving order.\n \"\"\"\n seen = set()\n seen_add = seen.add\n return type(seq)(x for x in seq if x not in seen and not seen_add(x))\n","repo_name":"pyblub/notpyload","sub_path":"src/pyload/utils/purge.py","file_name":"purge.py","file_ext":"py","file_size_in_byte":1768,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"17304676435","text":"import json\n\nfrom internal.classes.domain.classes import Classes\nfrom internal.classes.infrastructure.repository.json.dto.classes import ClassesDTO\n\n\nclass DTOClassesMapperRead:\n def dto_class_to_domain(self, class_obj: ClassesDTO) -> Classes:\n pass\n\n\nclass ClassesRepositoryRead(DTOClassesMapperRead):\n def __init__(self, mapper: DTOClassesMapperRead, filename_classes: str):\n self.mapper = mapper\n self.filename_classes = filename_classes\n\n def get_class_by_class_id(self, class_id: str) -> Classes:\n try:\n with open(self.filename_classes, 'r') as file:\n class_data = json.load(file)\n\n if class_id not in class_data:\n raise Exception(f\"No class found for class_id: {class_id}\")\n\n class_dto = ClassesDTO(**class_data[class_id])\n class_domain = self.mapper.dto_class_to_domain(class_dto)\n\n return class_domain\n except Exception as e:\n raise e\n","repo_name":"julianVelandia/ClassAndStudentAPIPython","sub_path":"internal/classes/infrastructure/repository/json/read/classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"2709605478","text":"\nfrom app.api.abstract_facade import JSONAPIAbstractFacade\nfrom app.models import PersonHasRole\n\n\nclass PersonHasRoleFacade(JSONAPIAbstractFacade):\n \"\"\"\n\n \"\"\"\n TYPE = \"person-has-role\"\n TYPE_PLURAL = \"persons-having-roles\"\n\n MODEL = PersonHasRole\n\n @property\n def id(self):\n return self.obj.id\n\n @property\n def resource(self):\n resource = {\n **self.resource_identifier,\n \"attributes\": {\n \"function\": self.obj.function,\n \"field\": self.obj.field\n },\n \"meta\": self.meta,\n \"links\": {\n \"self\": self.self_link\n }\n }\n\n if self.with_relationships_links:\n resource[\"relationships\"] = self.get_exposed_relationships()\n return resource\n\n def __init__(self, *args, **kwargs):\n super(PersonHasRoleFacade, self).__init__(*args, **kwargs)\n \"\"\"Make a JSONAPI resource object describing what is the relation between a person and its role within a document\n \"\"\"\n # ===================================\n # Add simple relationships\n # ===================================\n from app.api.document.facade import DocumentFacade\n from app.api.person.facade import PersonFacade\n from app.api.person_role.facade import PersonRoleFacade\n\n for rel_name, (rel_facade, to_many) in {\n \"person-role\": (PersonRoleFacade, False),\n \"document\": (DocumentFacade, False),\n \"person\": (PersonFacade, False),\n }.items():\n u_rel_name = rel_name.replace(\"-\", \"_\")\n\n self.relationships[rel_name] = {\n \"links\": self._get_links(rel_name=rel_name),\n \"resource_identifier_getter\": self.get_related_resource_identifiers(rel_facade, u_rel_name, to_many),\n \"resource_getter\": self.get_related_resources(rel_facade, u_rel_name, to_many),\n }\n\n def get_data_to_index_when_added(self, propagate):\n return self.get_relationship_data_to_index(rel_name=\"person\")\n\n\nclass PersonHasRoleIncludedFacade(PersonHasRoleFacade):\n def __init__(self, *args, **kwargs):\n super(PersonHasRoleIncludedFacade, self).__init__(*args, **kwargs)\n\n @property\n def resource(self):\n resource = {\n **self.resource_identifier,\n \"attributes\": {\n \"function\": self.obj.function,\n \"field\": self.obj.field,\n \"person_id\": self.obj.person_id,\n \"document_id\": self.obj.document_id,\n \"role_id\": self.obj.person_role_id,\n \"document_title\": self.obj.document.title,\n \"document_creation_label\": self.obj.document.creation_label\n },\n \"meta\": self.meta,\n \"links\": {\n \"self\": self.self_link\n }\n }\n\n return resource\n","repo_name":"chartes/lettres-app","sub_path":"app/api/person_has_role/facade.py","file_name":"facade.py","file_ext":"py","file_size_in_byte":2923,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"}
+{"seq_id":"274095617","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Mar 21 20:06:50 2020\r\n\r\n@author: Pratiksha\r\n\r\nThis function analyses a list/string and helps to return the top n entities\r\nin the list/string according to their number of occurences in descending order\r\nwhere n is a number that is specified by the programmer.\r\n\r\n\"\"\"\r\n\r\nfrom collections import Counter \r\n \r\narr =list(map(int,input('Enter the list : ').split())) \r\ntop=int(input('Enter number of values required : '))\r\ncounter = Counter(arr) \r\ntop_values = counter.most_common(top) \r\nprint(top_values) ","repo_name":"PratikshaDanti/APS","sub_path":"Code Library/54.Counter_Demo.py","file_name":"54.Counter_Demo.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"15087860884","text":"#!/usr/bin/env python2.7\n# Python 2.7 version by Alex Eames of http://RasPi.TV \n# functionally similar to the Gertboard motor test by Gert Jan van Loo & Myra VanInwegen\n# Use at your own risk - I'm pretty sure the code is harmless, but check it yourself.\n# It works pretty well on Raspbian August 2012, but stutters a bit on the September release\n\nfrom __future__ import print_function # all print statements in this prog must now be in python 3 format\nimport RPi.GPIO as GPIO\nimport sys\nfrom time import sleep\n\nGPIO.setmode(GPIO.BCM)\nports = [18,17] # define which ports to be pulsed (using a list)\nReps = 400 # 2000 Hz cycle time, so Reps=400 is 0.2s for each percentage ON\nHertz = 2000 # Cycle time. You can tweak this, Max 3000 \nFreq = (1 / float(Hertz)) - 0.0003 # run_motor loop code takes 0.0003s\n\nfor port_num in ports: # set the ports up for output\n GPIO.setup(port_num, GPIO.OUT) # set up GPIO output channel\n print (\"setting up GPIO port:\", port_num)\n GPIO.output(port_num, False) # set both ports to OFF\n \ndef run_motor(Reps, pulse_width, port_num, time_period):\n try: # try: except:, traps errors\n for i in range(0, Reps):\n GPIO.output(port_num, True) # switch port on\n sleep(pulse_width) # make sure pulse stays on for correct time\n GPIO.output(port_num, False) # switch port off\n sleep(time_period) # time_period for port OFF defined in run_loop\n except KeyboardInterrupt: # reset all ports used by this program if CTRL-C pressed\n GPIO.cleanup()\n\ndef run_loop(startloop, endloop, step, port_num, printchar):\n for pulse_width_percent in range(startloop, endloop, step):\n print (printchar, sep='', end='')\n sys.stdout.flush()\n pulse_width = pulse_width_percent / float(100) * Freq # define exact pulse width\n time_period = Freq - (Freq * pulse_width_percent / float(100)) # sleep period needed to get required Hz\n run_motor(Reps, pulse_width, port_num, time_period)\n print(\"\") # print line break between runs\n\nprint (\"\\nThese are the connections for the motor test:\") # Print wiring instructions\nprint (\"GP17 in J2 --- MOTB (just above GP1)\")\nprint (\"GP18 in J2 --- MOTA (just above GP4)\")\nprint (\"+ of external power source --- MOT+ in J19\")\nprint (\"ground of external power source --- GND (any)\")\nprint (\"one wire for your motor in MOTA in J19\")\nprint (\"the other wire for your motor in MOTB in J19\")\ncommand = raw_input(\"When ready hit enter.\\n>\")\n\nprint (\">>>\", sep='', end='')\nrun_loop(5, 95, 1, 18,'+') # (startloop, endloop, step, port_num, printchar, loopnum)\nrun_loop(95, 5, -1, 18,'-') # if you go all the way to 100% it seems out of control at the changeover\nsleep(0.2) # a slight pause before change direction stops sudden motor jerking\nprint (\"<<<\", sep='', end='')\nrun_loop(5, 95, 1, 17,'+')\nrun_loop(95, 5, -1, 17,'-')\n\nGPIO.output(port_num, False) # Finish up: set both ports to off\nGPIO.cleanup() # reset all ports used by this program on finishing\n","repo_name":"Ambella/Electronics","sub_path":"RPi/GertBoard/GB_Python/motor-rg.py","file_name":"motor-rg.py","file_ext":"py","file_size_in_byte":3621,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"32808311208","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\nimport django.utils.timezone\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Admin_code',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, serialize=False, auto_created=True)),\n ('code', models.CharField(verbose_name='API用密链', max_length=50, default='test')),\n ],\n ),\n migrations.CreateModel(\n name='Authorization',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, serialize=False, auto_created=True)),\n ('customer_QQ', models.PositiveIntegerField(verbose_name='客户的QQ')),\n ('bot_QQ', models.PositiveIntegerField(verbose_name='机器人的QQ')),\n ('begin_time', models.DateField(verbose_name='创建时间', auto_now_add=True)),\n ('deadline_time', models.DateField(verbose_name='到期时间', default=django.utils.timezone.now)),\n ('proxy_man', models.ForeignKey(verbose_name='代理', to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.CreateModel(\n name='Others_info',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, serialize=False, auto_created=True)),\n ('balance', models.PositiveIntegerField(verbose_name='用户余额', default=0)),\n ('ad', models.CharField(verbose_name='代理广告', max_length=30)),\n ('TOKEN', models.CharField(verbose_name='API密链', max_length=15, unique=True)),\n ('user', models.OneToOneField(to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.CreateModel(\n name='Software',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, serialize=False, auto_created=True)),\n ('software_id', models.PositiveIntegerField(verbose_name='软件ID', unique=True)),\n ('software_name', models.CharField(verbose_name='软件名', max_length=30)),\n ('software_version_number', models.CharField(verbose_name='软件版本号', max_length=30, default='V1.0')),\n ('software_each_time', models.PositiveIntegerField(verbose_name='套餐时间(按小时计算)', default=720)),\n ('software_cost', models.PositiveIntegerField(verbose_name='套餐价格', default=10)),\n ],\n ),\n migrations.CreateModel(\n name='Time_code',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, serialize=False, auto_created=True)),\n ('time', models.PositiveIntegerField(verbose_name='时长')),\n ('code', models.CharField(verbose_name='卡密', max_length=10)),\n ('cost', models.PositiveIntegerField(verbose_name='价格')),\n ('used', models.BooleanField(verbose_name='是否使用过', default=False)),\n ('proxy_man', models.ForeignKey(verbose_name='代理', null=True, to=settings.AUTH_USER_MODEL)),\n ('software', models.ForeignKey(verbose_name='软件对象', to='main_app.Software')),\n ],\n ),\n migrations.AddField(\n model_name='authorization',\n name='software',\n field=models.ForeignKey(verbose_name='软件对象', to='main_app.Software'),\n ),\n ]\n","repo_name":"simplerjiang/proxy_code_system","sub_path":"main_app/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":3718,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"31"}
+{"seq_id":"44801907718","text":"# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html\n\n\n# useful for handling different item types with a single interface\nfrom itemadapter import ItemAdapter\nimport sqlite3\nimport pickle\n\nclass OryxPipeline:\n def __init__(self):\n with open('name.p', 'rb') as file:\n self.name = pickle.load(file)\n self.create_connection() \n \n def create_connection(self):\n self.conn = sqlite3.connect(self.name + \".db\")\n self.curr = self.conn.cursor()\n \n def process_item(self, item, spider):\n self.store_db(item)\n\n return item\n\n def store_db(self, item):\n self.curr.execute(\"\"\"insert into quotes_tb values (?,?,?,?)\"\"\", (\n item['data'],\n item['country'],\n item['staf'],\n item['content']\n ))\n \n self.conn.commit()","repo_name":"pawelgoj/exemplary_scraping_project","sub_path":"oryx/oryx/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"70441688408","text":"#!/usr/bin/env python3\nimport sys\ndef get_suffix(filename, has_dot=False):\n '''\n Get suffix of file\n\n :param filename: filename\n :param has_dot: Do the returned suffix names need to be dotted\n :return: suffix\n '''\n pos = filename.rfind('.')\n if 0 < pos < len(filename) - 1:\n index = pos if has_dot else pos + 1\n return filename[index:]\n else:\n return ''\n\nif __name__ == '__main__':\n print(get_suffix(sys.argv[1]))\n","repo_name":"Yao-Phoenix/day_code","sub_path":"suffix.py","file_name":"suffix.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"31146004269","text":"import random\nfrom typing import List\nfrom agent import Agent\nfrom information import Information\nfrom position import Position\nfrom grid import Grid\n\ndef main():\n random.seed(42)\n g = Grid()\n print(g)\n\n print(\"### TESTING ADD AGENT ###\")\n ################# testing addAgent\n p = Position(1,1)\n g._addAgent(p)\n print(len(g._agents))\n print(g)\n\n #agent30 = g._findAgent(30)\n #print(g._agentsInRange(agent30)[0])\n ############## testing agentInRange when spread radius is 1\n print(\"### TESTING AGENT IN RANGE RANGE 1 ###\")\n agent9 = g._findAgent(9)\n p2 = Position(1,3)\n g._addAgent(p2)\n #test = g._agentsInRange(agent9)\n #for a in test:\n #print(a)\n\n ############ testing agentInRange when spread radius is 2\n print(\"### TESTING AGENT IN RANGE RANGE 2 ###\")\n test = g._agentsInRange(agent9)\n for a in test:\n print(a)\n \n ########## testing algorithm\n print(\"### TESTING ALGORITHM\")\n\n #agent12 = g._findAgent(12)\n #test = g._agentsInRange(agent12)\n agent_ = g._findAgent(12) #25\n #print(agent_)\n test = g._agentsInRange(agent_)\n for a in test:\n print(a)\n\n print(g)\n random.seed(40)\n g.simulate(1)\n\n\n\nmain()\n","repo_name":"AruPV/FinalProject","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1227,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"34354456127","text":"import torch\nimport torch.nn as nn\n\nimport torch.nn.functional as F\n\nclass BaseModule(nn.Module):\n def __init__(self):\n super().__init__()\n self.conv1 = nn.Conv2d(3, 8, 5, padding=1)\n self.max_pool1 = nn.MaxPool2d(kernel_size=2)\n self.conv2 = nn.Conv2d(8, 16, kernel_size=3, padding=1)\n self.max_pool2 = nn.MaxPool2d(kernel_size=2)\n self.conv3 = nn.Conv2d(16, 32, kernel_size= 1, padding=1)\n\n def forward(self, x):\n x = self.conv1(x)\n x = torch.relu(x)\n x = self.max_pool1(x)\n x = self.conv2(x)\n x = torch.relu(x)\n x = self.max_pool2(x)\n x = self.conv3(x)\n\n return x\n\n\nclass FinalClassifier(nn.Module):\n def __init__(self):\n super().__init__()\n self.fc1 = nn.Linear(32*9*9, 10)\n self.sm = nn.Softmax(-1)\n\n def forward(self, x):\n x = x.view(x.size()[0], -1)\n x = self.fc1(x)\n return self.sm(x)\n # return x\n\n\nclass ConfidenceEval(nn.Module):\n def __init__(self):\n super().__init__()\n self.conv1 = nn.Conv2d(32, 16, 1)\n self.max_pool1 = nn.MaxPool2d(kernel_size=2)\n self.fc1 = nn.Linear(256, 1)\n\n def forward(self, x):\n x = self.conv1(x)\n x = torch.relu(x)\n x = self.max_pool1(x)\n x = x.view(x.size(0), -1)\n x = self.fc1(x)\n return torch.tanh(x)\n\nclass QueryMachine(nn.Module):\n def __init__(self):\n super().__init__()\n self.conv1 = nn.Conv2d(32, 64, 1)\n self.conv2 = nn.Conv2d(64, 16, 1)\n # self.max_pool = nn.MaxPool2d(kernel_size=3)\n\n def forward(self, x):\n x = self.conv1(x)\n # x = torch.relu(x)\n\n # x = self.max_pool(x)\n return x\n\nclass AnsMachine(nn.Module):\n def __init__(self):\n super().__init__()\n self.conv1 = nn.Conv2d(32 + 16, 64, kernel_size=1)\n self.conv2 = nn.Conv2d(64, 32, kernel_size=1)\n self.batch_norm = nn.BatchNorm2d(32)\n def forward(self, x, q):\n unified = torch.cat((q, x), dim=1)\n unified = F.relu(self.conv1(unified))\n unified = F.relu(self.conv2(unified))\n unified = self.batch_norm(unified)\n return torch.tanh(unified)\n\n\n\n\nclass TM(nn.Module):\n def __init__(self, device, conf_threshold = 0.0, max_depth= 15):\n super().__init__()\n self.device = device\n self.base_module = BaseModule()\n self.max_depth = max_depth\n self.conf_threshold = conf_threshold\n self.f_cls = FinalClassifier()\n self.conf_eval = ConfidenceEval()\n self.q_m = QueryMachine()\n self.a_m = AnsMachine()\n\n def forward(self, mini_batch, compute_outputs = True):\n #todo different forward for train and eval\n\n all_confs = []\n all_f_cls = []\n\n batch_size = len(mini_batch)\n\n actual_depth = torch.ones(batch_size, device=self.device, dtype=torch.long) * self.max_depth\n\n x = self.base_module(mini_batch)\n\n depth = 0\n\n while depth < self.max_depth and (self.training or actual_depth.max() == self.max_depth):\n depth += 1\n current_confs = self.conf_eval(x)\n\n # print(\"CONF: \",current_confs.mean())\n current_f_cls = self.f_cls(x)\n acceptable_conf = (( current_confs.squeeze() < self.conf_threshold).nonzero()).view(-1)\n\n # print(acceptable_conf)\n\n depth_tensor = torch.ones(len(acceptable_conf), device= self.device, dtype=torch.long) * depth\n actual_depth[acceptable_conf] = torch.min(input = actual_depth[acceptable_conf], other = depth_tensor)\n\n all_confs.append(current_confs)\n all_f_cls.append(current_f_cls)\n\n q = self.q_m(x)\n a = self.a_m(x, q)\n\n x = x + a\n\n if self.training:\n all_f_cls.append(self.f_cls(x))\n\n outputs = []\n\n all_f_cls = torch.stack(all_f_cls).transpose(0, 1)\n all_confs = torch.stack(all_confs).transpose(0, 1).squeeze(-1)\n\n if compute_outputs:\n for sample_idx in range(batch_size):\n outputs.append(all_f_cls[sample_idx, actual_depth[sample_idx] - 1, :])\n outputs = torch.stack(outputs)\n\n if self.training:\n return outputs, all_f_cls, all_confs, actual_depth\n else:\n return outputs\n\n\n","repo_name":"Tensor-Reloaded/Thinking-Machine","sub_path":"tm/thinking_machine.py","file_name":"thinking_machine.py","file_ext":"py","file_size_in_byte":4346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"4142428429","text":"\"\"\"\n5/11/2023 by Zehao Li\n\nThis script defines the Screen class for a Pygame-based graphical user interface. The main function of this class is\nto display video feed from a camera and overlay it with text messages. The display is set up to work specifically on\na Raspberry Pi device with a PiTFT touchscreen. The video feed can be processed for errors and adjusted for display\nrequirements. The class also handles user interactions with the touchscreen.\n\"\"\"\nimport cv2\nimport pygame\nimport numpy as np\nimport time\nimport os\n\n\n# Defining a Screen class for video feed display and user interface operations\nclass Screen():\n def __init__(self):\n super()\n self.font = None\n self.lcd = None\n self.init_pygame()\n self.message = None\n self.message_start_time = None\n self.frame = None\n self.surface = None\n\n # Initialize Pygame with necessary settings\n def init_pygame(self):\n # Setting up the video driver and mouse driver\n os.environ[\"SDL_VIDEODRIVER\"] = \"fbcon\"\n os.putenv('SDL_FBDEV', '/dev/fb0') #\n os.putenv('SDL_MOUSEDRV', 'TSLIB') # Track mouse clicks on piTFT\n os.putenv('SDL_MOUSEDEV', '/dev/input/touchscreen')\n pygame.init()\n # Setting up the display\n self.lcd = pygame.display.set_mode((320, 240))\n pygame.mouse.set_visible(False)\n self.font = pygame.font.Font(None, 30) # Choose font size and type\n\n # Method to process a frame for display\n def get_processed_frame(self):\n frame = self.frame\n ret, buffer = cv2.imencode('.jpg', frame)\n frame = buffer.tobytes()\n return frame\n\n # Method to update the displayed frame from the camera feed\n def update_from_camera(self, frame, roll_error=None):\n # Checking if a valid frame was provided\n if frame is not None and not frame.size == 0:\n # Checking if a roll error was provided\n if roll_error is not None:\n # Rotate the image with the degrees of roll error to balance the video frame\n rotation_matrix = cv2.getRotationMatrix2D((320, 240), -roll_error, 1)\n rotated_frame = cv2.warpAffine(frame, rotation_matrix, (640, 480))\n cropped_frame = rotated_frame[120:380, 100:500]\n self.frame = cropped_frame\n frame = cv2.resize(cropped_frame, (320, 240), interpolation=cv2.INTER_NEAREST)\n # Convert the color format from BGR to RGB for display with Pygame\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # Convert to RGB format for Pygame\n else:\n # Resizing and converting the color format of the frame if no roll error was provided\n self.frame = frame\n frame = cv2.resize(frame, (320, 240), interpolation=cv2.INTER_NEAREST)\n # Convert the color format from BGR to RGB for display with Pygame\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # Convert to RGB format for Pygame\n\n # Rotating and flipping the frame for correct orientation\n frame = np.rot90(frame)\n frame = np.flipud(frame)\n # Creating a Pygame surface from the frame\n surface = pygame.surfarray.make_surface(frame)\n # Convert the frame surface to the same format as the destination surface (self.lcd)\n surface = surface.convert(self.lcd)\n # Displaying the frame on the screen\n self.lcd.blit(surface, (0, 0))\n self.surface = surface\n\n # Displaying a message on the screen for 2 seconds\n if self.message and self.message_start_time:\n if time.time() - self.message_start_time < 2:\n text_surface = self.font.render(self.message, True, (255, 255, 255))\n text_width, text_height = text_surface.get_size()\n text_position = (160 - text_width // 2, 120 - text_height // 2)\n self.lcd.blit(text_surface, text_position) # Position the message on the screen\n else:\n self.message = None\n self.message_start_time = None\n # Update the Pygame display\n pygame.display.update()\n else:\n # If no frame was provided, keep displaying the last frame\n if self.surface is not None:\n self.lcd.blit(self.surface, (0, 0))\n pygame.display.update()\n\n # Method to set a message to be displayed on the screen\n def show_message(self, message):\n self.message = message\n self.message_start_time = time.time()\n","repo_name":"xalzh/ECE5725-Final-Project","sub_path":"Update_Screen.py","file_name":"Update_Screen.py","file_ext":"py","file_size_in_byte":4680,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"33993312868","text":"class AdjacencyList:\n def __init__(self, nodes):\n self.Nodes = nodes\n self.adj_list = {}\n \n for node in self.Nodes:\n self.adj_list[node] = []\n \n def add_edge(self, u, v):\n self.adj_list[u].append(v)\n self.adj_list[v].append(u)\n\n def print_adj_list(self):\n print(\"\\nAdjacency List\")\n for node in self.Nodes:\n print(node,\"->\", self.adj_list[node])\n \n \nnodes = [\"A\", \"B\", \"C\", \"D\", \"E\"]\ngraph = AdjacencyList(nodes)\n\nall_edges = [\n (\"A\", \"B\"),\n (\"A\", \"C\"),\n (\"B\", \"D\"),\n (\"C\", \"D\"),\n (\"C\", \"E\"),\n (\"D\", \"E\"),\n]\n\nfor u, v in all_edges:\n graph.add_edge(u, v)\n\ngraph.print_adj_list()","repo_name":"virajSandakelum/Graph-Theory","sub_path":"AdjacencyList.py","file_name":"AdjacencyList.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"37805656187","text":"from pdf2image import convert_from_path\r\nimport pytesseract\r\nimport util\r\nfrom backend.src.parser_prescription import PrescriptionParser\r\nfrom backend.src.parser_patientdetails import PatientDetailsParser\r\n\r\n#poppler is used for image to pdf conversion\r\n#pytesseract is used for image to string conversion\r\n\r\nPOPPLER_PATH = r'C:\\poppler-22.04.0\\Library\\bin'\r\npytesseract.pytesseract.tesseract_cmd=r'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'\r\n\r\ndef extract(file_path,file_format):\r\n # extraction text from pdf file\r\n pages = convert_from_path(file_path, poppler_path=POPPLER_PATH)\r\n document_text = ''\r\n #for page in pages:\r\n if len(pages)>0:\r\n page = pages[0]\r\n processed_image = util.preprocess_image(page)\r\n text = pytesseract.image_to_string(processed_image, lang=\"eng\")\r\n document_text = '\\n' + text\r\n #step 2 : check file format\r\n if file_format == 'prescription':\r\n extracted_data = PrescriptionParser(document_text).parse()\r\n elif file_format =='patient_details':\r\n extracted_data = PatientDetailsParser(document_text).parse()\r\n else:\r\n raise Exception(f\"Invalid File format: {file_format}\")\r\n #step 3 : Return the data\r\n return extracted_data\r\nif __name__ == '__main__':\r\n data = extract('../resources/patient_details/pd_1.pdf','patient_details')\r\n print(data)\r\n","repo_name":"Shindeanita/MedicalOCRProject","sub_path":"backend/src/extractor.py","file_name":"extractor.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"}
+{"seq_id":"73342946647","text":"\"\"\"\nConvert human reviewed submissions from a workflow to a 'labeled data'format and writes it to CSV.\n\"\"\"\nfrom indico_toolkit.staggered_loop import StaggeredLoop\nfrom indico_toolkit import create_client\n\n\nclient = create_client(\"app.indico.io\", \"./indico_api_token.txt\")\nstagger = StaggeredLoop(client)\n# workflow_id is required, but optionally specify submission ids to include and \n# the specific model name if more than 1 in workflow\nstagger.get_reviewed_prediction_data(\n workflow_id=412, submission_ids=[123, 415, 987], model_name=\"model_v1\"\n)\nstagger.write_csv(\"./data_to_add_to_model.csv\")\n","repo_name":"IndicoDataSolutions/Indico-Solutions-Toolkit","sub_path":"examples/staggered_loop.py","file_name":"staggered_loop.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"31"}
+{"seq_id":"30904641417","text":"import torch\nimport torch.nn.functional as F\n\n\ndef bdcn_loss2(inputs, targets, l_weight=1.1):\n # bdcn loss modified in DexiNed\n\n targets = targets.long()\n mask = targets.float()\n num_positive = torch.sum((mask > 0.0).float()).float() # >0.1\n num_negative = torch.sum((mask <= 0.0).float()).float() # <= 0.1\n\n mask[mask > 0.] = 1.0 * num_negative / (num_positive + num_negative) #0.1\n mask[mask <= 0.] = 1.1 * num_positive / (num_positive + num_negative) # before mask[mask <= 0.1]\n inputs= torch.sigmoid(inputs)\n cost = torch.nn.BCELoss(mask, reduction='none')(inputs, targets.float())\n cost = torch.sum(cost.float().mean((1, 2, 3))) # before sum\n return l_weight*cost\n\n# ------------ cats losses ----------\n\ndef bdrloss(prediction, label, radius,device='cpu'):\n '''\n The boundary tracing loss that handles the confusing pixels.\n '''\n\n filt = torch.ones(1, 1, 2*radius+1, 2*radius+1)\n filt.requires_grad = False\n filt = filt.to(device)\n\n bdr_pred = prediction * label\n pred_bdr_sum = label * F.conv2d(bdr_pred, filt, bias=None, stride=1, padding=radius)\n\n\n\n texture_mask = F.conv2d(label.float(), filt, bias=None, stride=1, padding=radius)\n mask = (texture_mask != 0).float()\n mask[label == 1] = 0\n pred_texture_sum = F.conv2d(prediction * (1-label) * mask, filt, bias=None, stride=1, padding=radius)\n\n softmax_map = torch.clamp(pred_bdr_sum / (pred_texture_sum + pred_bdr_sum + 1e-10), 1e-10, 1 - 1e-10)\n cost = -label * torch.log(softmax_map)\n cost[label == 0] = 0\n\n return torch.sum(cost.float().mean((1, 2, 3)))\n\n\n\ndef textureloss(prediction, label, mask_radius, device='cpu'):\n '''\n The texture suppression loss that smooths the texture regions.\n '''\n filt1 = torch.ones(1, 1, 3, 3)\n filt1.requires_grad = False\n filt1 = filt1.to(device)\n filt2 = torch.ones(1, 1, 2*mask_radius+1, 2*mask_radius+1)\n filt2.requires_grad = False\n filt2 = filt2.to(device)\n\n pred_sums = F.conv2d(prediction.float(), filt1, bias=None, stride=1, padding=1)\n label_sums = F.conv2d(label.float(), filt2, bias=None, stride=1, padding=mask_radius)\n\n mask = 1 - torch.gt(label_sums, 0).float()\n\n loss = -torch.log(torch.clamp(1-pred_sums/9, 1e-10, 1-1e-10))\n loss[mask == 0] = 0\n\n return torch.sum(loss.float().mean((1, 2, 3)))\n\n\ndef cats_loss(prediction, label, l_weight=[0.,0.], device='cpu'):\n # tracingLoss\n\n tex_factor,bdr_factor = l_weight\n balanced_w = 1.1\n label = label.float()\n prediction = prediction.float()\n with torch.no_grad():\n mask = label.clone()\n\n num_positive = torch.sum((mask == 1).float()).float()\n num_negative = torch.sum((mask == 0).float()).float()\n beta = num_negative / (num_positive + num_negative)\n mask[mask == 1] = beta\n mask[mask == 0] = balanced_w * (1 - beta)\n mask[mask == 2] = 0\n prediction = torch.sigmoid(prediction)\n\n cost = torch.nn.functional.binary_cross_entropy(\n prediction.float(), label.float(), weight=mask, reduction='none')\n cost = torch.sum(cost.float().mean((1, 2, 3))) # by me\n label_w = (label != 0).float()\n textcost = textureloss(prediction.float(), label_w.float(), mask_radius=4, device=device)\n bdrcost = bdrloss(prediction.float(), label_w.float(), radius=4, device=device)\n\n return cost + bdr_factor * bdrcost + tex_factor * textcost","repo_name":"xavysp/LDC","sub_path":"loss2.py","file_name":"loss2.py","file_ext":"py","file_size_in_byte":3396,"program_lang":"python","lang":"en","doc_type":"code","stars":98,"dataset":"github-code","pt":"31"}
+{"seq_id":"29918801976","text":"import os\nfrom django import forms\nfrom django.contrib.auth.models import User\nfrom django.forms import Textarea, TextInput, NullBooleanSelect, Select\nfrom django.contrib.auth.forms import UserCreationForm\n\nfrom arquitectura.models import *\n\nclass FormControl:\n\n\tdef __init__(self, *args, **kwargs):\n\t\tsuper().__init__(*args, **kwargs)\n\t\tfor field in iter(self.fields):\n\t\t\tclase = 'form-control'\n\t\t\tif \"fecha\" in field:\n\t\t\t\tclase += ' datepicker-autoclose'\n\t\t\tself.fields[field].widget.attrs.update({\n\t \t\t\t'class': clase\n\t \t})\n\n\nclass SignUpForm(FormControl, UserCreationForm):\n\tnombre = forms.CharField(max_length=80, required=True)\n\tapellido = forms.CharField(max_length=80, required=True)\n\temail = forms.EmailField(required=True)\n\tcodigo = forms.CharField(max_length=5, required=True, label=\"Codigo de creacion\", help_text=\"Para poder registrarte necesitas un código de creación de usuario. El código se encuentra en el email de bienvenida que recibiste, si no contas con uno, solicitalo a la administración de tu consorcio\")\n\n\n\n\tdef save(self, commit=True):\n\t\tuser = super().save(commit=False)\n\t\tuser.email = self.cleaned_data[\"email\"]\n\t\tuser.first_name = self.cleaned_data[\"nombre\"]\n\t\tuser.last_name = self.cleaned_data[\"apellido\"]\n\t\tif commit:\n\t\t\tuser.save()\n\t\treturn user\n\n\n\nclass ExcelFileField(forms.FileField):\n def validate(self, value):\n file_extension = os.path.splitext(value.name)[1]\n if file_extension != '.xlsx':\n raise forms.ValidationError(\n ('Solo se admite archivos .xlsx'),\n code='invalid'\n )\n super().validate(value)","repo_name":"ramosagustin2103/adminmut_beta","sub_path":"admincu/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1635,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"22353569801","text":"import sys\nimport os\n\ndef calcLuhn(cardNo: str, isCurrentCharEven: bool = False):\n \"\"\"\n cardNo:\n cardNo for checking if isCurrentCharEven = False\n cardNoWithoutLuhn for calculation Luhn number if isCurrentCharEven = True\n isCurrentCharEven:\n False for checking\n True for calculation Luhn number\n \"\"\"\n luhnNumber = 0\n for currentChar in cardNo[::-1]: # Pass from right to left, so reverse cardNo\n currenDigit = ord(currentChar) - ord('0')\n if isCurrentCharEven:\n currenDigit = currenDigit * 2\n luhnNumber = luhnNumber + (currenDigit // 10)\n luhnNumber = luhnNumber + (currenDigit % 10)\n isCurrentCharEven = not isCurrentCharEven\n \n luhnNumber = luhnNumber % 10\n if luhnNumber: \n luhnNumber = 10 - luhnNumber # Calculate Luhn number for generateLuhn(cardNoWithoutLuhn)\n # If initial isCurrentCharEven == False (called for checking)\n # and luhnNumber == 0 then cardNo[-1] is correct Luhn number\n # else cardNo[-1] is NOT correct Luhn number\n # else luhnNumber is calculated Luhn number\n return luhnNumber \ndef checkLuhn(cardNo: str):\n return False if calcLuhn(cardNo) else True\ndef generateLuhn(cardNoWithoutLuhn: str):\n return cardNoWithoutLuhn + chr(calcLuhn(cardNoWithoutLuhn, True) + ord('0'))\n\nif __name__ == \"__main__\":\n # print(generateLuhn(\"444555oooooo777\".replace(\"o\",\"0\")))\n if len(sys.argv) == 2:\n print(generateLuhn(sys.argv[1].replace(\"o\",\"0\")))\n else:\n print(\"Usage: %s \" % os.path.split(sys.argv[0])[1])\n","repo_name":"py552/n0luhn","sub_path":"n0luhn.py","file_name":"n0luhn.py","file_ext":"py","file_size_in_byte":1631,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"11132264396","text":"import time\n\nimport osbrain\nfrom osbrain import run_agent\nfrom osbrain import run_nameserver\n\n\ndef log_message(agent, message):\n agent.log_info('Received: %s' % message)\n\n\nif __name__ == '__main__':\n osbrain.config['TRANSPORT'] = 'inproc'\n\n ns = run_nameserver()\n alice = run_agent('Alice', transport='tcp')\n bob = run_agent('Bob')\n\n addr = alice.bind('PUSH', alias='main')\n bob.connect(addr, handler=log_message)\n\n # What about performance?\n for _ in range(3):\n time.sleep(1)\n alice.send('main', 'Hello, Bob!')\n\n ns.shutdown()","repo_name":"muratcanakcay/Agent-Systems-and-Software-Applications","sub_path":"lab6/8.py","file_name":"8.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"8923505390","text":"from django.shortcuts import render, redirect\nimport folium\nfrom geocoder import location\nfrom .forms import SearchForm\nfrom find_buddy.map.models import Search\nfrom ..common.helpers import def_my_map\nfrom django.contrib.auth.decorators import login_required\n\n\n@login_required(login_url='profile login')\ndef show_map(request):\n nav_bar = True\n if request.method == 'POST':\n form = SearchForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect('map')\n\n else:\n form = SearchForm()\n address = Search.objects.all().last()\n loc = location(str(address))\n my_lat = loc.lat\n my_lng = loc.lng\n\n if not request.user.pk:\n nav_bar = False\n return redirect('page 404')\n\n if my_lat is None or my_lng is None:\n address.delete()\n nav_bar = False\n return redirect('page 404')\n # Create MAP Object\n m = def_my_map()\n folium.Marker([my_lat, my_lng], tooltip='You have a friend near by',\n draggable=True, zoom=True).add_to(m)\n # m = m._repr_html_() # we need to create a html representation of the map object\n m.fit_bounds(m.get_bounds(), padding=(30, 30))\n m = m._repr_html_()\n\n context = {\n 'map': m,\n 'form': form,\n 'nav_bar': nav_bar,\n }\n return render(request, 'home-map.html', context)\n","repo_name":"LiliaVasileva/FindWoofBuddy","sub_path":"find_buddy/map/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"30643851125","text":"#find the HCF of the smallest integer out of the denominator or numerator. here, it is the numerator \nclass Rational:\n def __init__(self, r1, r2):\n self.r1 = r1\n self.r2 = r2\n \n def reduced_form(self, numerator, denominator):\n self.numerator = numerator\n self.denominator= denominator\n g =[]\n h =[]\n f = []\n v = []\n if self.denominator > self.numerator:\n for i in range(1, self.numerator+1):\n if self.numerator % i == 0:\n v.append(i)\n print(v)\n for i in v:\n if self.denominator % i == 0:\n f.append(i)\n div_no =max(f)\n reduced_numerator = self.numerator/ div_no\n reduced_denominator = self.denominator / div_no\n print(f\"{reduced_numerator} / {reduced_denominator}\")\n\n\n elif numerator > self.denominator:\n for i in range(1, self.denominator+1):\n if self.denominator % i == 0:\n h.append(i)\n print(h)\n for i in h:\n if self.numerator % i == 0:\n g.append(i)\n div_no2 = max(g)\n reduced_numerator = self.numerator/ div_no2\n reduced_denominator = self.denominator / div_no2\n print(f\"{reduced_numerator} / {reduced_denominator}\")\n\n def add_rational(self, num1, num2, den1, den2):\n red1 = self.reduced_form(num1, den1)\n red2= self.reduced_form(num2, den2)\n x = (den1 * den2) / (den1) * (num1)\n y = (den1 * den2) / (den2) * (num2)\n z = (x + y)\n h = (den1 * den2)\n answer = self.reduced_form(z, h)\n # print(answer)\n \n def subtract_rational(self, num1, num2, den1, den2):\n red1 = self.reduced_form(num1, den1)\n red2= self.reduced_form(num2, den2)\n x = (den1 * den2) / (den1) * (num1)\n y = (den1 * den2) / (den2) * (num2)\n z = (x - y)\n h = (den1 * den2)\n answer = self.reduced_form(z, h)\n\n def division_rational(self, num1, num2, den1, den2):\n red1 = self.reduced_form(num1, den1)\n red2= self.reduced_form(num2, den2)\n x = (num1 * den2) \n y = (num2 * den1)\n h = self.reduced_form(x, y)\n\n def multiply_rational(self, num1, num2, den1, den2):\n # red1 = self.reduced_form(num1, den1)\n # red2= self.reduced_form(num2, den2)\n red3 = (num1 * num2) \n red4 = (den1 * den2)\n h = self.reduced_form(red3, red4)\n \n\n# rational = Rational((9/12), (2/4))\n# rational.reduced_form(444, 33)\n# rational.add_rational(4,3,2,6)\n# rational.subtract_rational(4,3,2,6)\n# rational.division_rational(4,3,2,6)\n# rational.multiply_rational(10,3,2,6)\n\n\ndef sect():\n import random\n d = [\"faith\", \"tiger\", \"Lion\"]\n # for i in range(5):\n x = random.choice(d)\n k = len(x)\n v = \"_\"\n r = v*k \n print(r)\n print(x)\n \n\n\n alphabet = x\n v = \"\"\n while True:\n secret_message = input('guess the word ')\n secret_message = secret_message.lower()\n # while secret_message != x:\n # for i in range(5):\n for c in secret_message:\n if c in x:\n c = (x[secret_message.index(c)])\n # print (x[secret_message.index(c)])\n v = v + c\n \n continue\n \n if c not in x:\n c = \"_\"\n v = v + c\n print(v)\n \n \n if v == x:\n print(\"you win\")\n else:\n print(\"try again\")\n\n \n \n\nsect()\n","repo_name":"adebusola-prog/ATS","sub_path":"week10/rational_numbers.py","file_name":"rational_numbers.py","file_ext":"py","file_size_in_byte":3656,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"5296139837","text":"#Creating a csv file and writing into it.\n\nfrom pathlib import Path\nimport csv\n\ndirectory = Path(r'C:\\Users\\KataniMed\\MyScripts')\nmy_file = directory / 'Patients info.txt'\nmy_file.touch()\n\nwith open(r'C:\\Users\\KataniMed\\MyScripts\\Patients info.txt', mode='w') as file:\n filenames = ['Date', 'OP Number', 'Gender','Age', 'Name', 'Resident', 'Contacts']\n write_file = csv.writer(file, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n \n write_file.writerow(['13/06/1999', '9999', 'Male', '24', 'Juggernaut', 'Katani', '0702538306'])","repo_name":"itsbonface/Project001","sub_path":"MyScripts/Pyprojects/Project001/Greentage0011.py","file_name":"Greentage0011.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"43228053112","text":"import importlib\nimport sys\n\n\ndef run_day(day):\n try:\n module = importlib.import_module(f\"day{day:02d}.solution\")\n except ImportError:\n return\n\n with open(f\"day{day:02d}/input.txt\") as fh:\n lines = fh.readlines()\n\n results = {}\n\n for part in (\"part1\", \"part2\"):\n if hasattr(module, part):\n results[part] = getattr(module, part)(lines)\n\n if results:\n print(f\"Day {day:02d}\")\n for part, result in results.items():\n print(f\" {part}: {result}\")\n print()\n\n\ndef run_all():\n for day in range(2, 7):\n run_day(day)\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) > 1:\n day = int(sys.argv[1])\n run_day(day)\n else:\n run_all()\n","repo_name":"sneeu/advent-of-code-2020","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"11896636049","text":"from pathlib import Path\nimport logging\nimport numpy as np\nimport pandas as pd\n\nfrom pytest import approx, mark\n\nfrom lenskit.algorithms.user_knn import UserUser\nfrom lenskit.algorithms.item_knn import ItemItem\nfrom lenskit.algorithms.basic import PopScore\nfrom lenskit.algorithms.ranking import PlackettLuce\nfrom lenskit.algorithms import Recommender\nfrom lenskit.util.test import ml_test, demo_recs\nfrom lenskit.metrics.topn import _dcg, precision, recall\nfrom lenskit import topn, batch, crossfold as xf\n\n_log = logging.getLogger(__name__)\n\n\ndef test_split_keys():\n rla = topn.RecListAnalysis()\n recs, truth = topn._df_keys(['algorithm', 'user', 'item', 'rank', 'score'],\n ['user', 'item', 'rating'])\n assert truth == ['user']\n assert recs == ['algorithm', 'user']\n\n\ndef test_split_keys_gcol():\n recs, truth = topn._df_keys(['algorithm', 'user', 'item', 'rank', 'score', 'fishtank'],\n ['user', 'item', 'rating'],\n ['algorithm', 'fishtank', 'user'])\n assert truth == ['user']\n assert recs == ['algorithm', 'fishtank', 'user']\n\n\ndef test_run_one():\n rla = topn.RecListAnalysis()\n rla.add_metric(topn.precision)\n rla.add_metric(topn.recall)\n\n recs = pd.DataFrame({'user': 1, 'item': [2]})\n recs.name = 'recs'\n truth = pd.DataFrame({'user': 1, 'item': [1, 2, 3], 'rating': [3.0, 5.0, 4.0]})\n truth.name = 'truth'\n\n print(recs)\n print(truth)\n\n res = rla.compute(recs, truth)\n print(res)\n\n assert res.index.name == 'user'\n assert res.index.is_unique\n\n assert len(res) == 1\n assert all(res.index == 1)\n assert all(res.precision == 1.0)\n assert res.recall.values == approx(1/3)\n\n\ndef test_run_two():\n rla = topn.RecListAnalysis()\n rla.add_metric(topn.precision)\n rla.add_metric(topn.recall)\n rla.add_metric(topn.ndcg)\n\n recs = pd.DataFrame({\n 'data': 'a',\n 'user': ['a', 'a', 'a', 'b', 'b'],\n 'item': [2, 3, 1, 4, 5],\n 'rank': [1, 2, 3, 1, 2]\n })\n truth = pd.DataFrame({\n 'user': ['a', 'a', 'a', 'b', 'b', 'b'],\n 'item': [1, 2, 3, 1, 5, 6],\n 'rating': [3.0, 5.0, 4.0, 3.0, 5.0, 4.0]\n })\n\n def prog(inner):\n assert len(inner) == 2\n return inner\n\n res = rla.compute(recs, truth)\n print(res)\n\n assert res.columns.nlevels == 1\n assert len(res) == 2\n assert res.index.nlevels == 2\n assert res.index.names == ['data', 'user']\n assert all(res.index.levels[0] == 'a')\n assert all(res.index.levels[1] == ['a', 'b'])\n assert all(res.reset_index().user == ['a', 'b'])\n partial_ndcg = _dcg([0.0, 5.0]) / _dcg([5, 4, 3])\n assert res.ndcg.values == approx([1.0, partial_ndcg])\n assert res.precision.values == approx([1.0, 1/2])\n assert res.recall.values == approx([1.0, 1/3])\n\n\ndef test_inner_format():\n rla = topn.RecListAnalysis()\n\n recs = pd.DataFrame({\n 'data': 'a',\n 'user': ['a', 'a', 'a', 'b', 'b'],\n 'item': [2, 3, 1, 4, 5],\n 'rank': [1, 2, 3, 1, 2]\n })\n truth = pd.DataFrame({\n 'user': ['a', 'a', 'a', 'b', 'b', 'b'],\n 'item': [1, 2, 3, 1, 5, 6],\n 'rating': [3.0, 5.0, 4.0, 3.0, 5.0, 4.0]\n })\n\n def inner(recs, truth, foo='a'):\n assert foo == 'b'\n assert set(recs.columns) == set(['LKRecID', 'LKTruthID', 'item', 'rank'])\n assert truth.index.name == 'item'\n assert truth.index.is_unique\n print(truth)\n assert all(truth.columns == ['rating'])\n return len(recs.join(truth, on='item', how='inner'))\n rla.add_metric(inner, name='bob', foo='b')\n\n res = rla.compute(recs, truth)\n print(res)\n\n assert len(res) == 2\n assert res.index.nlevels == 2\n assert res.index.names == ['data', 'user']\n assert all(res.index.levels[0] == 'a')\n assert all(res.index.levels[1] == ['a', 'b'])\n assert all(res.reset_index().user == ['a', 'b'])\n assert all(res['bob'] == [3, 1])\n\n\ndef test_spec_group_cols():\n rla = topn.RecListAnalysis(group_cols=['data', 'user'])\n rla.add_metric(topn.precision)\n rla.add_metric(topn.recall)\n rla.add_metric(topn.ndcg)\n\n recs = pd.DataFrame({\n 'data': 'a',\n 'user': ['a', 'a', 'a', 'b', 'b'],\n 'item': [2, 3, 1, 4, 5],\n 'rank': [1, 2, 3, 1, 2],\n 'wombat': np.random.randn(5)\n })\n truth = pd.DataFrame({\n 'user': ['a', 'a', 'a', 'b', 'b', 'b'],\n 'item': [1, 2, 3, 1, 5, 6],\n 'rating': [3.0, 5.0, 4.0, 3.0, 5.0, 4.0]\n })\n\n res = rla.compute(recs, truth)\n print(res)\n\n assert len(res) == 2\n assert res.index.nlevels == 2\n assert res.index.names == ['data', 'user']\n assert all(res.index.levels[0] == 'a')\n assert all(res.index.levels[1] == ['a', 'b'])\n assert all(res.reset_index().user == ['a', 'b'])\n partial_ndcg = _dcg([0.0, 5.0]) / _dcg([5, 4, 3])\n assert res.ndcg.values == approx([1.0, partial_ndcg])\n assert res.precision.values == approx([1.0, 1/2])\n assert res.recall.values == approx([1.0, 1/3])\n\n\ndef test_java_equiv():\n dir = Path(__file__).parent\n metrics = pd.read_csv(str(dir / 'topn-java-metrics.csv'))\n recs = pd.read_csv(str(dir / 'topn-java-recs.csv'))\n truth = pd.read_csv(str(dir / 'topn-java-truth.csv'))\n\n rla = topn.RecListAnalysis()\n rla.add_metric(topn.ndcg)\n res = rla.compute(recs, truth)\n\n umm = pd.merge(metrics, res.reset_index())\n umm['err'] = umm['ndcg'] - umm['Java.nDCG']\n _log.info('merged: \\n%s', umm)\n assert umm['err'].values == approx(0, abs=1.0e-6)\n\n\n@mark.slow\ndef test_fill_users():\n rla = topn.RecListAnalysis()\n rla.add_metric(topn.precision)\n rla.add_metric(topn.recall)\n\n algo = UserUser(20, min_nbrs=10)\n algo = Recommender.adapt(algo)\n\n splits = xf.sample_users(ml_test.ratings, 1, 50, xf.SampleN(5))\n train, test = next(splits)\n algo.fit(train)\n\n rec_users = test['user'].sample(50).unique()\n assert len(rec_users) < 50\n recs = batch.recommend(algo, rec_users, 25)\n\n scores = rla.compute(recs, test, include_missing=True)\n assert len(scores) == test['user'].nunique()\n assert scores['recall'].notna().sum() == len(rec_users)\n assert all(scores['ntruth'] == 5)\n\n mscores = rla.compute(recs, test)\n assert len(mscores) < len(scores)\n\n recall = scores.loc[scores['recall'].notna(), 'recall'].copy()\n recall, mrecall = recall.align(mscores['recall'])\n assert all(recall == mrecall)\n\n\n@mark.slow\ndef test_adv_fill_users():\n rla = topn.RecListAnalysis()\n rla.add_metric(topn.precision)\n rla.add_metric(topn.recall)\n\n a_uu = UserUser(30, min_nbrs=10)\n a_uu = Recommender.adapt(a_uu)\n a_ii = ItemItem(20, min_nbrs=4)\n a_ii = Recommender.adapt(a_ii)\n\n splits = xf.sample_users(ml_test.ratings, 2, 50, xf.SampleN(5))\n all_recs = {}\n all_test = {}\n for i, (train, test) in enumerate(splits):\n a_uu.fit(train)\n rec_users = test['user'].sample(50).unique()\n all_recs[(i+1, 'UU')] = batch.recommend(a_uu, rec_users, 25)\n\n a_ii.fit(train)\n rec_users = test['user'].sample(50).unique()\n all_recs[(i+1, 'II')] = batch.recommend(a_ii, rec_users, 25)\n all_test[i+1] = test\n\n recs = pd.concat(all_recs, names=['part', 'algo'])\n recs.reset_index(['part', 'algo'], inplace=True)\n recs.reset_index(drop=True, inplace=True)\n\n test = pd.concat(all_test, names=['part'])\n test.reset_index(['part'], inplace=True)\n test.reset_index(drop=True, inplace=True)\n\n scores = rla.compute(recs, test, include_missing=True)\n inames = scores.index.names\n scores.sort_index(inplace=True)\n assert len(scores) == 50 * 4\n assert all(scores['ntruth'] == 5)\n assert scores['recall'].isna().sum() > 0\n _log.info('scores:\\n%s', scores)\n\n ucounts = scores.reset_index().groupby('algo')['user'].agg(['count', 'nunique'])\n assert all(ucounts['count'] == 100)\n assert all(ucounts['nunique'] == 100)\n\n mscores = rla.compute(recs, test)\n mscores = mscores.reset_index().set_index(inames)\n mscores.sort_index(inplace=True)\n assert len(mscores) < len(scores)\n _log.info('mscores:\\n%s', mscores)\n\n recall = scores.loc[scores['recall'].notna(), 'recall'].copy()\n recall, mrecall = recall.align(mscores['recall'])\n assert all(recall == mrecall)\n\n\n@mark.parametrize('drop_rating', [False, True])\ndef test_pr_bulk_match(demo_recs, drop_rating):\n \"bulk and normal match\"\n train, test, recs = demo_recs\n if drop_rating:\n test = test[['user', 'item']]\n\n rla = topn.RecListAnalysis()\n rla.add_metric(precision)\n rla.add_metric(recall)\n # metric without the bulk capabilities\n rla.add_metric(lambda *a: precision(*a), name='ind_p')\n rla.add_metric(lambda *a: recall(*a), name='ind_r')\n res = rla.compute(recs, test)\n\n print(res)\n _log.info('precision mismatches:\\n%s',\n res[res.precision != res.ind_p])\n _log.info('recall mismatches:\\n%s',\n res[res.recall != res.ind_r])\n\n assert res.precision.values == approx(res.ind_p.values)\n assert res.recall.values == approx(res.ind_r.values)\n","repo_name":"lenskit/lkpy","sub_path":"tests/test_topn_analysis.py","file_name":"test_topn_analysis.py","file_ext":"py","file_size_in_byte":9148,"program_lang":"python","lang":"en","doc_type":"code","stars":248,"dataset":"github-code","pt":"31"}
+{"seq_id":"6170599738","text":"import os\nimport pandas as pd\nimport numpy as np\nfrom pyod.models.iforest import IForest\n\nfrom six import StringIO\nfrom sklearn import tree\nimport pydotplus\n\nimport matplotlib.pyplot as plt\nfrom sklearn.decomposition import PCA\nfrom sklearn.preprocessing import StandardScaler\nfrom mpl_toolkits.mplot3d import Axes3D\n\ndef do_iforest(x, n_estimators=100, max_samples=512):\n clf = IForest(behaviour=\"new\", n_estimators=n_estimators, max_samples=max_samples, random_state=None)\n y_pred = clf.fit_predict(x)\n scores = clf.decision_function(x)\n index = np.where(y_pred == 1)[0]\n return clf, scores, index\n\n\ndef iforest_vis(x, outlier_index, score):\n pca = PCA(n_components=3) # Reduce to k=3 dimensions\n x = StandardScaler().fit_transform(x)\n x = pca.fit_transform(x)\n fig = plt.figure()\n ax = fig.add_subplot(211, projection='3d')\n # Plot the compressed data points\n ax.scatter(x[:, 0], x[:, 1], zs=x[:, 2], s=20, lw=1, c=score, cmap=\"summer\")\n\n ax2 = fig.add_subplot(212, projection='3d')\n ax2.scatter(x[:, 0], x[:, 1], zs=x[:, 2], s=20, lw=1, label=\"inliers\", c=\"green\")\n ax2.scatter(x[outlier_index, 0], x[outlier_index, 1], x[outlier_index, 2],\n lw=2, s=60, marker=\"x\", c=\"red\", label=\"outliers\")\n\n plt.show()\n return\n\n# 这里可以调节输出的树的格式,jpg格式必须先输出dot格式\ndef draw_tree(iForest, tree_list, out_dot=True, out_pdf=True, out_jpg=True):\n for tree_id in tree_list:\n model = iForest.estimators_[tree_id]\n name = 'Tree-' + str(tree_id)\n dot_data = StringIO()\n tree.export_graphviz(model, node_ids=True, filled=True, out_file=dot_data)\n graph = pydotplus.graph_from_dot_data(dot_data.getvalue())\n\n if out_dot:\n graph.write(name + \".dot\")\n if out_pdf:\n graph.write_pdf(name + \".pdf\")\n if out_jpg:\n transfer = \"dot -Tjpg \" + name + \".dot\" + \" -o \" + name + \".jpg\"\n os.system(transfer)\n\n\ndef iforest_depth_table(iforest, x):\n n_tree = len(iforest.estimators_samples_)\n n_sample = x.shape[0]\n print(\"Tree Num: %d\" % n_tree)\n\n depth_table = np.ones([n_sample, n_tree], dtype=int) * -1\n for i in range(n_tree):\n estimator_tree = iforest.estimators_[i].tree_\n n_node = estimator_tree.node_count\n tree_sample_id = iforest.estimators_samples_[i]\n\n # find data sample id for each node in tree i\n # assign depth for each node in tree i\n print(tree_sample_id)\n sample_map = {0: tree_sample_id}\n node_depth = np.zeros(n_node, dtype=int)\n leaf_node_list = []\n for j in range(n_node):\n # if this node is a leaf node then continue\n if estimator_tree.children_left[j] == -1:\n leaf_node_list.append(j)\n continue\n this_node_sample_id = sample_map[j]\n # get the condition of this node (feature & threshold)\n feature, threshold = estimator_tree.feature[j], estimator_tree.threshold[j]\n left_child, right_child = estimator_tree.children_left[j], estimator_tree.children_right[j]\n\n node_depth[left_child] = node_depth[j] + 1\n node_depth[right_child] = node_depth[j] + 1\n sample_map[left_child] = this_node_sample_id[np.where(x[this_node_sample_id, feature] <= threshold)[0]]\n sample_map[right_child] = this_node_sample_id[np.where(x[this_node_sample_id, feature] > threshold)[0]]\n\n\n depth_table[tree_sample_id][i] = 0\n for id in leaf_node_list:\n sample_list = sample_map[id]\n this_depth = node_depth[id]\n depth_table[sample_list, i] = this_depth\n\n columns = [\"Tree-\" + str(i) for i in range(n_tree)]\n depth_df = pd.DataFrame(depth_table, dtype=int, index=np.arange(n_sample), columns=columns)\n return depth_df\n\n\nif __name__ == '__main__':\n file_path = \"data/cardio.csv\"\n df = pd.read_csv(file_path)\n x = df.values[:, :-1]\n y = df.values[:, -1]\n iforest, if_scores, if_outlier_index = do_iforest(x, n_estimators=100)\n\n # iforest_vis(x, if_outlier_index, if_scores)\n depth = iforest_depth_table(iforest, x)\n print(depth)\n import pandas as pd\n\n depth.to_csv('data/d_t.csv')\n\n n_tree = len(iforest.estimators_samples_)\n draw_tree(iforest, np.arange(10))","repo_name":"bettyzry/EFMOL","sub_path":"iForestVis.py","file_name":"iForestVis.py","file_ext":"py","file_size_in_byte":4345,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"40995942306","text":"import numpy as np\nimport vtk\nimport vtk.util.numpy_support as npv\n\n\n# ========================================================= #\n# === construct vtk unstructuredgrid === #\n# ========================================================= #\n\nclass construct__uGrid:\n\n \n # ========================================================= #\n # === initial settings === #\n # ========================================================= #\n def __init__( self, nodes=None, elems =None, vtkFile =\"out.vtu\", DataFormat=\"binary\", \\\n elementType=None, cellData=None, pointData=None, cellDataName=None, pointDataName=None ):\n\n # ------------------------------------------------- #\n # --- [1] ID_TYPE Definition ( type for IDs ) --- #\n # ------------------------------------------------- #\n if vtk.VTK_ID_TYPE == 12:\n self.ID_TYPE = np.int64\n else:\n self.ID_TYPE = np.int32\n\n # ------------------------------------------------- #\n # --- [2] input variables and its size --- #\n # ------------------------------------------------- #\n self.vtkFile = vtkFile\n self.DataFormat = DataFormat\n self.elementType = elementType\n self.nodes = np.copy( nodes )\n self.elems = np.copy( elems )\n self.nElem = self.elems.shape[0]\n self.nVert = self.elems.shape[1]\n if ( self.elems.dtype != self.ID_TYPE ):\n self.elems.astype( self.ID_TYPE )\n if ( self.elems.flags['C_CONTIGUOUS'] != True ):\n self.elems = np.ascontiguousarray( self.elems )\n\n # ------------------------------------------------- #\n # --- [3] cell & point Data --- #\n # ------------------------------------------------- #\n\n if ( cellData is not None ):\n if ( cellData.ndim == 1 ):\n cellData = np.reshape( cellData, (-1,1) )\n elif ( cellData.ndim > 2 ):\n sys.exit( \"[construct__uGrid] cellData shape == {0} \".format( cellData.shape ) )\n self.cellData = np.copy( cellData )\n if ( cellDataName is None ):\n self.cellDataName = [ \"eData{0:02}\".format(ik+1) for ik in range( cellData.shape[1] ) ]\n else:\n self.cellDataName = cellDataName\n else:\n self.cellData = None\n self.cellDataName = None\n\n if ( pointData is not None ):\n if ( pointData.ndim == 1 ):\n pointData = np.reshape( pointData, (-1,1) )\n elif ( pointData.ndim > 2 ):\n sys.exit( \"[construct__uGrid] pointData shape == {0} \".format( pointData.shape ) )\n self.pointData = np.copy( pointData )\n if ( pointDataName is None ):\n self.pointDataName = [ \"pData{0:02}\".format(ik+1) for ik in range( pointData.shape[1] ) ]\n else:\n self.pointData = None\n self.pointDataName = None\n\n \n # ------------------------------------------------- #\n # --- [3] make unstructuredGridData --- #\n # ------------------------------------------------- #\n self.make__uGrid()\n self.save__uGrid()\n\n\n # ========================================================= #\n # === store elems & nodes in a ugrid format === #\n # ========================================================= #\n def make__uGrid( self ):\n \n # ------------------------------------------------- #\n # --- [1] element IDs & offset = define cells --- #\n # ------------------------------------------------- #\n # -- [1-1] offset & elemIDs -- #\n nVertArray = np.sum( np.ones_like( self.elems ), axis=1 )\n offset = np.cumsum( np.insert( nVertArray, 0, 0.0 ) )\n offset = npv.numpy_to_vtkIdTypeArray( ( offset[:-1] ).astype( self.ID_TYPE ) )\n \n # -- [1-2] cell type -- #\n if ( self.elementType is not None ):\n cellType = np.full( ( self.nElem,), self.elementType )\n if ( self.nVert == 4 ):\n cellType = np.full( ( self.nElem,), vtk.VTK_TETRA )\n if ( self.nVert == 8 ):\n cellType = np.full( ( self.nElem,), vtk.VTK_HEXAHEDRON )\n cellType = cellType.astype( np.uint8 )\n cellType = npv.numpy_to_vtk( cellType )\n\n # -- [1-3] cell array -- #\n elemIDs = np.concatenate( [ np.reshape( nVertArray, ( self.nElem,1) ), \\\n self.elems ], axis=1 )\n elemIDs = npv.numpy_to_vtkIdTypeArray( np.ravel( elemIDs ) )\n cellArray = vtk.vtkCellArray()\n cellArray.SetCells( self.nElem, elemIDs )\n # -- elemID Data Structure -- #\n # [ [ N, e1, e2, e3, ...., eN ], [ N, e1, e2, e3, ...., eN ], .... ]\n # -- \n \n # ------------------------------------------------- #\n # --- [2] node definition --- #\n # ------------------------------------------------- #\n vtkPoints = vtk.vtkPoints()\n vtkPoints.SetData( npv.numpy_to_vtk( self.nodes ) )\n\n # ------------------------------------------------- #\n # --- [3] Define unstructured Grid --- #\n # ------------------------------------------------- #\n self.ugrid = vtk.vtkUnstructuredGrid()\n self.ugrid.SetPoints( vtkPoints )\n self.ugrid.SetCells( cellType, offset, cellArray )\n\n # ------------------------------------------------- #\n # --- [4] cellData & pointData --- #\n # ------------------------------------------------- #\n # -- [4-1] cellData -- #\n if ( self.cellData is not None ):\n self.cellDataDict = { key: npv.numpy_to_vtk( self.cellData[:,ik], deep=True ) \\\n for ik,key in enumerate( self.cellDataName ) }\n for key in self.cellDataName:\n self.cellDataDict[key].SetName( key )\n self.ugrid.GetCellData().AddArray( self.cellDataDict[key] )\n\n # -- [4-2] pointData -- #\n if ( self.pointData is not None ):\n self.pointDataDict = { key: npv.numpy_to_vtk( self.pointData[:,ik], deep=True ) \\\n for ik,key in enumerate( self.pointDataName ) }\n for key in self.pointDataName:\n self.pointDataDict[key].SetName( key )\n self.ugrid.GetPointData().AddArray( self.pointDataDict[key] )\n \n\n \n # ========================================================= #\n # === save as a vtk Format File === #\n # ========================================================= #\n def save__uGrid( self, DataFormat=None, vtkFile=None ):\n\n if ( DataFormat is not None ):\n self.DataFormat = DataFormat\n if ( vtkFile is not None ):\n self.vtkFile = vtkFile\n \n self.writer = vtk.vtkXMLUnstructuredGridWriter()\n self.writer.SetDataModeToBinary()\n if ( self.DataFormat.lower() == \"ascii\" ):\n self.writer.SetDataModeToAscii()\n if ( self.DataFormat.lower() == \"binary\" ):\n self.writer.SetDataModeToBinary()\n self.writer.SetFileName( self.vtkFile )\n self.writer.SetInputData( self.ugrid )\n self.writer.Write()\n print( \"[save__uGrid] outFile :: {0} \".format( self.vtkFile ) )\n\n\n\n\n# ========================================================= #\n# === 実行部 === #\n# ========================================================= #\n\nif ( __name__==\"__main__\" ):\n\n import nkUtilities.equiSpaceGrid as esg\n x1MinMaxNum = [ 0.0, 1.0, 2 ]\n x2MinMaxNum = [ 0.0, 2.0, 2 ]\n x3MinMaxNum = [ 0.0, 3.0, 3 ]\n nodes = esg.equiSpaceGrid( x1MinMaxNum=x1MinMaxNum, x2MinMaxNum=x2MinMaxNum, \\\n x3MinMaxNum=x3MinMaxNum, returnType = \"point\", \\\n DataOrder =\"ijk\" )\n \n elems = np.array( [ [ 0, 1, 3, 2, 4, 5, 7, 6 ], \\\n [ 4, 5, 7, 6, 8, 9, 11, 10 ] ] )\n cellData = np.array( [ [ 1.0, 2.0, 3.0 ], [0.0, 1.0, 2.0] ] )\n pointData1 = np.sqrt( nodes[:,0]**2 + nodes[:,1]**2, nodes[:,2]**2 )\n pointData2 = np.exp( - 0.5 * nodes[:,0]**2 + nodes[:,1]**2, nodes[:,2]**2 )\n pointData = np.concatenate( ( pointData1[:,None], pointData2[:,None] ), axis=1 )\n \n construct__uGrid( nodes=nodes, elems=elems, cellData=cellData, pointData=pointData, vtkFile=\"out.vtu\" )\n","repo_name":"wfw-pgr/nkVTKRoutines","sub_path":"construct__uGrid.py","file_name":"construct__uGrid.py","file_ext":"py","file_size_in_byte":8871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"33642891859","text":"from enum import Enum\nimport numpy as np\n\nclass GrowthlaneRoi(object):\n \"\"\" Represents the growth-lane present inside a Mother-machine image. \"\"\"\n\n def __init__(self, roi=None, id=None, parent_gl_region_id=None):\n self.roi = roi\n self.id = id\n self.parent_gl_region_id = parent_gl_region_id\n self.exit_location: GrowthlaneExitLocation = None\n self.normalization_range = None\n\n def get_oriented_roi_image(self, image):\n roi_image = self.roi.get_from_image(image)\n if self.exit_location is None:\n self.exit_location = self.determine_location_of_growthlane_exit(roi_image[0, ...], search_area=50)\n\n if self.normalization_range:\n roi_image[0, ...] = self._normalize_image_with_min_and_max_values(roi_image[0, ...], self.normalization_range[0], self.normalization_range[1])\n\n if self.exit_location is GrowthlaneExitLocation.AT_TOP:\n return roi_image\n elif self.exit_location is GrowthlaneExitLocation.AT_LEFT:\n return np.rot90(roi_image,-1, axes=(1, 2))\n elif self.exit_location is GrowthlaneExitLocation.AT_BOTTOM:\n return np.rot90(roi_image, 2, axes=(1, 2))\n elif self.exit_location is GrowthlaneExitLocation.AT_RIGHT:\n return np.rot90(roi_image, 1, axes=(1, 2))\n else:\n raise ValueError(\"Growthlane orientation is not set.\")\n\n def determine_location_of_growthlane_exit(self, growthlane_roi_image, search_area):\n \"\"\"\n This function determines the location of the growthlane by comparing the value sum of values\n at the start of the *extended* GL to those at the end.\n :param growthlane_roi_image: the image of from the extended GL ROI.\n :param search_area: the value by which the GL was extended in *both* directions.\n :return:\n \"\"\"\n height, width = growthlane_roi_image.shape\n\n if width > height:\n sum_at_left = np.sum(growthlane_roi_image[:, 0:search_area].flatten(), 0)\n sum_at_right = np.sum(growthlane_roi_image[:, -search_area:].flatten(), 0)\n if sum_at_left > sum_at_right:\n return GrowthlaneExitLocation.AT_LEFT\n elif sum_at_right > sum_at_left:\n return GrowthlaneExitLocation.AT_RIGHT\n else:\n raise ValueError(\"Could not determine location of growthlane exit.\")\n elif height > width:\n sum_at_top = np.sum(growthlane_roi_image[0:search_area, :].flatten(), 0)\n sum_at_bottom = np.sum(growthlane_roi_image[-search_area:, :].flatten(), 0)\n if sum_at_top > sum_at_bottom:\n return GrowthlaneExitLocation.AT_TOP\n elif sum_at_bottom > sum_at_top:\n return GrowthlaneExitLocation.AT_BOTTOM\n else:\n raise ValueError(\"Could not determine location of growthlane exit.\")\n else:\n raise ValueError(\"Could not determine location of growthlane exit.\")\n\n print(\"stop\")\n\n @property\n def length(self):\n \"\"\"\n Returns the length of the growthlane.\n \"\"\"\n if self.roi.width >= self.roi.height:\n return self.roi.width\n else:\n return self.roi.height\n\n @property\n def width(self):\n \"\"\"\n Returns the width of the channel ROI.\n Note that this is not identical with RotatedRoi.width (but it can be).\n \"\"\"\n if self.roi.height < self.roi.width:\n return self.roi.height\n else:\n return self.roi.width\n\n def _normalize_image_with_min_and_max_values(self, image, norm_range_minimum, norm_range_maximum):\n return (image - norm_range_minimum) / (norm_range_maximum - norm_range_minimum)\n\n\n\nclass GrowthlaneExitLocation(Enum):\n \"\"\"Enum for passing back the result from determining the location of the growthlane exit.\"\"\"\n AT_LEFT = 0\n AT_RIGHT = 1\n AT_TOP = 2\n AT_BOTTOM = 3\n","repo_name":"nimwegenLab/moma-preprocessing","sub_path":"mmpreprocesspy/mmpreprocesspy/GrowthlaneRoi.py","file_name":"GrowthlaneRoi.py","file_ext":"py","file_size_in_byte":3974,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"12206125761","text":"import torch\n\nclass Evaluate:\n def __init__(self):\n pass\n\n def accuracy(self, network, x_val, y_val, gpu):\n correct = 0\n total = 0\n for index, (inputs, labels) in enumerate(zip(x_val, y_val)):\n inputs = torch.tensor(inputs)\n labels = torch.tensor(labels)\n\n if gpu:\n network.cuda()\n inputs = inputs.cuda()\n labels = labels.cuda()\n\n outputs = network(inputs)\n for i, output in enumerate(outputs):\n correct += self.evalOneHot(output.tolist(), labels[i].tolist())\n total += 1\n print(f'Calculating accuracy: {index}/{len(x_val)}', end='\\r')\n\n return correct / total\n\n def evalOneHot(self, output, label):\n maxOutput = output.index(max(output))\n maxLabel = label.index(max(label))\n return maxOutput == maxLabel\n","repo_name":"felixxwu/Jazz-Chord-Generator","sub_path":"dataset/evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"35378202707","text":"from ..libs.requests_with_caching import get\nfrom ..safe_get import safe_get\n\ndef get_movies_from_tastedive(movie_title):\n baseurl = \"https://tastedive.com/api/similar\"\n params_diction = {\"limit\": 5, \"type\": \"movies\"}\n params_diction[\"q\"] = movie_title\n resp = get(baseurl, params = params_diction)\n return resp.json()\n\ndef extract_movie_titles(movies_data):\n return [ safe_get(movie, \"Name\") for movie in safe_get(movies_data, \"Similar.Results\") ]\n\ndef reduce(function, sequence, initial=None):\n it = iter(sequence)\n value = initial\n for element in it:\n value = function(value, element)\n return value\n\ndef get_related_titles(titles):\n movies_res = [ get_movies_from_tastedive(movie) for movie in titles]\n related_titles = reduce(lambda acc, li: acc + li,[extract_movie_titles(data) for data in movies_res], [])\n return list(set(related_titles))","repo_name":"santiagoclv/python-3","sub_path":"basics_3/week_3/final_assegment/movie_recomendation.py","file_name":"movie_recomendation.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"}
+{"seq_id":"11963773071","text":"#!/usr/bin/python\n# -*- coding:utf-8 -*-\n\n\nimport tensorflow as tf\nimport six\nfrom tools import visualize\n\n\nFLAGS = tf.app.flags.FLAGS\ntf.app.flags.DEFINE_integer('cls', 10, 'numbers of classifiers')\ntf.app.flags.DEFINE_integer('IMG_WIDTH', 299, 'image width')\ntf.app.flags.DEFINE_integer('IMG_HEIGHT', 299, 'image height')\ntf.app.flags.DEFINE_integer('IMG_CHANNEL', 3, 'image channel')\ntf.app.flags.DEFINE_integer('batch_size', 5, 'batch size')\ntf.app.flags.DEFINE_integer('epoches', 1, 'epoches')\ntf.app.flags.DEFINE_float('LEARNING_RATE', 0.0001, 'learning rate for momentum GD')\ntf.app.flags.DEFINE_float('MOMENTUM', 0.9, 'momentum rate for momentum GD')\ntf.app.flags.DEFINE_string('data_path', '/home/workspace/cc', 'path of dataset')\ntf.app.flags.DEFINE_string('LOG_DIR', 'Log--' + visualize.get_time(), 'tensorboard log dir')\n\n\ndef convolution(data, kernel, strides, padding='SAME', name=None):\n with tf.name_scope(name):\n conv = tf.nn.conv2d(input=data,\n filter=tf.Variable(tf.truncated_normal(shape=kernel, stddev=1e-2, dtype=tf.float32)),\n strides=[1, strides, strides, 1], padding=padding, name=name)\n return conv\n\n\ndef pooling(data, ksize, strides, padding='SAME', type='max', name=None):\n with tf.name_scope(name):\n if type == 'max':\n pool = tf.nn.max_pool(value=data, ksize=[1, ksize, ksize, 1],\n strides=[1, strides, strides, 1], padding=padding, name=name)\n else:\n pool = tf.nn.avg_pool(value=data, ksize=[1, ksize, ksize, 1],\n strides=[1, strides, strides, 1], padding=padding, name=name)\n return pool\n\n\ndef relu(data, name=None):\n with tf.name_scope(name):\n relu_res = tf.nn.relu(data, name=name)\n return relu_res\n\n\ndef fullconnection(data, weights, biases, name):\n with tf.name_scope(name):\n fc = tf.nn.xw_plus_b(data, weights, biases, name=name)\n return fc\n\n\ndef stem(data):\n with tf.name_scope('stem'):\n conv1 = convolution(data, kernel=[3, 3, FLAGS.IMG_CHANNEL, 32], strides=2, padding='VALID',\n name='stem_conv1')\n conv2 = convolution(conv1, kernel=[3, 3, 32, 32], strides=1, padding='VALID', name='stem_conv2')\n conv3 = convolution(conv2, kernel=[3, 3, 32, 64], strides=1, name='stem_conv3')\n\n # block1\n block1_max_pool = pooling(conv3, ksize=3, strides=2, padding='VALID', name='stem_block1_max_pool')\n block1_conv = convolution(conv3, kernel=[3, 3, 64, 96], strides=2, padding='VALID', name='stem_block1_conv')\n block1 = tf.concat(axis=3, values=[block1_max_pool, block1_conv])\n\n # block2_1\n block2_1_conv1 = convolution(block1, kernel=[1, 1, 160, 64], strides=1, name='block2_1_conv1')\n block2_1_conv2 = convolution(block2_1_conv1, kernel=[3, 3, 64, 96], strides=1, padding='VALID',\n name='block2_1_conv2')\n\n # block2_2\n block2_2_conv1 = convolution(block1, kernel=[1, 1, 160, 64], strides=1, name='block2_2_conv1')\n block2_2_conv2 = convolution(block2_2_conv1, kernel=[7, 1, 64, 64], strides=1, name='block2_2_conv2')\n block2_2_conv3 = convolution(block2_2_conv2, kernel=[1, 7, 64, 64], strides=1, name='block2_2_conv3')\n block2_2_conv4 = convolution(block2_2_conv3, kernel=[3, 3, 64, 96], strides=1, padding='VALID',\n name='block2_2_conv4')\n block2 = tf.concat(axis=3, values=[block2_1_conv2, block2_2_conv4])\n\n # block3\n block3_conv = convolution(block2, kernel=[3, 3, 192, 192], strides=2, padding='VALID', name='block3_conv')\n block3_pool = pooling(block2, ksize=3, strides=2, padding='VALID', name='block3_pool')\n block3 = tf.concat(axis=3, values=[block3_conv, block3_pool])\n\n return block3\n\n\ndef inception_resnet_a(data):\n with tf.name_scope('inception_resnet_a'):\n relu1 = relu(data, name='relu1')\n\n # patch1\n patch1_conv1 = convolution(data, kernel=[1, 1, 384, 32], strides=1, name='patch1_conv1')\n\n # patch2\n patch2_conv1 = convolution(data, kernel=[1, 1, 384, 32], strides=1, name='patch2_conv1')\n patch2_conv2 = convolution(patch2_conv1, kernel=[3, 3, 32, 32], strides=1, name='patch2_conv2')\n\n # patch3\n patch3_conv1 = convolution(data, kernel=[1, 1, 384, 32], strides=1, name='patch3_conv1')\n patch3_conv2 = convolution(patch3_conv1, kernel=[3, 3, 32, 48], strides=1, name='patch3_conv2')\n patch3_conv3 = convolution(patch3_conv2, kernel=[3, 3, 48, 64], strides=1, name='patch3_conv3')\n\n patch = tf.concat(axis=3, values=[patch1_conv1, patch2_conv2, patch3_conv3])\n patch_conv = convolution(patch, kernel=[1, 1, 128, 384], strides=1, name='patch_conv')\n\n relu1 += patch_conv\n return relu1\n\n\ndef reduction_a(data):\n with tf.name_scope('reduction_a'):\n patch1 = pooling(data, ksize=3, strides=2, padding='VALID', name='patch1')\n patch2 = convolution(data, kernel=[3, 3, 384, 384], strides=2, padding='VALID', name='patch2')\n patch3_conv1 = convolution(data, kernel=[1, 1, 384, 256], strides=1, name='patch3_conv1')\n patch3_conv2 = convolution(patch3_conv1, kernel=[3, 3, 256, 256], strides=1, name='patch3_conv2')\n patch3_conv3 = convolution(patch3_conv2, kernel=[3, 3, 256, 384], strides=2, padding='VALID',\n name='patch3_conv3')\n patch = tf.concat(axis=3, values=[patch1, patch2, patch3_conv3])\n return patch\n\n\ndef inception_resnet_b(data):\n with tf.name_scope('inception_resnet_b'):\n relu1 = relu(data, name='relu1')\n\n # patch1\n patch1_conv1 = convolution(data, kernel=[1, 1, 1152, 192], strides=1, name='patch1_conv1')\n\n # patch2\n patch2_conv1 = convolution(data, kernel=[1, 1, 1152, 128], strides=1, name='patch2_conv1')\n patch2_conv2 = convolution(patch2_conv1, kernel=[1, 7, 128, 160], strides=1, name='patch2_conv2')\n patch2_conv3 = convolution(patch2_conv2, kernel=[7, 1, 160, 192], strides=1, name='patch2_conv3')\n\n patch = tf.concat(axis=3, values=[patch1_conv1, patch2_conv3])\n patch = convolution(patch, kernel=[1, 1, 384, 1152], strides=1, name='patch_conv')\n\n relu1 += patch\n return relu1\n\n\ndef reduction_b(data):\n # patch1\n patch1 = pooling(data, ksize=3, strides=2, padding='VALID', name='patch1_max')\n\n # patch2\n patch2_conv1 = convolution(data, kernel=[1, 1, 1152, 256], strides=1, name='patch2_conv1')\n patch2_conv2 = convolution(patch2_conv1, kernel=[3, 3, 256, 384], strides=2, padding='VALID', name='patch2_conv2')\n\n # patch3\n patch3_conv1 = convolution(data, kernel=[1, 1, 1152, 256], strides=1, name='patch3_conv1')\n patch3_conv2 = convolution(patch3_conv1, kernel=[3, 3, 256, 288], strides=2, padding='VALID', name='patch3_conv2')\n\n # patch4\n patch4_conv1 = convolution(data, kernel=[1, 1, 1152, 256], strides=1, name='patch4_conv1')\n patch4_conv2 = convolution(patch4_conv1, kernel=[3, 3, 256, 288], strides=1, name='patch4_conv2')\n patch4_conv3 = convolution(patch4_conv2, kernel=[3, 3, 288, 320], strides=2, padding='VALID', name='patch4_conv3')\n\n patch = tf.concat(axis=3, values=[patch1, patch2_conv2, patch3_conv2, patch4_conv3])\n return patch\n\n\ndef inception_resnet_c(data):\n with tf.name_scope('inception_resnet_c'):\n relu1 = relu(data, name='relu1')\n\n # patch1\n patch1_conv1 = convolution(data, kernel=[1, 1, 2144, 192], strides=1, name='patch1_conv1')\n\n # patch2\n patch2_conv1 = convolution(data, kernel=[1, 1, 2144, 192], strides=1, name='patch2_conv1')\n patch2_conv2 = convolution(patch2_conv1, kernel=[1, 3, 192, 224], strides=1, name='patch2_conv2')\n patch2_conv3 = convolution(patch2_conv2, kernel=[3, 1, 224, 256], strides=1, name='patch2_conv3')\n\n patch = tf.concat(axis=3, values=[patch1_conv1, patch2_conv3])\n patch = convolution(patch, kernel=[1, 1, 448, 2144], strides=1, name='patch')\n\n relu1 += patch\n return relu1\n\n\ndef model(data):\n stem_unit = stem(data)\n inception_resnet_a_unit = stem_unit\n for _ in six.moves.range(5):\n inception_resnet_a_unit = inception_resnet_a(inception_resnet_a_unit)\n reduction_a_unit = reduction_a(inception_resnet_a_unit)\n inception_resnet_b_unit = reduction_a_unit\n for _ in six.moves.range(10):\n inception_resnet_b_unit = inception_resnet_b(inception_resnet_b_unit)\n reduction_b_unit = reduction_b(inception_resnet_b_unit)\n inceptio_resnet_c_unit = reduction_b_unit\n for _ in six.moves.range(5):\n inceptio_resnet_c_unit = inception_resnet_c(inceptio_resnet_c_unit)\n avg_pool_unit = pooling(inceptio_resnet_c_unit, ksize=8, strides=1, padding='VALID', type='avg', name='avg_pool')\n drop = tf.nn.dropout(avg_pool_unit, keep_prob=0.8)\n drop = tf.reshape(drop, shape=[-1, 2144])\n fc = fullconnection(drop,\n weights=tf.Variable(tf.truncated_normal(shape=[2144, FLAGS.cls], dtype=tf.float32)),\n biases=tf.Variable(tf.truncated_normal(shape=[FLAGS.cls], dtype=tf.float32)), name='full_conn')\n return fc\n\n\ndef train_act(features_train, labels_train, features_test, labels_test):\n sess = tf.InteractiveSession()\n x = tf.placeholder(dtype=tf.float32,\n shape=[None, FLAGS.IMG_WIDTH, FLAGS.IMG_HEIGHT, FLAGS.IMG_CHANNEL], name='features')\n y = tf.placeholder(dtype=tf.float32, shape=[None, FLAGS.cls], name='labels')\n pred = model(data=x)\n with tf.name_scope('loss'):\n loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))\n tf.summary.scalar('loss', loss)\n tf.summary.histogram('loss', loss)\n with tf.name_scope('train'):\n train = tf.train.MomentumOptimizer(learning_rate=FLAGS.LEARNING_RATE, momentum=FLAGS.MOMENTUM).minimize(loss)\n with tf.name_scope('accuracy'):\n accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1)), tf.float32))\n tf.summary.scalar('accuracy', accuracy)\n tf.summary.histogram('accuracy', accuracy)\n\n merge = tf.summary.merge_all()\n logwriter = tf.summary.FileWriter(FLAGS.LOG_DIR, sess.graph)\n initial = tf.global_variables_initializer()\n sess.run(initial)\n\n data_size = features_train.shape[0]\n iterations = int(data_size / FLAGS.batch_size)\n for _ in range(FLAGS.epoches):\n for i in range(iterations):\n data = []\n labels = []\n if i == iterations - 1:\n data = features_train[i * FLAGS.batch_size: data_size, :, :, :]\n labels = labels_train[i * FLAGS.batch_size: data_size]\n else:\n data = features_train[i * FLAGS.batch_size: (i + 1) * FLAGS.batch_size, :, :, :]\n labels = labels_train[i * FLAGS.batch_size: (i + 1) * FLAGS.batch_size]\n sess.run(train, feed_dict={x: data, y: labels})\n if i % 10 == 0:\n summary, accuracy_res = sess.run([merge, accuracy], feed_dict={x: features_test, y: labels_test})\n logwriter.add_summary(summary, i)\n print(visualize.get_time() +\n ' epoch %d, train_iteration at %d, test score: %f ' % (_, i, accuracy_res))\n sess.close()\n logwriter.close()\n\n\ndef main():\n from tools import dataset\n features_train, labels_train, features_test, labels_test = dataset.load_cifar10(FLAGS.data_path,\n width=FLAGS.IMG_WIDTH,\n height=FLAGS.IMG_HEIGHT,\n one_hot=True)\n train_act(features_train, labels_train, features_test, labels_test)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"gu-yan/mlAlgorithms","sub_path":"tensorflow/inception_impl/Inception_resnet_v2_temsorflow.py","file_name":"Inception_resnet_v2_temsorflow.py","file_ext":"py","file_size_in_byte":12006,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"31"}
+{"seq_id":"27700751805","text":"# -*- coding:utf-8 -*-\nimport wx\nfrom PIL import Image\n\nclass MyFrame(wx.Frame):\n def __init__(self, parent, id):\n wx.Frame.__init__(self, parent, id, u'CM升级工具', size=(600, 400))\n\n # 创建面板\n\n panel = wx.Panel(self)\n\n # 创建按钮\n self.bt_FlipHoriz = wx.Button(panel, label='水平翻转')\n self.bt_FlipVert = wx.Button(panel, label='垂直翻转')\n self.bt_MidBase = wx.Button(panel, label='居中白底') # 确定白底像素\n self.bt_AddWrite = wx.Button(panel, label='添加白底')\n\n # 创建文本\n\n self.lb_FilePath = wx.StaticText(panel, 0, u\"文件路径:\", style=wx.TE_LEFT)\n self.lb_Pixel = wx.StaticText(panel, 0, u\"像 素:\", style=wx.TE_LEFT)\n self.txt_FilePath = wx.TextCtrl(panel, style=wx.TE_LEFT, value=u'请选择图片目录')\n self.txt_Pixel = wx.TextCtrl(panel, style=wx.TE_LEFT, value=u'请输入像素')\n # 创建文本内容框,多行,垂直滚动条\n self.text_contents = wx.TextCtrl(panel, style=wx.TE_MULTILINE | wx.HSCROLL)\n\n # 添加容器\n bsizer_top = wx.BoxSizer(wx.HORIZONTAL)\n\n bsizer_center = wx.BoxSizer(wx.HORIZONTAL)\n\n bsizer_botton1 = wx.BoxSizer(wx.VERTICAL)\n bsizer_botton2 = wx.BoxSizer(wx.VERTICAL)\n bsizer_content = wx.BoxSizer(wx.HORIZONTAL)\n\n # 容器中添加控件\n bsizer_top.Add(self.lb_FilePath, proportion=0, flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT, border=5)\n bsizer_top.Add(self.txt_FilePath, proportion=2, flag=wx.EXPAND | wx.ALL, border=5)\n\n bsizer_center.Add(self.lb_Pixel, proportion=0, flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT,\n border=5)\n bsizer_center.Add(self.txt_Pixel, proportion=2, flag=wx.EXPAND | wx.ALL, border=5)\n\n bsizer_botton1.Add(self.bt_FlipHoriz, proportion=1, flag=wx.ALL, border=5)\n bsizer_botton1.Add(self.bt_FlipVert, proportion=1, flag=wx.ALL, border=5)\n bsizer_botton1.Add(self.bt_MidBase, proportion=1, flag=wx.ALL, border=5)\n bsizer_botton2.Add(self.bt_AddWrite, proportion=1, flag=wx.ALL, border=5)\n bsizer_content.Add(self.text_contents, proportion=1, flag=wx.EXPAND | wx.ALL, border=5)\n\n # wx.VERTICAL 横向分割\n bsizer_all = wx.BoxSizer(wx.VERTICAL)\n # 添加顶部sizer,proportion=0 代表bsizer_top大小不可变化\n bsizer_all.Add(bsizer_top, proportion=0, flag=wx.EXPAND | wx.ALL, border=5)\n bsizer_all.Add(bsizer_center, proportion=0, flag=wx.EXPAND | wx.ALL, border=5)\n # 添加底部sizer,proportion=1 代表bsizer_bottom大小变化\n bsizer_botoom = wx.BoxSizer(wx.HORIZONTAL)\n bsizer_all.Add(bsizer_botoom, proportion=0, flag=wx.EXPAND | wx.ALL, border=5)\n bsizer_botoom.Add(bsizer_botton1, proportion=0, flag=wx.EXPAND | wx.ALL, border=5)\n bsizer_botoom.Add(bsizer_botton2, proportion=0, flag=wx.EXPAND | wx.ALL, border=5)\n bsizer_botoom.Add(bsizer_content, proportion=1, flag=wx.EXPAND | wx.ALL, border=5)\n self.Bind(wx.EVT_BUTTON, self.update, self.bt_FlipHoriz)\n self.Bind(wx.EVT_BUTTON, self.zipweb, self.bt_FlipVert)\n self.Bind(wx.EVT_BUTTON, self.addwrite, self.bt_AddWrite)\n panel.SetSizer(bsizer_all)\n\n def copyFiles(self, sourceDir, targetDir):\n pass\n\n def update(self, event):\n\n # build\n self.text_contents.AppendText('升级结束\\n')\n\n # 生成网站升级包\n def zipweb(self, event):\n pass\n\n def addwrite(self, event):\n try:\n sourceFile = self.txt_FilePath.GetValue()\n image = Image.open(sourceFile)\n image = image.convert('RGBA')\n\n imagewidth = image.size[0] # 图片宽度\n imageheight = image.size[1] # 图片高度\n\n whiteimage = Image.open('白底.jpg')\n whiteimage = whiteimage.convert('RGB')\n\n whiteimage = whiteimage.resize((imagewidth, imageheight))\n\n whiteimage.paste(image, (0, 0), mask=image)\n whiteimage.save(sourceFile)\n self.text_contents.AppendText('白底转换成功\\n')\n except Exception as e:\n self.text_contents.AppendText('报错:{0}\\n'.format(e))\nif __name__ == '__main__':\n app = wx.App()\n frame = MyFrame(parent=None, id=-1)\n frame.Show()\n frame.Center()\n app.MainLoop()\n","repo_name":"ZhuoXinXin/ImageProcessTool","sub_path":"ImageProcessTool.py","file_name":"ImageProcessTool.py","file_ext":"py","file_size_in_byte":4433,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"32156115409","text":"import pygame\r\nimport sys\r\nfrom pygame.color import THECOLORS\r\n\r\nfrom Interface import Interface\r\n\r\n\r\nclass Main:\r\n def __init__(self):\r\n pygame.init()\r\n self.wid = 800\r\n self.hei = 600\r\n self.screen = pygame.display.set_mode((self.wid, self.hei))\r\n self.interface = Interface()\r\n self.functions = Functions()\r\n self.draw_work = True\r\n\r\n def draw(self):\r\n self.interface.draw(self.screen)\r\n\r\n def start(self):\r\n while True:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n return 0\r\n self.draw()\r\n pygame.display.flip()\r\nmain = Main()\r\nmain.start()","repo_name":"Otafat/Watermelon_clicker","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"73223921688","text":"import pytest\nimport numpy as np\nfrom mlir_graphblas import utils\n\n\ndef test_pick_and_renumber_indices():\n rows = np.array([0, 0, 1, 1, 1, 1], dtype=np.uint64)\n cols = np.array([1, 2, 0, 1, 2, 3], dtype=np.uint64)\n vals = np.array([1, 2, 6, 7, 8, 9])\n selected = np.array([1, 1, 0, 0, 1])\n rows, cols, vals = utils.pick_and_renumber_indices(selected, rows, cols, vals)\n np.testing.assert_equal(rows, [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 3, 3, 4, 4, 4, 4])\n np.testing.assert_equal(cols, [0, 1, 2, 3, 0, 1, 2, 3, 1, 2, 1, 2, 0, 1, 2, 3])\n np.testing.assert_equal(vals, [6, 7, 8, 9, 6, 7, 8, 9, 1, 2, 1, 2, 6, 7, 8, 9])\n","repo_name":"python-graphblas/python-mlir-graphblas","sub_path":"mlir_graphblas/tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"15677869348","text":"import pandas as pd\nimport numpy as np\nfrom insurance.component.model_evaluation import ModelEvaluation\nfrom insurance.constant import *\nfrom insurance.exception import InsuranceException\nfrom insurance.util.util import load_object\nfrom insurance.logger import logging\nfrom insurance.entity.artifact_entity import ModelEvaluationArtifact,DataTransformationArtifact,ModelPusherArtifact\n\n\n\nimport os,sys\n\n\n\nclass PredictPipeline:\n def __init__(self):\n pass\n\n def predict(self,features):\n try:\n print(\"Before Loading\")\n model_file_path=r'saved_models\\20230707211336\\model.pkl'\n logging.info(features)\n model=load_object(file_path=model_file_path)\n logging.info('after loading')\n # Convert the input features to a pandas DataFrame with a single sample\n \n preds = model.predict((features))\n return preds\n \n except Exception as e:\n raise InsuranceException(e,sys) from e\n\n\n\nclass CustomData:\n def __init__( self,\n age: int,\n sex: str,\n bmi:int,\n children: int,\n smoker: str,\n region: str):\n\n self.age = age\n\n self.sex = sex\n\n self.bmi =bmi\n\n self.children = children\n\n self.smoker = smoker\n\n self.region = region\n\n \n\n def get_data_as_data_frame(self):\n logging.info('get_data_as_data_frame')\n try:\n custom_data_input_dict = {\n \"age\": [self.age],\n \"sex\": [self.sex],\n \"bmi\": [self.bmi],\n \"children\": [self.children],\n \"smoker\": [self.smoker],\n \"region\": [self.region]\n \n }\n s=pd.DataFrame(custom_data_input_dict)\n logging.info(pd.DataFrame(custom_data_input_dict))\n print(s.head())\n\n return pd.DataFrame(custom_data_input_dict,columns=['age', 'sex', 'bmi', 'children', 'smoker', 'region'])\n\n except Exception as e:\n raise InsuranceException(e, sys) from e","repo_name":"shiva4778/INSURANCE_PREMIUM_PREDICTION_1","sub_path":"insurance/pipeline/predict_pipeline.py","file_name":"predict_pipeline.py","file_ext":"py","file_size_in_byte":2083,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"40750576727","text":"\n\n# Standard Library\nfrom builtins import str\nfrom builtins import range\nimport csv\nimport hashlib\nimport random\nimport string\n\n# Third Party Stuff\nfrom django.core.mail import EmailMultiAlternatives\nfrom .models import MdlUser\nfrom validate_email import validate_email\n\n# Spoken Tutorial Stuff\nfrom events.models import *\n\n\ndef update_participants_count(training):\n training.participant_count = TrainingAttendance.objects.filter(training=training, status__gte=1).count()\n training.save()\n\n\ndef _is_organiser(user):\n try:\n if user.groups.filter(name='Organiser').count() == 1 and user.organiser and user.organiser.status == 1:\n return True\n except:\n pass\n\n\ndef encript_password(password):\n password = hashlib.md5((password + 'VuilyKd*PmV?D~lO19jL(Hy4V/7T^G>p').encode('utf-8')).hexdigest()\n return password\n\n\ndef create_account(w, firstname, lastname, gender, email, category):\n password_string = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8))\n password_encript = encript_password(password_string)\n password = password_encript\n username = email\n mdluser = None\n try:\n mdluser = MdlUser.objects.filter(email=email).first()\n mdluser.institution = w.academic_id\n mdluser.firstname = firstname\n mdluser.lastname = lastname\n mdluser.save()\n except Exception as e:\n mdluser = MdlUser()\n mdluser.auth = 'manual'\n mdluser.firstname = firstname\n mdluser.username = username\n mdluser.lastname = lastname\n mdluser.password = password\n mdluser.institution = w.academic_id\n mdluser.email = email\n mdluser.confirmed = 1\n mdluser.mnethostid = 1\n mdluser.save()\n mdluser = MdlUser.objects.filter(email=email, firstname=firstname, username=username, password=password).first()\n # send password to email\n subject = \"Spoken Tutorial Online Test password\"\n to = [mdluser.email]\n message = '''Hi {0},\n\nYour account password at 'Spoken Tutorials Online Test as follows'\n\nYour current login information is now:\nusername: {1}\npassword: {2}\n\nPlease go to this page to change your password:\n{3}\n\nIn most mail programs, this should appear as a blue link\nwhich you can just click on. If that doesn't work,\nthen cut and paste the address into the address\nline at the top of your web browser window.\n\nCheers from the 'Spoken Tutorials Online Test Center' administrator,\n\nAdmin Spoken Tutorials\n'''.format(mdluser.firstname, mdluser.username, password_string, 'http://onlinetest.spoken-tutorial.org/login/change_password.php')\n\n # send email\n email = EmailMultiAlternatives(\n subject, message, 'administrator@spoken-tutorial.org',\n to=to, bcc=[], cc=[],\n headers={'Reply-To': 'no-replay@spoken-tutorial.org', \"Content-type\": \"text/html;charset=iso-8859-1\"}\n )\n try:\n result = email.send(fail_silently=False)\n except:\n pass\n return mdluser\n\n\ndef get_or_create_participant(w, firstname, lastname, gender, email, category):\n mdluser = None\n # Added category check as zero. Means the call is coming from new student\n # batch upload interface. And category is/was not used.\n if category == 0:\n create_account(w, firstname, lastname, gender, email, category)\n return True\n if w and w.organiser.academic.institution_type.name == 'School' and not email:\n ta = TrainingAttendance()\n ta.status = 1\n ta.training_id = w.id\n ta.firstname = firstname\n ta.lastname = lastname\n ta.gender = gender\n ta.email = email\n ta.save()\n return True\n else:\n mdluser = create_account(w, firstname, lastname, gender, email, category)\n if TrainingAttendance.objects.filter(training_id=w.id, mdluser_id=mdluser.id).exists():\n return True\n ta = TrainingAttendance()\n ta.mdluser_id = mdluser.id\n ta.status = 1\n ta.training_id = w.id\n ta.firstname = mdluser.firstname\n ta.lastname = mdluser.lastname\n ta.gender = gender\n ta.email = mdluser.email\n ta.save()\n return True\n return False\n\n\ndef store_error(error_line_no, count, invalid_emails=None, email=None):\n if not email:\n if not error_line_no:\n error_line_no = error_line_no + str(count)\n else:\n error_line_no = error_line_no + ',' + str(count)\n else:\n if not invalid_emails:\n invalid_emails = invalid_emails + email\n else:\n invalid_emails = invalid_emails + ', ' + email\n csv_file_error = 1\n return csv_file_error, error_line_no, invalid_emails\n\n\ndef can_allow_participant_to_attend(more_then_two_per_day_list, tdate, email):\n \"\"\" restrict participating more then 2 training per day \"\"\"\n if tdate:\n tdate = tdate.split(' ')[0]\n training_count = TrainingAttendance.objects.filter(email=email, training__tdate = tdate, training__status__lte=4, status=1).count()\n if training_count < 2:\n return more_then_two_per_day_list\n if not more_then_two_per_day_list:\n more_then_two_per_day_list = more_then_two_per_day_list + email\n else:\n more_then_two_per_day_list = more_then_two_per_day_list + ', ' + email\n return more_then_two_per_day_list\n\n\ndef is_new_participant(reattempt_list, foss, email):\n \"\"\" check weather already participated in particular software \"\"\"\n training_count = TrainingAttendance.objects.filter(email=email, training__foss_id=foss, training__status__lte=4,\n status=1).count()\n if training_count == 0:\n return reattempt_list\n if not reattempt_list:\n reattempt_list = reattempt_list + email\n else:\n reattempt_list = reattempt_list + ', ' + email\n return reattempt_list\n\n\ndef check_csvfile(user, file_path, w=None, flag=0, **kwargs):\n tdate = None\n foss = None\n if w:\n try:\n tdate = w.tdate.strftime(\"%Y-%m-%d\")\n foss = w.foss_id\n except:\n tdate = w.tdate\n foss = w.foss_id\n if kwargs and 'tdate' in kwargs['form_data'] and 'foss' in kwargs['form_data']:\n tdate = kwargs['form_data']['tdate']\n foss = kwargs['form_data']['foss']\n\n csv_file_error = 0\n error_line_no = ''\n invalid_emails = ''\n reattempt_list = ''\n more_then_two_per_day_list = ''\n with open(file_path, 'rbU') as csvfile:\n count = 0\n csvdata = csv.reader(csvfile, delimiter=',', quotechar='|')\n try:\n for row in csvdata:\n count = count + 1\n try:\n row_length = len(row)\n if row_length < 1:\n continue\n if row_length < 4:\n csv_file_error, error_line_no, invalid_emails = store_error(error_line_no, count, invalid_emails)\n continue\n firstname = row[0].strip().title()\n lastname = row[1].strip().title()\n gender = row[3].strip().title()\n email = row[2].strip().lower()\n if not firstname or not gender or row_length < 4 or ((user.organiser.academic.institution_type.name != 'School' or (w and w.organiser.academic.institution_type.name != 'School')) and not email):\n csv_file_error, error_line_no, invalid_emails = store_error(error_line_no, count, invalid_emails)\n continue\n if row_length > 3 and email:\n if not flag:\n if not validate_email(email, verify=True):\n csv_file_error, error_line_no, invalid_emails = store_error(error_line_no, count, invalid_emails, email)\n continue\n # restrict the participant\n more_then_two_per_day_list = can_allow_participant_to_attend(more_then_two_per_day_list, tdate, email)\n reattempt_list = is_new_participant(reattempt_list, foss, email)\n if flag and flag <= 2 and not csv_file_error:\n if not w:\n return 1, error_line_no\n get_or_create_participant(w, firstname, lastname, gender, email, 2)\n except Exception as e:\n print(e)\n csv_file_error, error_line_no, invalid_emails = store_error(error_line_no, count, invalid_emails)\n if error_line_no:\n error_line_no = \"\"\"\n
\n
\n The Line numbers {0} in CSV file data is not in a proper format in the Participant list. The format should be First name, Last name, Email, Gender.\n For more details Click here.\n \n
\n The Line numbers {0} in CSV file data is not in a proper format in the Participant list. The format should be First name, Last name, Email, Gender.\n For more details Click here.\n \n
\n
\n \"\"\".format(error_line_no, \"http://process.spoken-tutorial.org/images/c/c2/Participant_data.pdf\")\n if invalid_emails:\n error_line_no += \"\"\"\n
\n
\n The participants listed below do not have valid email-ids. Pls create valid email-ids and upload once again.\n {0}\n \n
\n
\n \"\"\".format(invalid_emails)\n if flag == 3 and int(w.participant_count < count):\n csv_file_error = 1\n error_line_no = \"\"\"\n
\n
\n Training participant count less than {0}.\n
\n
\n \"\"\".format(w.participant_count)\n if more_then_two_per_day_list:\n csv_file_error = 1\n error_line_no += \"\"\"\n
\n
\n The participants listed below have already enrolled for 2 software training workshops on the given date.\n \n NOTE: Participants cannot enroll for more than 2 workshops per day. {0}\n \n
\n
\n \"\"\".format(more_then_two_per_day_list)\n if reattempt_list:\n if w:\n tps = w.trainingattendance_set.values_list('email')\n for p in tps:\n email = str(p[0])\n reattempt_list = reattempt_list.replace(','+email, '').replace(email+',', '').replace(email, '')\n if reattempt_list:\n csv_file_error = 1\n error_line_no += \"\"\"\n
\n
\n The participants listed below have already attended this software training workshop before. {0}\n
\n The participants listed below have already enrolled for 2 software training workshops on the given date.\n \n NOTE: Participants cannot enroll for more than 2 workshops per day. {0}\n \n
\n
\n \"\"\".format(more_then_two_per_day_list)\n if reattempt_list:\n csv_file_error = 1\n error_line_no += \"\"\"\n
\n
\n The participants listed below have already attended this software training workshop before. {0}\n
\n
\n \"\"\".format(reattempt_list)\n return csv_file_error, error_line_no, reattempt_list, more_then_two_per_day_list\n","repo_name":"Spoken-tutorial/spoken-website","sub_path":"mdldjango/get_or_create_participant.py","file_name":"get_or_create_participant.py","file_ext":"py","file_size_in_byte":13418,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"31"}
+{"seq_id":"12567739939","text":"from django.urls import path\nfrom .import views\n\napp_name = 'auth_app'\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('register', views.register_method, name= 'register'),\n path('login', views.login_method, name='login'),\n path('logout', views.logout_method, name='logout'),\n path('profile', views.profile_update, name='profile'),\n]\n\n","repo_name":"Kakarotpani/bezen","sub_path":"auth_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"15730165637","text":"import unittest\nfrom app import *\nclass TestPredictImage(unittest.TestCase):\n APP_ROOT_FOLDER = os.path.dirname(os.path.abspath(__file__))\n def test_dog_detector(self):\n image1=os.path.join(APP_ROOT_FOLDER, '{}'.format(\"dogImages/train/021.Belgian_sheepdog/Belgian_sheepdog_01492.jpg\"))\n image2=os.path.join(APP_ROOT_FOLDER, '{}'.format(\"dogImages/train/022.Belgian_tervuren/Belgian_tervuren_01563.jpg\"))\n image3=os.path.join(APP_ROOT_FOLDER, '{}'.format(\"lfw/Ben_Howland/Ben_Howland_0001.jpg\"))\n image4=os.path.join(APP_ROOT_FOLDER, '{}'.format(\"lfw/Ben_Howland\"))\n image5=os.path.join(APP_ROOT_FOLDER, '{}'.format(\"test\"))\n \n\n self.assertAlmostEqual(dog_detector(image1),True)\n self.assertAlmostEqual(dog_detector(image2),True)\n self.assertAlmostEqual(dog_detector(image3),False)\n self.assertAlmostEqual(dog_detector(image4),False)\n self.assertAlmostEqual(dog_detector(image5),False)\n def test_face_detector(self):\n image1=os.path.join(APP_ROOT_FOLDER, '{}'.format(\"dogImages/train/021.Belgian_sheepdog/Belgian_sheepdog_01492.jpg\"))\n image2=os.path.join(APP_ROOT_FOLDER, '{}'.format(\"dogImages/train/022.Belgian_tervuren/Belgian_tervuren_01563.jpg\"))\n image3=os.path.join(APP_ROOT_FOLDER, '{}'.format(\"lfw/Ben_Howland/Ben_Howland_0001.jpg\"))\n image4=os.path.join(APP_ROOT_FOLDER, '{}'.format(\"lfw/Ben_Howland\"))\n image5=os.path.join(APP_ROOT_FOLDER, '{}'.format(\"test\"))\n \n\n self.assertAlmostEqual(face_detector(image1),False)\n self.assertAlmostEqual(face_detector(image2),False)\n self.assertAlmostEqual(face_detector(image3),True)\n self.assertAlmostEqual(face_detector(image4),False)\n self.assertAlmostEqual(face_detector(image5),False)\n def test_predictImage(self):\n image1=os.path.join(APP_ROOT_FOLDER, '{}'.format(\"dogImages/train/021.Belgian_sheepdog/Belgian_sheepdog_01492.jpg\"))\n image2=os.path.join(APP_ROOT_FOLDER, '{}'.format(\"dogImages/train/022.Belgian_tervuren/Belgian_tervuren_01563.jpg\"))\n image3=os.path.join(APP_ROOT_FOLDER, '{}'.format(\"lfw/Ben_Howland/Ben_Howland_0001.jpg\"))\n \n model=load_ResNet50Model()\n \n\n _,result=predictImage(image1,model)\n self.assertAlmostEqual(result,\"Belgian_sheepdog\")\n\n _,result=predictImage(image2,model)\n self.assertAlmostEqual(result,\"Belgian_tervuren\")\n\n self.assertRaises(Exception, predictImage,image1,None)\n self.assertRaises(Exception, predictImage,image3,None)\n\n \n \n\n \n\n","repo_name":"SadhanaPaladugu/DogProject","sub_path":"test_app.py","file_name":"test_app.py","file_ext":"py","file_size_in_byte":2594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"12254626463","text":"import pygame, sys\nfrom pygame.locals import *\nfrom spritesheet import SpriteSheet\nfrom config import *\n\n\nclass Crystal:\n def __init__(self, surface, image, rect):\n self.image = image\n self.rect = Rect(rect)\n self.max_health = 1000\n self.health = 1000\n self.__surface = surface\n self.HealthRect = Rect(250, 570, 300, 4)\n self.x = self.rect.x\n self.y = self.rect.y\n self.regen = 0\n def draw(self):\n self.__surface.blit(self.image, self.rect)\n if self.health < self.max_health:\n self.health += self.regen * .01\n #To Do: Draw Health Bar\n pygame.draw.rect(self.__surface, (255,0,0), self.HealthRect)\n ratio = self.health / self.max_health\n gRect = Rect(self.HealthRect)\n gRect.w *= ratio\n pygame.draw.rect(self.__surface, (0,255,0), gRect)\n\n def damage(self, points):\n self.health -= points\n \n \n","repo_name":"Micah0320/The-Crystal-of-Ulumok","sub_path":"game/crystal.py","file_name":"crystal.py","file_ext":"py","file_size_in_byte":951,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"}
+{"seq_id":"38099441682","text":"# 861.\n# 翻转矩阵后的得分\n#\n# 有一个二维矩阵A其中每个元素的值为0或1 。移动是指选择任一行或列,并转换该行或列中的每一个值:将所有0都更改为1,将所有1都更改为0。\n# 在做出任意次数的移动后,将该矩阵的每一行都按照二进制数来解释,矩阵的得分就是这些数字的总和。返回尽可能高的分数。\n# 示例:\n# 输入:[[0, 0, 1, 1], [1, 0, 1, 0], [1, 1, 0, 0]]\n# 输出:39\n# 解释:转换为[[1, 1, 1, 1], [1, 0, 0, 1], [1, 1, 1, 1]]0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39\n# 提示:\n# 1 <= A.length <= 20\n# 1 <= A[0].length <= 20 A[i][j]是0或1\n\n\nclass Solution(object):\n def matrixScore(self, A):\n \"\"\"\n :type A: List[List[int]]\n :rtype: int\n \"\"\"\n def change(martrix, row = -1, column = -1):\n if row != -1:\n for i in range(len(martrix[row])):\n if martrix[row][i] == 0:\n martrix[row][i] = 1\n else:\n martrix[row][i] = 0\n if column != -1:\n for i in range(len(martrix)):\n if martrix[i][column] == 0:\n martrix[i][column] = 1\n else:\n martrix[i][column] = 0\n return martrix\n for i in range(len(A)):\n if A[i][0] == 0: # 第i行第0列为0,就改变这行\n A = change(A, i, -1)\n numOfZero, numOfOne = 0, 0\n for i in range(1, len(A[0])):\n numOfZero, numOfOne = 0, 0\n for j in range(0, len(A)):\n if A[j][i] == 0:\n numOfZero += 1\n else:\n numOfOne += 1\n if numOfZero > numOfOne: # 第i列0的个数比1多,就改变这列\n A = change(A, -1, i)\n res = 0\n cur = ''\n for i in range(len(A)):\n cur = ''\n for j in range(len(A[0])):\n cur += str(A[i][j])\n res += int(cur, 2)\n return res\n\n # '''\n # 思路:\n # 可以这样看,n*m的每个格子都具有一个权重,其中每一行权重都自左向右递减,\n # 为使总和最大则尽可能使权重大的格子填“1”。最左边一列权重最大,所以总可以通过\n # 行翻转使左边第一列全都置“1”,后面就不能再使用行翻转了,以免破环当前的结构,\n # 所以考虑列翻转。对于除最左边第一列外的每一列,总可以通过列翻转使得该列“1”\n # 的个数不小于“0”的个数。最后所有填“1”的格子的权重和即为答案。\n # '''\n #\n # class Solution:\n # def matrixScore(self, A: List[List[int]]) -> int:\n # n, m = len(A), len(A[0])\n # for i in range(n):\n # if A[i][0] == 0:\n # for j in range(m):\n # A[i][j] = 1 ^ A[i][j]\n # sum = 0\n # for i in zip(*A):\n # m -= 1\n # sum += 2 ** m * max(i.count(1), i.count(0))\n # return sum","repo_name":"wulalala17/leetcode","sub_path":"leetcode/2020/December/861matrixScore.py","file_name":"861matrixScore.py","file_ext":"py","file_size_in_byte":3157,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"}
+{"seq_id":"31063792411","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.tree import plot_tree\nfrom sklearn.model_selection import train_test_split\nfrom pandas.core.common import SettingWithCopyWarning\nimport warnings \nwarnings.simplefilter(action=\"ignore\", category=SettingWithCopyWarning)\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import LabelEncoder\n\ndef clean_dataset(df):\n assert isinstance(df, pd.DataFrame), \"df needs to be a pd.DataFrame\"\n df.dropna(inplace=True)\n indices_to_keep = ~df.isin([np.nan, np.inf, -np.inf]).any(1)\n return df[indices_to_keep].astype(np.float64)\n\n#read the data from the csv and delete blank spaces on columns names\ndf = pd.read_csv(\"healthcare-dataset-stroke-data.csv\")\ndf = df.drop(columns=['gender','ever_married','Residence_type', 'work_type'])\ndf.colums = df.columns.str.replace(' ','')\n#deleting information where a value is missed\ndf_rows_complete = df.loc[(df['bmi'] != 'N/A')]\n\n\nobj = df_rows_complete['stroke']\nexpl = df_rows_complete.drop(columns='stroke', axis='columns')\n\n\nle_smoking_status = LabelEncoder()\n\n\nexpl['smoking_status_n'] = le_smoking_status.fit_transform(expl['smoking_status'])\n\nexpl_n = expl.drop(columns='smoking_status', axis='columns')\nexpl_n = clean_dataset(expl_n)\nprint(expl_n)\n\nX_train, X_test, y_train, y_test = train_test_split(expl_n, obj, test_size=0.2)\n\nmodel = DecisionTreeRegressor(min_samples_split=2, max_depth=3)\n\nmodel.fit(X_train, y_train)\nmodel.score(X_test, y_test)\n\ntreeFigure = plt.figure(figsize=(150, 155), dpi=42)\n\nex = plot_tree(model, feature_names=expl_n.columns, rounded=True, class_names=[\"No stroke\", \"Stroke\"], filled=False)\n\ntreeFigure.savefig(\"decission.jpg\")\n","repo_name":"scarlosro/AIProject","sub_path":"stroke_pre_fra2.py","file_name":"stroke_pre_fra2.py","file_ext":"py","file_size_in_byte":1714,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"3847365188","text":"def log_3_vec( drg, var):\n for ii in range(3):\n drg.add_variable(var+\"[\"+str(ii)+\"]\")\n\ndr_group = trick.sim_services.DRAscii(\"V_1_State\")\ndr_group.set_cycle(12)\ndr_group.freq = trick.sim_services.DR_Always\n\nfor veh in [\"vehA\",\"vehB\"]:\n log_3_vec( dr_group, veh+\".ned.ned_state.cart_coords\")\n for coords in [\"sphere\", \"ellip\"]:\n dr_group.add_variable( veh +\".ned.ned_state.\"+coords+\"_coords.altitude\")\n dr_group.add_variable( veh +\".ned.ned_state.\"+coords+\"_coords.latitude\")\n dr_group.add_variable( veh +\".ned.ned_state.\"+coords+\"_coords.longitude\")\n\nlog_3_vec( dr_group, \"rel_state.vehA_wrt_vehB.rel_state.trans.position\")\nlog_3_vec( dr_group, \"rel_state.vehA_wrt_vehB.rel_state.trans.velocity\")\nlog_3_vec( dr_group, \"rel_state.vehB_wrt_vehA.rel_state.trans.position\")\nlog_3_vec( dr_group, \"rel_state.vehB_wrt_vehA.rel_state.trans.velocity\")\nlog_3_vec( dr_group, \"vehA.dyn_body.structure.state.trans.position\")\n\ntrick.add_data_record_group(dr_group)\n","repo_name":"nasa/jeod","sub_path":"models/dynamics/derived_state/verif/SIM_NED/Log_data/log_orbital_state_rec.py","file_name":"log_orbital_state_rec.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"31"}
+{"seq_id":"40749358157","text":"# -*- coding: utf-8 -*-\n\n\n# Third Party Stuff\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('creation', '0003_fosssupercategory'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='fosscategory',\n name='category',\n field=models.ManyToManyField(to='creation.FossSuperCategory', null=True),\n ),\n ]\n","repo_name":"Spoken-tutorial/spoken-website","sub_path":"creation/migrations/0004_fosscategory_category.py","file_name":"0004_fosscategory_category.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"31"}
+{"seq_id":"11424473624","text":"from datetime import timedelta\nfrom time import mktime\nfrom celery import shared_task\nfrom decouple import config\nfrom django.db import transaction\nfrom django.utils import timezone\nfrom nylas import APIClient\nfrom rest_framework.exceptions import ValidationError\n\nfrom ..models import (\n NylasUserAccount, Thread, Folder, Label, Message, Participant,\n MessageParticipant,\n)\n\n\ndef create_message_participant(message_instance, data: dict, participant_type):\n participant, _ = Participant.objects.get_or_create(\n email=data.get('email'), defaults={'name': data.get('name')}\n )\n MessageParticipant.objects.create(\n message=message_instance,\n participant=participant,\n type=participant_type,\n )\n\n\ndef save_message_by_id(message_id, thread_instance: Thread, nylas):\n \"\"\"\n message.id\n message.account_id\n message.body\n message.date\n message.folder\n message.snippet\n message.starred\n message.subject\n message.thread_id\n message.unread\n message.bcc\n message.cc\n message.from_\n message.to\n\n message.object\n message.files\n message.events\n message.labels\n message.received_at\n \"\"\"\n message = nylas.messages.get(message_id)\n # get or create folder if it exists in message\n if hasattr(message, 'folder') and message.folder:\n message_folder, _ = Folder.objects.get_or_create(\n id=message.folder.id,\n name=message.folder.name,\n account_id=thread_instance.account_id,\n defaults={\n 'display_name': message.folder.display_name,\n })\n else:\n message_folder = None\n\n # save message instance\n message_instance, created = Message.objects.update_or_create(\n id=message.id,\n account_id=thread_instance.account_id,\n defaults=dict(\n body=message.body,\n date=message.date,\n folder=message_folder,\n snippet=message.snippet,\n starred=message.starred,\n subject=message.subject,\n thread_id=thread_instance,\n unread=message.unread,\n reply_to_message_id=message.reply_to_message_id,\n )\n )\n # participant should not change in message; hence only create them if message is created\n if created:\n # create bcc participants\n for bcc in message.bcc:\n create_message_participant(message_instance, bcc, 'bcc')\n # create cc participants\n for cc in message.cc:\n create_message_participant(message_instance, cc, 'cc')\n # create from participants\n for from_ in message.from_:\n create_message_participant(message_instance, from_, 'from')\n # create reply_to participants\n for reply_to in message.reply_to:\n create_message_participant(message_instance, reply_to, 'reply_to')\n # create to participants\n for to in message.to:\n create_message_participant(message_instance, to, 'to')\n\n\ndef save_thread_with_messages(thread, user: NylasUserAccount, nylas):\n \"\"\"\n thread.id\n thread.account_id\n thread.first_message_timestamp\n thread.has_attachments\n thread.last_message_received_timestamp\n thread.last_message_timestamp\n thread.starred\n thread.subject\n thread.unread\n thread.version\n\n thread.message_ids\n thread.labels # Gmail accounts only\n thread.folders # All providers other than Gmail\n\n ### not implemented:\n thread.object\n thread.first_message_at\n thread.snippet\n thread.participants\n thread.draft_ids\n thread.last_message_received_at\n thread.last_message_at\n \"\"\"\n # save thread instance\n thread_instance, created = Thread.objects.update_or_create(\n id=thread.id, account_id=user,\n defaults=dict(\n first_message_timestamp=thread.first_message_timestamp,\n has_attachments=thread.has_attachments,\n last_message_received_timestamp=thread.last_message_received_timestamp,\n last_message_sent_timestamp=thread.last_message_sent_timestamp,\n last_message_timestamp=thread.last_message_timestamp,\n starred=thread.starred,\n subject=thread.subject,\n unread=thread.unread,\n version=thread.version,\n )\n )\n # add many-to-many relationship between thread and folder\n thread_instance.folders.clear()\n for folder in thread.folders:\n # create folder instance if it doesn't exist\n thread_folder, _ = Folder.objects.get_or_create(\n id=folder.id, name=folder.name, account_id=user,\n defaults={'display_name': folder.display_name}\n )\n thread_instance.folders.add(thread_folder)\n\n # add many-to-many relationship between thread and label\n thread_instance.labels.clear()\n for label in thread.labels:\n # create label instance if it doesn't exist\n thread_label, _ = Label.objects.get_or_create(\n id=label.id, name=label.name, account_id=user,\n defaults={'display_name': label.display_name}\n )\n thread_instance.labels.add(thread_label)\n\n # save messages associated with thread\n for message_id in thread.message_ids:\n save_message_by_id(message_id, thread_instance, nylas)\n\n\ndef get_nylas_instance(user_id: str):\n try:\n user = NylasUserAccount.objects.get(id=user_id)\n except NylasUserAccount.DoesNotExist:\n print(f'NylasUserAccount does not exist {user_id}')\n return None, None\n\n try:\n nylas = APIClient(\n config('NYLAS_CLIENT_ID'),\n config('NYLAS_CLIENT_SECRET'),\n user.access_token,\n )\n except Exception as e:\n print(f'Exception Occurred connecting nylas API Client {e}')\n return None, None\n\n return user, nylas\n\n\n@shared_task\ndef sync_nylas_for_user(user_id: str, resync=False):\n user, nylas = get_nylas_instance(user_id)\n if not user or not nylas:\n return\n\n # check of sync status from nylas\n account = nylas.account\n if account.sync_state != 'running':\n print(f'Sync is not running on user {user_id}')\n return\n\n # for thread in nylas.threads.all():\n if resync:\n sync_days = config('LAST_N_DAYS_RESYNC', cast=int)\n else:\n sync_days = config('LAST_N_DAYS_SYNC', cast=int)\n\n sync_after_datetime = timezone.now() - timedelta(days=sync_days)\n after_timestamp = int(mktime(sync_after_datetime.timetuple()))\n for thread in nylas.threads.where(last_message_after=after_timestamp):\n # saving with atomic transaction so\n # the overhead of saving is minimal\n with transaction.atomic():\n save_thread_with_messages(thread, user, nylas)\n\n\n@shared_task\ndef update_thread_from_webhook_delta(account_id: str, thread_id: str):\n print(f'Updating thread {thread_id} for account {account_id}')\n user, nylas = get_nylas_instance(account_id)\n if not user or not nylas:\n return\n\n thread = nylas.threads.get(thread_id)\n with transaction.atomic():\n save_thread_with_messages(thread, user, nylas)\n","repo_name":"ashwinbande/user-management-with-email-integration","sub_path":"nylas_email_app/tasks/sync_nylas_for_user.py","file_name":"sync_nylas_for_user.py","file_ext":"py","file_size_in_byte":7126,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"2920382950","text":"import pandas as pd\n\n#Part 1 \ndf_gme = pd.read_csv('gme_data_clean.csv')\ndf_gme.head()\n\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom matplotlib.backends.backend_pdf import PdfPages\n\nsns.set()\n\nplt.suptitle('Game Stop Stock')\n\nfor plot_idx in range(1, 3):\n plt.subplot(1, 2, plot_idx)\n x = df_gme['days since 2020_Feb_03']\n for label in ['Low', 'High']:\n y = df_gme[label]\n plt.plot(x, y, label=label)\n plt.ylabel('price ($)')\n plt.legend()\n plt.xlabel('days since Feb 3 2020')\n\n if plot_idx == 2:\n # only set y scale on rightward plot\n plt.yscale('log')\n\n\nplt.gcf().set_size_inches((10, 5))\n\nf_out = 'game_stop.pdf'\nwith PdfPages(f_out) as pdf:\n pdf.savefig(bbox_inches='tight') \n","repo_name":"tarasawhney/DS3000","sub_path":"HW2/gamestop.py","file_name":"gamestop.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"32310879186","text":"from os import path\nfrom contact import Contact\n\nclass PhoneBook:\n def __init__(self, path):\n self.contacts = []\n self.filePath = path\n\n self.ReadContacts()\n\n def AddContact(self, contact):\n self.contacts.append(contact)\n\n def PrintContacts(self):\n for contact in self.contacts:\n print(contact.ToString())\n\n def ReadContacts(self):\n if path.exists(self.filePath):\n file = open(self.filePath, \"r\", encoding=\"utf-8\")\n for row in file:\n contact = row.strip().split(\",\")\n\n contact_obj = Contact(contact[0], contact[1], contact[2], contact[3])\n self.contacts.append(contact_obj)\n\n file.close()\n\n def SaveContacts(self):\n contacts = \"\"\n for contact in self.contacts:\n contacts += contact.ToCSV() + \"\\n\"\n\n file = open(self.filePath, \"w\", encoding=\"utf-8\")\n file.write(contacts)\n file.close()\n","repo_name":"samikojo-tuni/2021_Python_3005","sub_path":"Examples/Classes/phonebook.py","file_name":"phonebook.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"12991694701","text":"#!/usr/bin/python3.6\n# -*- coding: UTF-8 -*-\nfrom multiprocessing import Process, Queue\n\nimport pangolin as pango\nimport numpy as np\nimport OpenGL.GL as gl\nimport OpenGL.GLUT as glut\nfrom multi_robot_tools import MultiRobotTools\n\nclass MultiViewer3D(object):\n '''\n 3d viewer for g2o maps\n - based off ficiciSLAM's viewer\n - github.com/kemfic/ficiciSLAM\n '''\n is_optim = False\n tform = np.array([[0.0, 0.0, 1.0, 0.0],\n [1.0, 0.0, 0.0, 0.0],\n [0.0, 1.0, 0.0, 0.0],\n [0.0, 0.0, 0.0, 1.0]])\n def __init__(self, graph,robot_num,file_name='g2o_stuff'):\n self.file_name = file_name\n self.init()\n self.color_init()\n self.graph = graph\n self.nodes = np.dot(graph.nodes, self.tform)\n self.edges = np.array(graph.edges)\n self.robot_num = robot_num\n self.nodes_keys = np.array(graph.nodes_keys)\n self.edges_key_pairs = np.array(graph.edges_key_pairs)\n self.multi_robot_tools = MultiRobotTools()\n self.separator_edges = self.graph.separator_edges \n self.separator_nodes = np.dot(self.graph.separator_nodes,self.tform)\n self.partition_graph_np()\n while not pango.ShouldQuit():\n self.refresh()\n\n def init(self):\n w, h = (1024,768)\n f = 2000 #420\n\n pango.CreateWindowAndBind(self.file_name , w, h)\n gl.glEnable(gl.GL_DEPTH_TEST)\n glut.glutInit()\n self.camera_size=0.2\n self.viewpoint_x = 0\n self.viewpoint_y = 0 \n self.viewpoint_z = 100\n self.viewpoint_f = 1000\n # Projection and ModelView Matrices\n self.look_view = pango.ModelViewLookAt(self.viewpoint_x, self.viewpoint_y, self.viewpoint_z,\n 0.0, 0.0, 0.0,\n 0.0, -1.0, 0.0)\n self.scam = pango.OpenGlRenderState(\n pango.ProjectionMatrix(w, h, self.viewpoint_f, self.viewpoint_f, w //2, h//2, 0.1, 100000),self.look_view\n )#pango.AxisDirection.AxisY))\n self.handler = pango.Handler3D(self.scam)\n \n # Interactive View in Window\n self.dcam = pango.CreateDisplay()\n self.dcam.SetBounds(0.0, 1.0, 0.0, 1.0, -w/h)\n panel = pango.CreatePanel('ui')\n panel.SetBounds(0.0, 1.0, 0.0, 180/640.)\n\n self.axis = pango.Renderable()\n # print(dir(tree))\n # print(dir(pango.Axis()))\n self.axis.Add(pango.Axis())\n # def draw(view):\n # view.Activate(self.scam)\n # tree.Render()\n # self.dcam.SetDrawFunction(draw)\n # self.rename_id = pango.VarString('ui.rename id', \"10\")\n # self.rename_id_dir = pango.VarString('ui.rename id dir', \"10\")\n\n self.reset_view_button = pango.VarBool('ui.Reset View', value=False, toggle=False)\n self.show_grid = pango.VarBool('ui.Show Grid', value=True, toggle=True)\n self.show_id = pango.VarBool('ui.Show Id', value=False, toggle=False)\n\n self.show_g2o_id = pango.VarBool('ui.Show G2o Id', value=False, toggle=True)\n self.show_gtsam_id = pango.VarBool('ui.Show Gtsam Id', value=False, toggle=True)\n\n self.show_robot = pango.VarBool('ui.Show Robot', value=False, toggle=False)\n\n self.show_separator = pango.VarBool('ui.Show Separator', value=True, toggle=True)\n self.show_separator_only = pango.VarBool('ui.Only Show Separator', value=False, toggle=True)\n \n self.show_robot_1 = pango.VarBool('ui.Show Robot 1', value=True, toggle=True)\n self.show_robot_2 = pango.VarBool('ui.Show Robot 2', value=True, toggle=True)\n self.show_robot_3 = pango.VarBool('ui.Show Robot 3', value=True, toggle=True)\n self.show_robot_4 = pango.VarBool('ui.Show Robot 4', value=True, toggle=True)\n\n self.show_list = [self.show_robot_1,self.show_robot_2,self.show_robot_3,self.show_robot_4]\n\n\n\n self.rename_id_button = pango.VarBool('ui.Renameid', value=False, toggle=False)\n self.rename_id_dir_button = pango.VarBool('ui.Renameid Dir', value=False, toggle=False)\n\n self.iterations = pango.VarString('ui.Iterations', \"10\")\n self.init_guess_button = pango.VarBool('ui.Initial Guess', value=False, toggle=False)\n self.reload_button = pango.VarBool('ui.Reload', value=False, toggle=False)\n self.optimize_button = pango.VarBool('ui.Optimize', value=False, toggle=False)\n\n \n\n\n\n self.dcam.SetHandler(self.handler)\n self.dcam.Activate()\n\n pango.RegisterKeyPressCallback(ord('r'), self.optimize_callback)\n pango.RegisterKeyPressCallback(ord('t'), self.switch_callback)\n\n \n def color_init(self):\n color_list = [[255,69,0],[255,215,0],[0,255,127],[0,191,255],[138,43,226]]\n self.color_list = color_list\n self.separator_edge_color = [244,164,96]\n self.separator_node_color = [255,250,205]\n\n def refresh(self):\n\n if pango.Pushed(self.reset_view_button):\n self.reset_view_callback()\n print(\"reset view\")\n if pango.Pushed(self.rename_id_button):\n print(\"rename id\")\n if pango.Pushed(self.rename_id_dir_button):\n print(\"rename id dir\")\n if pango.Pushed(self.init_guess_button):\n print(\"init_guess_button\")\n self.init_guess_callback()\n if pango.Pushed(self.reload_button):\n print(\"reload\")\n if pango.Pushed(self.optimize_button):\n print(\"optimize\")\n self.optimize_button_callback()\n\n \n #clear and activate screen\n gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)\n gl.glClearColor(0.15, 0.15, 0.15, 0.0)\n\n #gl.glClearColor(1.0, 1.0, 1.0, 0.0)\n\n self.dcam.Activate(self.scam)\n\n gl.glLineWidth(5)\n self.axis.Render()\n\n\n if self.show_grid.Get():\n gl.glLineWidth(1)\n self.drawPlane()\n \n if self.show_separator.Get():\n # draw separator\n if len(self.separator_nodes) >1:\n gl.glLineWidth(2)\n gl.glColor3f(self.separator_node_color[0]/255.0, self.separator_node_color[1]/255.0, self.separator_node_color[2]/255.0)\n pango.DrawCameras(self.separator_nodes,self.camera_size)\n \n if len(self.separator_edges) >1:\n gl.glLineWidth(3)\n gl.glColor3f(self.separator_edge_color[0]/255.0, self.separator_edge_color[1]/255.0, self.separator_edge_color[2]/255.0)\n pango.DrawLines(self.separator_edges[:,0,:-1, -1], self.separator_edges[:,1,:-1,-1])\n # pango.DrawText('Hello, world!', 20, 20)\n\n for robot_id in range(self.robot_num):\n edge_color = self.color_list[robot_id]\n nodes = self.nodes_dict[robot_id]\n edges = self.edges_dict[robot_id]\n if self.show_list[robot_id].Get() and not self.show_separator_only.Get():\n # render\n # render cameras\n gl.glLineWidth(1)\n if len(nodes) > 1:\n gl.glColor3f(edge_color[0]/255.0, edge_color[1]/255.0, edge_color[2]/255.0)\n # gl.glColor3f(1.0, 1.0, 1.0)\n\n pango.DrawCameras(nodes,self.camera_size)\n \n # render edges\n if len(edges) > 1:\n gl.glColor3f(edge_color[0]/255.0, edge_color[1]/255.0, edge_color[2]/255.0)\n pango.DrawLines(edges[:,0,:-1, -1], edges[:,1,:-1,-1])\n if(self.show_gtsam_id.Get() or self.show_g2o_id.Get()):\n self.draw_vertex_key()\n\n pango.FinishFrame()\n\n def partition_graph_np(self):\n self.nodes_dict = {}\n self.edges_dict = {}\n\n for robot_id in range(self.robot_num):\n node_id_mask = np.array([self.multi_robot_tools.key2robot_id_g2o(key)==robot_id for key in self.nodes_keys])\n # node_id_mask = np.array([self.multi_robot_tools.key2robot_id_g2o(key) for key in self.nodes_keys])\n # node_id_mask = np.array([key for key in self.nodes_keys])\n\n # print(node_id_mask)\n \n self.nodes_dict[robot_id] = self.nodes[node_id_mask]\n\n node_key = self.nodes_keys[node_id_mask]\n\n # print(\"----------node_key---------------\")\n # print(\"----------robot\"+str(robot_id)+'-----------')\n # print(node_key)\n\n\n edge_id_mask = np.array([ (self.multi_robot_tools.key2robot_id_g2o(key_pair[0]) ==robot_id or self.multi_robot_tools.key2robot_id_g2o(key_pair[1])==robot_id)\n for key_pair in self.edges_key_pairs])\n\n edges_key_pairs = self.edges_key_pairs[edge_id_mask]\n\n # print(\"----------edge_key---------------\")\n # print(\"----------robot\"+str(robot_id)+'-----------')\n # print(edges_key_pairs)\n\n self.edges_dict[robot_id] = self.edges[edge_id_mask]\n\n\n def update(self, graph=None):\n '''\n add new stuff to queues\n '''\n \n self.nodes = np.dot(self.graph.nodes_optimized, self.tform)\n self.edges = self.graph.edges_optimized\n\n def drawPlane(self,num_divs=30, div_size=5):\n # Plane parallel to x-z at origin with normal -y\n minx = -num_divs*div_size\n miny = -num_divs*div_size\n maxx = num_divs*div_size\n maxy = num_divs*div_size\n #gl.glLineWidth(2)\n #gl.glColor3f(0.7,0.7,1.0)\n gl.glColor3f(0.7,0.7,0.7)\n gl.glBegin(gl.GL_LINES)\n for n in range(2*num_divs):\n gl.glVertex3f(minx+div_size*n,miny,0)\n gl.glVertex3f(minx+div_size*n,maxy,0)\n gl.glVertex3f(minx,miny+div_size*n,0)\n gl.glVertex3f(maxx,miny+div_size*n,0)\n gl.glEnd()\n\n def optimize_callback(self):\n self.graph.optimize()\n self.is_optim = False\n self.switch_callback()\n\n def switch_callback(self):\n self.is_optim = ~self.is_optim\n if self.is_optim:\n print(\"optimized\")\n self.nodes = np.dot(self.graph.nodes_optimized, self.tform)\n self.edges = self.graph.edges_optimized\n else:\n print(\"original\")\n self.nodes = np.dot(self.graph.nodes, self.tform)\n self.edges = self.graph.edges\n\n def init_guess_callback(self):\n self.graph.initial_guess()\n self.graph.update_key_position()\n self.update()\n self.partition_graph_np()\n\n def optimize_button_callback(self):\n self.graph.optimize(int(self.iterations.Get()))\n self.graph.update_key_position()\n self.update()\n self.partition_graph_np()\n \n def reset_view_callback(self):\n self.scam.SetModelViewMatrix(self.look_view)#pango.AxisDirection.AxisY))\n\n def draw_text(self,position,text):\n # pos_text = [0,0,0]\n # name = 'Hello'\n # gl.glDisable(gl.GL_LIGHTING)\n # gl.glColor3f(0.0, 0.0, 0.0)\n gl.glRasterPos3f(*position)\n glut.glutBitmapString(glut.GLUT_BITMAP_HELVETICA_12,\n text.encode())\n # gl.glEnable(gl.GL_LIGHTING)\n \n def draw_vertex_key(self):\n for key, value in self.graph.key_node_dict.items():\n robot_id = self.multi_robot_tools.key2robot_id_g2o(key)\n if self.show_list[robot_id].Get():\n \n edge_color = self.color_list[robot_id]\n gl.glColor3f(edge_color[0]/255.0, edge_color[1]/255.0, edge_color[2]/255.0)\n\n edge_color = self.color_list[robot_id]\n\n if self.show_g2o_id.Get():\n self.draw_text(value,str(key))\n elif self.show_gtsam_id.Get():\n new_key = self.multi_robot_tools.id_g2o2gtsam(key)\n self.draw_text(value,str(new_key))","repo_name":"jiangpin-legend/g2o_tools","sub_path":"multi_viewer.py","file_name":"multi_viewer.py","file_ext":"py","file_size_in_byte":10742,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"}
+{"seq_id":"6893079862","text":"import json\nimport pandas as pd\nimport numpy as np\n\nfrom enum import Enum\nfrom typing import List\nfrom dataset_attributes import DataSetAtrributes\n\nimport warnings\n\nwarnings.filterwarnings('ignore')\n\n\nclass ImputerStrategy(Enum):\n MEAN = 'mean'\n MEDIAN = 'median'\n MODE = 'mode'\n CONSTANT = 'constant'\n REGRESSOR_MODEL = 'regressor_model'\n CLASSIFICATION_MODEL = 'clasification_model'\n\n\nclass DataBot:\n numeric_types: List[str] = ['int64', 'float64', 'datetime64']\n string_types: List[str] = ['object', 'category']\n\n def __init__(self,\n dataset=None,\n target_name=None,\n null_threshold=0.3,\n cardinal_threshold=0.3,\n project_path=None):\n self.dataset = dataset\n self.target = target_name\n self.null_threshold = null_threshold\n self.cardinal_threshold = cardinal_threshold\n self.project_path = project_path\n self.categorical_columns = []\n self.numeric_columns = []\n\n self.datasetAttributes = DataSetAtrributes(self.project_path)\n\n if target_name is not None:\n self.target_name = target_name\n self.target = self.dataset[self.target_name]\n self.features = self.dataset.drop([self.target_name], axis=1)\n else:\n self.features = dataset\n\n # Lambda for a series object that fill nulls with the mean.\n fill_mean = None\n # Lambda for a series object that fill nulls with the mode.\n fill_mode = None\n\n def scale_range(self, x):\n return (x - x.min(axis=0)) / (x.max(axis=0) - x.min(axis=0))\n\n def scale_log(self, x):\n return np.log(x + 1)\n\n impute_strategies = {\n ImputerStrategy.MEAN: fill_mean,\n ImputerStrategy.MODE: fill_mode\n }\n\n def impute(self, columns, impute_strategy):\n \"\"\"Impute selected columns (pd.Series) from self.features with the given strategy.\n\n Parameters\n ----------\n :param columns: list of columns names to impute.\n :param impute_strategy: Selected ImputerStrategy\n \"\"\"\n pass\n\n def one_hot_encode(self, col_name, categorical_values):\n \"\"\" Apply one hot encoding to the given column.\n\n :param col_name: Name of the column to one hot encode.\n :param categorical_values: Unique values from self.features[col_name]\n :return:\n \"\"\"\n pass\n\n def normalize(self, columns):\n \"\"\"Apply self.scale_range and self.scale_log to the given columns\n :param columns: list of columns names to normalize\n \"\"\"\n self.features[columns] = None\n self.features[columns] = None\n\n def remove_null_columns(self):\n \"\"\"Remove columns with a percentage of null values greater than the given threshold (self.null_threshold).\n \n \"\"\"\n pass\n\n def remove_high_cardinality_columns(self):\n \"\"\"Remove columns with a cardinality percentage greater than the given threshold (self.cardinal_threshold).\n\n \"\"\"\n pass\n\n def pre_process(self):\n \"\"\"Preprocess dataset features before being send to ML algorithm for training.\n \"\"\"\n # Implement this method with the given indications in the given order\n\n # Remove columns with null values above the threshold\n\n # Remove columns with cardinality above the threshold\n\n # Create a python list with the names of columns with numeric values.\n # Numeric columns have one of the types stored in the list self.numeric_types\n self.numeric_columns = None\n\n # Create a python list with the names of columns with string values.\n # Categorical columns have one of the types stored in the list self.string_types\n self.categorical_columns = None\n\n # Create a python list with the names of numeric columns with at least one null value.\n numeric_nulls = None\n\n # Create a python list with the names of categorical columns with at least one null value.\n categorical_nulls = None\n\n # Impute numerical columns with at least one null value.\n\n # Impute categorical columns with at least one null value.\n\n # These two lines gather information from the dataset for further use.\n self.datasetAttributes.set_column_values(self.categorical_columns, self.features)\n self.datasetAttributes.set_number_values(self.numeric_columns, self.features)\n\n # Apply one hot encoding to all categorical columns.\n\n # Normalize all numeric columns\n\n # This line store relevant information from the processed dataset for further use.\n self.datasetAttributes.save()\n\n def pre_process_prediction(self, parameters):\n \"\"\"Preprocess records from API calls before running predictions\n\n :param parameters: information from the processed dataset in the training stage.\n\n \"\"\"\n self.features.drop(parameters['removed_columns'], axis=1, inplace=True)\n\n for column in parameters['categorical_columns'].keys():\n categorical_values = parameters['categorical_columns'][column][\"values\"]\n self.one_hot_encode(column, categorical_values)\n\n for column in parameters['numeric_columns'].keys():\n n_min = parameters['numeric_columns'][column][\"min\"]\n n_max = parameters['numeric_columns'][column][\"max\"]\n self.features[column] = self.features[column].apply(lambda x: (x - n_min) / (n_max - n_min))\n self.features[column] = self.features[column].apply(lambda x: np.log(x + 1))\n\n def get_dataset(self):\n \"\"\"Returns a dataset with features and labels.\n\n :return: Dataset with features and labels.\n \"\"\"\n self.dataset = self.features\n self.dataset[self.target_name] = self.target\n return self.dataset\n","repo_name":"mrugeles/numpy-pandas-project","sub_path":"data_bot.py","file_name":"data_bot.py","file_ext":"py","file_size_in_byte":5831,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"}
+{"seq_id":"73345765207","text":"import json\nimport posixpath\n\nimport requests\nfrom werkzeug.exceptions import ServiceUnavailable\n\n\ndef _get_settings():\n from indico_ursh.plugin import UrshPlugin\n api_key = UrshPlugin.settings.get('api_key')\n api_host = UrshPlugin.settings.get('api_host')\n\n if not api_key or not api_host:\n raise ServiceUnavailable('Not configured')\n\n return api_key, api_host\n\n\ndef is_configured():\n \"\"\"Check whether the plugin is properly configured.\"\"\"\n from indico_ursh.plugin import UrshPlugin\n api_key = UrshPlugin.settings.get('api_key')\n api_host = UrshPlugin.settings.get('api_host')\n return bool(api_key and api_host)\n\n\ndef request_short_url(original_url):\n from indico_ursh.plugin import UrshPlugin\n api_key, api_host = _get_settings()\n headers = {'Authorization': f'Bearer {api_key}', 'Content-Type': 'application/json'}\n url = posixpath.join(api_host, 'api/urls/')\n\n response = requests.post(url, data=json.dumps({'url': original_url, 'allow_reuse': True}), headers=headers)\n response.raise_for_status()\n data = response.json()\n UrshPlugin.logger.info('Shortcut created: %s -> %s', data['shortcut'], original_url)\n return data['short_url']\n\n\ndef register_shortcut(original_url, shortcut, user):\n from indico_ursh.plugin import UrshPlugin\n api_key, api_host = _get_settings()\n headers = {'Authorization': f'Bearer {api_key}', 'Content-Type': 'application/json'}\n url = posixpath.join(api_host, 'api/urls', shortcut)\n data = {'url': original_url, 'allow_reuse': True, 'meta': {'indico.user': user.id}}\n\n response = requests.put(url, data=json.dumps(data), headers=headers)\n if not (400 <= response.status_code < 500):\n response.raise_for_status()\n\n data = response.json()\n if not data.get('error'):\n UrshPlugin.logger.info('Shortcut created: %s -> %s', data['shortcut'], original_url)\n return data\n\n\ndef strip_end(text, suffix):\n if not text.endswith(suffix):\n return text\n return text[:len(text) - len(suffix)]\n","repo_name":"indico/indico-plugins","sub_path":"ursh/indico_ursh/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2029,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"31"}
+{"seq_id":"41978863012","text":"from flask import Flask, request, render_template\nimport stories\nfrom flask_debugtoolbar import DebugToolbarExtension\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = \"secret\"\n\ndebug = DebugToolbarExtension(app)\n\n@app.route('/')\ndef home_page():\n story = stories.story.prompts\n return render_template(\"home.html\",story_prompts = story)\n\n@app.route('/story')\ndef story_page():\n answer_dict = {prompt : request.args[prompt] for prompt in stories.story.prompts}\n full_story = stories.story.generate(answer_dict)\n return render_template(\"story.html\",full_story = full_story)","repo_name":"FangedMob24/flask-madlibs","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"13404469821","text":"import logging\nimport time\n\nimport ldap\nimport pytest\nfrom lib389 import Entry\nfrom lib389._constants import *\nfrom lib389.properties import *\nfrom lib389.topologies import topology_st\nfrom lib389.utils import *\n\npytestmark = pytest.mark.tier2\n\nlog = logging.getLogger(__name__)\n\n\ndef test_ticket47560(topology_st):\n \"\"\"\n This test case does the following:\n SETUP\n - Create entry cn=group,SUFFIX\n - Create entry cn=member,SUFFIX\n - Update 'cn=member,SUFFIX' to add \"memberOf: cn=group,SUFFIX\"\n - Enable Memberof Plugins\n\n # Here the cn=member entry has a 'memberOf' but\n # cn=group entry does not contain 'cn=member' in its member\n\n TEST CASE\n - start the fixupmemberof task\n - read the cn=member entry\n - check 'memberOf is now empty\n\n TEARDOWN\n - Delete entry cn=group,SUFFIX\n - Delete entry cn=member,SUFFIX\n - Disable Memberof Plugins\n \"\"\"\n\n def _enable_disable_mbo(value):\n \"\"\"\n Enable or disable mbo plugin depending on 'value' ('on'/'off')\n \"\"\"\n # enable/disable the mbo plugin\n if value == 'on':\n topology_st.standalone.plugins.enable(name=PLUGIN_MEMBER_OF)\n else:\n topology_st.standalone.plugins.disable(name=PLUGIN_MEMBER_OF)\n\n log.debug(\"-------------> _enable_disable_mbo(%s)\" % value)\n\n topology_st.standalone.stop(timeout=120)\n time.sleep(1)\n topology_st.standalone.start(timeout=120)\n time.sleep(3)\n\n # need to reopen a connection toward the instance\n topology_st.standalone.open()\n\n def _test_ticket47560_setup():\n \"\"\"\n - Create entry cn=group,SUFFIX\n - Create entry cn=member,SUFFIX\n - Update 'cn=member,SUFFIX' to add \"memberOf: cn=group,SUFFIX\"\n - Enable Memberof Plugins\n \"\"\"\n log.debug(\"-------- > _test_ticket47560_setup\\n\")\n\n #\n # By default the memberof plugin is disabled create\n # - create a group entry\n # - create a member entry\n # - set the member entry as memberof the group entry\n #\n entry = Entry(group_DN)\n entry.setValues('objectclass', 'top', 'groupOfNames', 'inetUser')\n entry.setValues('cn', 'group')\n try:\n topology_st.standalone.add_s(entry)\n except ldap.ALREADY_EXISTS:\n log.debug(\"Entry %s already exists\" % (group_DN))\n\n entry = Entry(member_DN)\n entry.setValues('objectclass', 'top', 'person', 'organizationalPerson', 'inetorgperson', 'inetUser')\n entry.setValues('uid', 'member')\n entry.setValues('cn', 'member')\n entry.setValues('sn', 'member')\n try:\n topology_st.standalone.add_s(entry)\n except ldap.ALREADY_EXISTS:\n log.debug(\"Entry %s already exists\" % (member_DN))\n\n replace = [(ldap.MOD_REPLACE, 'memberof', ensure_bytes(group_DN))]\n topology_st.standalone.modify_s(member_DN, replace)\n\n #\n # enable the memberof plugin and restart the instance\n #\n _enable_disable_mbo('on')\n\n #\n # check memberof attribute is still present\n #\n filt = 'uid=member'\n ents = topology_st.standalone.search_s(member_DN, ldap.SCOPE_BASE, filt)\n assert len(ents) == 1\n ent = ents[0]\n # print ent\n value = ensure_str(ent.getValue('memberof'))\n # print \"memberof: %s\" % (value)\n assert value == group_DN\n\n def _test_ticket47560_teardown():\n \"\"\"\n - Delete entry cn=group,SUFFIX\n - Delete entry cn=member,SUFFIX\n - Disable Memberof Plugins\n \"\"\"\n log.debug(\"-------- > _test_ticket47560_teardown\\n\")\n # remove the entries group_DN and member_DN\n try:\n topology_st.standalone.delete_s(group_DN)\n except:\n log.warning(\"Entry %s fail to delete\" % (group_DN))\n try:\n topology_st.standalone.delete_s(member_DN)\n except:\n log.warning(\"Entry %s fail to delete\" % (member_DN))\n #\n # disable the memberof plugin and restart the instance\n #\n _enable_disable_mbo('off')\n\n group_DN = \"cn=group,%s\" % (SUFFIX)\n member_DN = \"uid=member,%s\" % (SUFFIX)\n\n #\n # Initialize the test case\n #\n _test_ticket47560_setup()\n\n #\n # start the test\n # - start the fixup task\n # - check the entry is fixed (no longer memberof the group)\n #\n log.debug(\"-------- > Start ticket tests\\n\")\n\n filt = 'uid=member'\n ents = topology_st.standalone.search_s(member_DN, ldap.SCOPE_BASE, filt)\n assert len(ents) == 1\n ent = ents[0]\n log.debug(\"Unfixed entry %r\\n\" % ent)\n\n # run the fixup task\n topology_st.standalone.tasks.fixupMemberOf(suffix=SUFFIX, args={TASK_WAIT: True})\n\n ents = topology_st.standalone.search_s(member_DN, ldap.SCOPE_BASE, filt)\n assert len(ents) == 1\n ent = ents[0]\n log.debug(\"Fixed entry %r\\n\" % ent)\n\n if ensure_str(ent.getValue('memberof')) == group_DN:\n log.warning(\"Error the fixupMemberOf did not fix %s\" % (member_DN))\n result_successful = False\n else:\n result_successful = True\n\n #\n # cleanup up the test case\n #\n _test_ticket47560_teardown()\n\n assert result_successful is True\n\n log.info('Testcase PASSED')\n\n\nif __name__ == '__main__':\n # Run isolated\n # -s for DEBUG mode\n CURRENT_FILE = os.path.realpath(__file__)\n pytest.main(\"-s %s\" % CURRENT_FILE)\n","repo_name":"389ds/389-ds-base","sub_path":"dirsrvtests/tests/tickets/ticket47560_test.py","file_name":"ticket47560_test.py","file_ext":"py","file_size_in_byte":5595,"program_lang":"python","lang":"en","doc_type":"code","stars":162,"dataset":"github-code","pt":"31"}
+{"seq_id":"11916068612","text":"import json\nimport os\nimport subprocess\nimport sys\n\nimport pytest\nfrom click.testing import CliRunner\nfrom click_odoo import OdooEnvironment, odoo, odoo_bin\n\nfrom click_odoo_contrib.update import _load_installed_checksums, main\n\n# this extends the addons path of the odoodb and odoocfg fixtures\n# we use the v1 dir, so the first install work (since it's only since version 12\n# that Odoo updates the modules list before installing)\ntest_addons_dir = os.path.join(os.path.dirname(__file__), \"data\", \"test_update\", \"v1\")\n\n\ndef _addons_dir(v):\n return os.path.join(os.path.dirname(__file__), \"data\", \"test_update\", v)\n\n\ndef _addons_path(v):\n return \",\".join(\n [\n os.path.join(odoo.__path__[0], \"addons\"),\n os.path.join(odoo.__path__[0], \"..\", \"addons\"),\n _addons_dir(v),\n ]\n )\n\n\ndef _check_expected(odoodb, v):\n with OdooEnvironment(database=odoodb) as env:\n with open(os.path.join(_addons_dir(v), \"expected.json\")) as f:\n expected = json.load(f)\n for addon_name, expected_data in expected.items():\n env.cr.execute(\n \"SELECT state, latest_version FROM ir_module_module WHERE name=%s\",\n (addon_name,),\n )\n state, version = env.cr.fetchone()\n expected_state = expected_data.get(\"state\")\n if expected_state:\n assert state == expected_state, addon_name\n expected_version = expected_data.get(\"version\")\n if expected_version:\n assert version.split(\".\")[2:] == expected_version.split(\".\"), addon_name\n\n\ndef _install_one(odoodb, v):\n cmd = [\n odoo_bin,\n \"--addons-path\",\n _addons_path(\"v1\"),\n \"-d\",\n odoodb,\n \"-i\",\n \"addon_app\",\n \"--stop-after-init\",\n ]\n subprocess.check_call(cmd)\n\n\ndef _update_one(odoodb, v, ignore_addons=None, ignore_core_addons=False):\n cmd = [\n sys.executable,\n \"-m\",\n \"click_odoo_contrib.update\",\n \"--addons-path\",\n _addons_path(v),\n \"-d\",\n odoodb,\n ]\n if ignore_addons:\n cmd.extend([\"--ignore-addons\", ignore_addons])\n if ignore_core_addons:\n cmd.append(\"--ignore-core-addons\")\n subprocess.check_call(cmd)\n\n\ndef _update_list(odoodb, v):\n cmd = [\n sys.executable,\n \"-m\",\n \"click_odoo_contrib.update\",\n \"--addons-path\",\n _addons_path(v),\n \"-d\",\n odoodb,\n \"--list-only\",\n ]\n subprocess.check_call(cmd)\n\n\ndef test_update(odoodb):\n _install_one(odoodb, \"v1\")\n _check_expected(odoodb, \"v1\")\n # With --list-only option update shouldn't be performed:\n _update_list(odoodb, \"v2\")\n _check_expected(odoodb, \"v1\")\n # With --ignore-addons addon_app, update should not be performed\n _update_one(odoodb, \"v1\", ignore_addons=\"addon_app\")\n _check_expected(odoodb, \"v1\")\n # Default update should:\n _update_one(odoodb, \"v2\")\n _check_expected(odoodb, \"v2\")\n _update_one(odoodb, \"v3\")\n _check_expected(odoodb, \"v3\")\n with OdooEnvironment(odoodb) as env:\n checksums = _load_installed_checksums(env.cr)\n print(checksums)\n assert \"base\" in checksums\n assert checksums.get(\"addon_app\") == \"bb1ff827fd6084e69180557c3183989100ddb62b\"\n assert checksums.get(\"addon_d1\") == \"ff46eefbe846e1a46ff3de74e117fd285b72f298\"\n assert checksums.get(\"addon_d2\") == \"edf58645e2e55a2d282320206f73df09a746a4ab\"\n # 3.1 sets addons_d1 as uninstallable: it stays installed\n _update_one(odoodb, \"v3.1\")\n _check_expected(odoodb, \"v3.1\")\n _update_one(odoodb, \"v4\")\n _check_expected(odoodb, \"v4\")\n _update_one(odoodb, \"v5\")\n _check_expected(odoodb, \"v5\")\n _update_one(odoodb, \"v6\", ignore_core_addons=True)\n _check_expected(odoodb, \"v6\")\n with OdooEnvironment(odoodb) as env:\n checksums = _load_installed_checksums(env.cr)\n assert \"base\" not in checksums # because ignore_Core_addons=True\n with pytest.raises(subprocess.CalledProcessError):\n _update_one(odoodb, \"v7\")\n if odoo.release.version_info >= (12, 0):\n # Odoo >= 12 does -u in a transaction\n _check_expected(odoodb, \"v6\")\n\n\ndef test_update_db_not_exists():\n runner = CliRunner()\n result = runner.invoke(main, [\"-d\", \"dbthatdoesnotexist\"])\n assert result.exit_code != 0\n runner = CliRunner()\n result = runner.invoke(main, [\"--if-exists\", \"-d\", \"dbthatdoesnotexist\"])\n assert result.exit_code == 0\n\n\ndef test_update_i18n_overwrite(odoodb):\n cmd = [\n sys.executable,\n \"-m\",\n \"click_odoo_contrib.update\",\n \"--i18n-overwrite\",\n \"-d\",\n odoodb,\n ]\n subprocess.check_call(cmd)\n # TODO how to test i18n-overwrite was effectively applied?\n\n\ndef test_parallel_watcher(odoodb):\n # Test that the parallel updater does not disturb normal operation\n cmd = [\n sys.executable,\n \"-m\",\n \"click_odoo_contrib.update\",\n \"--watcher-max-seconds\",\n \"30\",\n \"-d\",\n odoodb,\n ]\n subprocess.check_call(cmd)\n # TODO Test an actual lock\n","repo_name":"acsone/click-odoo-contrib","sub_path":"tests/test_update.py","file_name":"test_update.py","file_ext":"py","file_size_in_byte":5147,"program_lang":"python","lang":"en","doc_type":"code","stars":83,"dataset":"github-code","pt":"31"}
+{"seq_id":"21423133855","text":"import datetime\nimport time\nimport os\nimport sys, getopt\nimport random\nfrom collections import defaultdict\nimport pandas as pd\nimport numpy as np\nfrom multiprocessing import Process\nfrom functools import reduce\nimport struct\n\nFOLDER_NAME_BASE ='/home/pensees/feature_compare/card_72_csv'\n#FOLDER_NAME_BASE ='/home/pensees/feature_compare/capture_csv_bak'\nFOLDER_NAME_CMP ='/home/pensees/feature_compare/capture_csv_bak'\nFILE_VET_GT='l2_results0.npy'\nALL = False\n# CSV = False\nCSV = True\nUINT8 = False\n# UINT8 = True\n\n\n\ndef load_vec_csv(file_name):\n if CSV==True:\n data = pd.read_csv(file_name,header=None)\n data = np.array(data)\n else:\n data = np.load(file_name)\n if UINT8==True:\n data = (data+0.5)/255\n vec_list = []\n nb = len(data)\n for i in range(nb):\n vec_list.append(data[i].tolist())\n return vec_list\n\ndef calInnerDistance(vec1,vec2):\n vec1 = np.array(vec1)\n vec2 = np.array(vec2)\n dist = np.inner(vec1,vec2)\n return dist\n\ndef compare(base,v_cmp):\n base_file = FOLDER_NAME_BASE + '/' + base +\".csv\"\n print(base_file)\n vec1 = load_vec_csv(base_file)\n if v_cmp!=None:\n v_cmp_file = FOLDER_NAME_CMP + '/' + v_cmp +\".csv\"\n print(v_cmp_file)\n vec2 = load_vec_csv(v_cmp_file)\n dist = calInnerDistance(vec1,vec2)\n print(dist[0][0])\n return\n data = np.load(FILE_VET_GT)\n vec_list = data.tolist()\n print(len(vec_list))\n for vec2 in vec_list:\n dist = calInnerDistance(vec1,vec2)\n print(dist[0])\n \n\n\ndef main():\n try:\n opts, args = getopt.getopt(\n sys.argv[1:],\n \"hb:c:p\",\n [\"help\", \"base=\", \"cmp=\", \"compare\"],\n )\n except getopt.GetoptError:\n print(\"Usage: test.py -q -k -t
-l -s\")\n sys.exit(2)\n base = None\n v_cmp = None\n for opt_name, opt_value in opts:\n if opt_name in (\"-h\", \"--help\"):\n print(\"test.py -q -k -t
-l -s\")\n sys.exit()\n elif opt_name in (\"-b\", \"--base\"):\n base = opt_value\n elif opt_name in (\"-c\", \"--cmp\"):\n v_cmp = opt_value\n elif opt_name in (\"-p\", \"--compare\"): #test.py -q -k -l\n compare(base,v_cmp)\n sys.exit()\nif __name__ == '__main__':\n main()\n","repo_name":"shiyu22/source_code","sub_path":"csy/py/vec_compare.py","file_name":"vec_compare.py","file_ext":"py","file_size_in_byte":2360,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"43099858555","text":"import aht20\nimport bmp280\nimport sys\n\n\nbmp280 = bmp280.BMP280(0x77, 1)\nbmp280.init()\n\naht20 = aht20.AHT20(0x38, 1)\naht20.init()\n\nwhile True:\n _ = sys.stdin.readline()\n aht20_humidity, aht20_temperature = aht20.measure()\n line = \"sensors,name=aht20 temperature=%.2f,humidity=%.2f\\n\"\n sys.stdout.write(line % (aht20_temperature, aht20_humidity))\n bmp280_pressure, bmp280_temperature = bmp280.measure()\n line = \"sensors,name=bmp280 temperature=%.2f,pressure=%.2f\\n\"\n sys.stdout.write(line % (bmp280_temperature, bmp280_pressure))\n sys.stdout.flush()\n","repo_name":"marcv81-test/sensors-stats","sub_path":"sensors_stats.py","file_name":"sensors_stats.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"3990330532","text":"\"\"\"\n* Filtrando a lista, aplico filter com função lambda verificando se o elemento é par. Caso True, adiciona à lista.\n\"\"\"\nlista = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n# com lambda\nprint(list(filter(lambda x: x % 2 == 0, lista)))\n\n\ndef par(num):\n if num % 2 == 0:\n return True\n\n\n# com função\nprint(list(filter(par, lista)))\n","repo_name":"MarcosAllysson/python-do-basico-ao-avancado","sub_path":"Funções embutidas/filter.py","file_name":"filter.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"}
+{"seq_id":"27361088104","text":"# 1. Написать генератор нечётных чисел от 1 до n (включительно), используя ключевое слово yield\n# -------------Решение----------------\n\n# Создаем функцию с генератором\ndef odd_nums(max_num):\n for num in range(1, max_num + 1, 2):\n yield num\n\n\n# Проверяем\nodd_to_15 = odd_nums(15)\nprint(next(odd_to_15))\nprint(next(odd_to_15))\n\n\n# 2. * (вместо 1) Решить задачу генерации нечётных чисел от 1 до n (включительно), не используя ключевое слово yield.\n# -------------Решение----------------\n# Создаем функцию с генератором\ndef gen(max_num):\n return (i for i in range(1, max_num + 1, 2))\n\n\n# Проверяем\ngen_to_15 = gen(15)\nprint(next(gen_to_15))\nprint(next(gen_to_15))\n","repo_name":"AADogov/GeekBrainsLesson5","sub_path":"GeekBrainsLesson_5_1_and_5_2.py","file_name":"GeekBrainsLesson_5_1_and_5_2.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"37523986122","text":"import os\nimport json\nimport base64\nimport numpy as np\nfrom plyfile import PlyData\nimport io\nimport cv2\nimport matplotlib.pyplot as plt\n\ndrawing = False\ntop_left_pt, bottom_right_pt = (-1, -1), (-1, -1)\n\ndef draw_rectangle(event, x, y, flags, param):\n global drawing, top_left_pt, bottom_right_pt\n if event == cv2.EVENT_LBUTTONDOWN:\n drawing = True\n top_left_pt = (x, y)\n elif event == cv2.EVENT_LBUTTONUP:\n drawing = False\n bottom_right_pt = (x, y)\n cv2.rectangle(param, top_left_pt, bottom_right_pt, (0, 255, 0), 2)\n cv2.imshow('Draw Bounding Box', param)\n\ndef process_gltf_file(file_path, person_count, gltf_count, save_folder):\n\n try:\n with open(file_path, 'r') as f:\n gltf_data = json.load(f)\n except Exception as e:\n print(f\"Error loading GLTF: {e}\")\n return\n\n try:\n data_uri = gltf_data[\"meshes\"][0][\"extras\"][\"dataURI\"]\n except (KeyError, IndexError) as e:\n print(f\"Couldn't find the necessary data in the GLTF file: {e}\")\n return\n\n base64_data = data_uri.split(\",\")[-1]\n decoded_data = base64.b64decode(base64_data)\n buffer = io.BytesIO(decoded_data)\n\n try:\n plydata = PlyData.read(buffer)\n except Exception as e:\n print(f\"Error reading PLY data: {e}\")\n return\n\n \n #print(plydata)\n import numpy as np\n\n #projection matrix\n P = np.array([[1052.667867276341, 0, 962.4130834944134, 0],\n [0, 1052.020917785721, 536.2206151001486, 0],\n [0, 0, 1, 0]])\n\n scale_factor = 1000\n downsample_factor = 1000\n\n if 'vertex' in plydata:\n\n\n vertex_element = plydata['vertex']\n x = vertex_element['x']\n y = vertex_element['y']\n z = vertex_element['z']\n\n points_3d = np.array([x, y, z, np.ones_like(x)])\n points_2d_hom = np.dot(P, points_3d)\n points_2d = points_2d_hom[:2, :] / points_2d_hom[2, :]\n\n x_proj = points_2d[0, :]\n y_proj = points_2d[1, :]\n\n # Round to reduce the range\n x_scaled = np.round(x_proj * scale_factor).astype(int)\n y_scaled = np.round(y_proj * scale_factor).astype(int)\n\n x_scaled = (x_scaled // downsample_factor)\n y_scaled = (y_scaled // downsample_factor)\n\n x_min, x_max = x_scaled.min(), x_scaled.max()\n y_min, y_max = y_scaled.min(), y_scaled.max()\n\n depth = np.zeros((y_max - y_min + 1, x_max - x_min + 1), dtype=np.float32)\n\n for i in range(len(x)):\n x_idx = x_scaled[i] - x_min\n y_idx = y_scaled[i] - y_min\n depth[y_idx, x_idx] = z[i]\n\n print(\"Depth array created with shape:\", depth.shape)\n\n \n original_depth = np.copy(depth)\n original_depth = np.flipud(original_depth)\n depth_normalized = ((depth - np.nanmin(depth)) / (np.nanmax(depth) - np.nanmin(depth))) * 255\n depth_normalized = depth_normalized.astype(np.uint8)\n depth_normalized = np.flipud(depth_normalized)\n depth_colored = plt.cm.magma(depth_normalized)\n \n depth_colored = (depth_colored[:, :, :3] * 255).astype(np.uint8)\n depth_colored = cv2.cvtColor(depth_colored, cv2.COLOR_RGB2BGR)\n clone = depth_colored.copy()\n cv2.namedWindow('Draw Bounding Box', cv2.WINDOW_NORMAL)\n cv2.resizeWindow('Draw Bounding Box', 800, 600)\n cv2.setMouseCallback('Draw Bounding Box', draw_rectangle, clone)\n # clone = depth_normalized.copy()\n # cv2.namedWindow('Draw Bounding Box', cv2.WINDOW_NORMAL)\n # cv2.resizeWindow('Draw Bounding Box', 800, 600)\n # cv2.setMouseCallback('Draw Bounding Box', draw_rectangle, clone)\n\n while True:\n cv2.imshow('Draw Bounding Box', clone)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n x1, y1 = top_left_pt\n x2, y2 = bottom_right_pt\n w = x2 - x1\n h = y2 - y1\n face_region_depth = original_depth[y1:y1+h, x1:x1+w]\n \n # cropped_original = original_depth[y1:y2, x1:x2]\n # cropped_normalized = normalized_depth[y1:y2, x1:x2]\n\n while True: \n plt.imshow(face_region_depth, cmap='magma')\n plt.title(\"Cropped Depth Face Image\")\n plt.show()\n\n user_input = input(\"Are you satisfied with the bounding box? (y)/n): \")\n if user_input.lower() == 'y':\n break \n elif user_input.lower() == 'n':\n # clone = depth_normalized.copy()\n # cv2.namedWindow('Draw Bounding Box', cv2.WINDOW_NORMAL)\n # cv2.resizeWindow('Draw Bounding Box', 800, 600)\n # cv2.setMouseCallback('Draw Bounding Box', draw_rectangle, clone)\n depth_colored = plt.cm.magma(depth_normalized)\n depth_colored = (depth_colored[:, :, :3] * 255).astype(np.uint8)\n depth_colored = cv2.cvtColor(depth_colored, cv2.COLOR_RGB2BGR)\n clone = depth_colored.copy()\n cv2.namedWindow('Draw Bounding Box', cv2.WINDOW_NORMAL)\n cv2.resizeWindow('Draw Bounding Box', 800, 600)\n cv2.setMouseCallback('Draw Bounding Box', draw_rectangle, clone)\n\n while True:\n cv2.imshow('Draw Bounding Box', clone)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n x1, y1 = top_left_pt\n x2, y2 = bottom_right_pt\n w = x2 - x1\n h = y2 - y1\n face_region_depth = original_depth[y1:y1+h, x1:x1+w]\n\n # #Display the normalized depth image using OpenCV\n # cv2.imshow('Depth Image', depth_normalized)\n # cv2.waitKey(0)\n # cv2.destroyAllWindows()\n\n print(face_region_depth)\n depth_image_folder = os.path.join(save_folder, str(person_count).zfill(3))\n depth_numpy_folder = os.path.join(save_folder, str(person_count).zfill(3))\n if not os.path.exists(depth_image_folder):\n os.makedirs(depth_image_folder)\n\n depth_image_path = os.path.join(depth_image_folder, f\"{str(person_count).zfill(3)}_{str(gltf_count).zfill(2)}_depth_image.png\")\n plt.imsave(depth_image_path, face_region_depth, cmap='magma')\n print(depth_image_path)\n if not os.path.exists(depth_numpy_folder):\n os.makedirs(depth_numpy_folder)\n\n depth_numpy_path = os.path.join(depth_numpy_folder, f\"{str(person_count).zfill(3)}_{str(gltf_count).zfill(2)}_depth_data.npy\")\n np.save(depth_numpy_path, face_region_depth)\n\n\nif __name__ == \"__main__\":\n root_folder = \"new_entries/test\" \n save_folder = \"new_entries/dataset_numpy_test\" \n\n for person_folder in sorted(os.listdir(root_folder)):\n person_path = os.path.join(root_folder, person_folder)\n if os.path.isdir(person_path):\n person_count = person_folder\n\n for gltf_file in sorted(os.listdir(person_path)):\n if gltf_file.endswith('.gltf'):\n gltf_count = gltf_file.split('.')[0]\n file_path = os.path.join(person_path, gltf_file)\n process_gltf_file(file_path, person_count, gltf_count, save_folder)","repo_name":"aliagha135/depth_face_recognition","sub_path":"Gltf/bounding_box_2.py","file_name":"bounding_box_2.py","file_ext":"py","file_size_in_byte":7078,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"39024772173","text":"from discord.ext import commands\nimport discord\nimport traceback\n\nfrom utils import template\nimport utils.errors as errors\n\n\nclass Error(commands.Cog):\n \"\"\"Handles errors related to the bot.\"\"\"\n\n def __init__(self, bot):\n self.bot = bot\n\n @commands.Cog.listener()\n async def on_command_error(self, ctx, error):\n if isinstance(error, (discord.ext.commands.errors.CommandNotFound, discord.errors.Forbidden)):\n return\n if isinstance(error, commands.CheckFailure):\n return await ctx.send(\n embed=template.error('You don\\'t have permission to use this command'),\n reference=ctx.message\n )\n try:\n if isinstance(error.original, errors.CustomError):\n return await ctx.send(\n embed=error.original.embed,\n reference=ctx.message\n )\n except AttributeError:\n pass\n if isinstance(error, (commands.errors.MissingRequiredArgument, errors.MissingArgument)):\n msg = str(error) if str(error) else 'Missing required argument'\n await ctx.send(embed=template.error(msg))\n tb = traceback.format_exception(type(error), error, error.__traceback__)\n tb_str = ''.join(tb[:-1]) + f'\\n{tb[-1]}'\n message = await self.bot.owner.send(embed=template.error(f'```{tb_str}```', ctx.message.jump_url))\n await ctx.channel.send(embed=template.error('Internal Error, report submitted.', message.jump_url))\n\n\nasync def setup(bot):\n await bot.wait_until_ready()\n await bot.add_cog(Error(bot))\n","repo_name":"RNG21/warframe-giveaways","sub_path":"cogs/errorhandle.py","file_name":"errorhandle.py","file_ext":"py","file_size_in_byte":1615,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"}
+{"seq_id":"36897423332","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport abc\nimport enum # pylint: disable=g-bad-import-order\nimport itertools\nimport functools\nimport os\nimport six\n\nfrom tensorflow.core.framework import attr_value_pb2\nfrom tensorflow.core.framework import variable_pb2\nfrom tensorflow.core.framework.embedding import config_pb2\nfrom tensorflow.python import pywrap_tensorflow\nfrom tensorflow.python.compat import compat as fwd_compat\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.lib.io import file_io\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import gen_array_ops\nfrom tensorflow.python.ops import gen_state_ops\nfrom tensorflow.python.ops import gen_math_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import state_ops\nfrom tensorflow.python.ops import gen_kv_variable_ops\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.training.tracking import base as trackable\nfrom tensorflow.python.util import compat\nfrom tensorflow.python.util import object_identity\nfrom tensorflow.python.util import tf_should_use\nfrom tensorflow.python.util.deprecation import deprecated\nfrom tensorflow.python.util.tf_export import tf_export\n\n\ndef default_variable_creator(_, **kwds):\n del kwds\n raise NotImplementedError(\"variable_scope needs to be imported\")\n\n\ndef default_variable_creator_v2(_, **kwds):\n del kwds\n raise NotImplementedError(\"variable_scope needs to be imported\")\n\n\ndef _make_getter(captured_getter, captured_previous):\n \"\"\"To avoid capturing loop variables.\"\"\"\n\n def getter(**kwargs):\n return captured_getter(captured_previous, **kwargs)\n\n return getter\n\n\n@tf_export(\"VariableSynchronization\")\nclass VariableSynchronization(enum.Enum):\n \"\"\"Indicates when a distributed variable will be synced.\n\n * `AUTO`: Indicates that the synchronization will be determined by the current\n `DistributionStrategy` (eg. With `MirroredStrategy` this would be\n `ON_WRITE`).\n * `NONE`: Indicates that there will only be one copy of the variable, so\n there is no need to sync.\n * `ON_WRITE`: Indicates that the variable will be updated across devices\n every time it is written.\n * `ON_READ`: Indicates that the variable will be aggregated across devices\n when it is read (eg. when checkpointing or when evaluating an op that uses\n the variable).\n \"\"\"\n AUTO = 0\n NONE = 1\n ON_WRITE = 2\n ON_READ = 3\n\n\n# LINT.IfChange\n@tf_export(\"VariableAggregation\", v1=[])\nclass VariableAggregationV2(enum.Enum):\n \"\"\"Indicates how a distributed variable will be aggregated.\n\n `tf.distribute.Strategy` distributes a model by making multiple copies\n (called \"replicas\") acting data-parallel on different elements of the input\n batch. When performing some variable-update operation, say\n `var.assign_add(x)`, in a model, we need to resolve how to combine the\n different values for `x` computed in the different replicas.\n\n * `NONE`: This is the default, giving an error if you use a\n variable-update operation with multiple replicas.\n * `SUM`: Add the updates across replicas.\n * `MEAN`: Take the arithmetic mean (\"average\") of the updates across replicas.\n * `ONLY_FIRST_REPLICA`: This is for when every replica is performing the same\n update, but we only want to perform the update once. Used, e.g., for the\n global step counter.\n \"\"\"\n NONE = 0\n SUM = 1\n MEAN = 2\n ONLY_FIRST_REPLICA = 3\n\n def __hash__(self):\n return hash(self.value)\n\n def __eq__(self, other):\n if self is other:\n return True\n elif isinstance(other, VariableAggregation):\n return int(self.value) == int(other.value)\n else:\n return False\n\n\n@tf_export(v1=[\"VariableAggregation\"])\nclass VariableAggregation(enum.Enum):\n NONE = 0\n SUM = 1\n MEAN = 2\n ONLY_FIRST_REPLICA = 3\n ONLY_FIRST_TOWER = 3 # DEPRECATED\n\n def __hash__(self):\n return hash(self.value)\n\n\n# LINT.ThenChange(//tensorflow/core/framework/variable.proto)\n#\n# Note that we are currently relying on the integer values of the Python enums\n# matching the integer values of the proto enums.\n\nVariableAggregation.__doc__ = (\n VariableAggregationV2.__doc__ +\n \"* `ONLY_FIRST_TOWER`: Deprecated alias for `ONLY_FIRST_REPLICA`.\\n \")\n\n\ndef validate_synchronization_aggregation_trainable(synchronization, aggregation,\n trainable, name):\n \"\"\"Given user-provided variable properties, sets defaults and validates.\"\"\"\n if aggregation is None:\n aggregation = VariableAggregation.NONE\n else:\n if not isinstance(aggregation,\n (VariableAggregation, VariableAggregationV2)):\n try:\n aggregation = VariableAggregationV2(aggregation)\n except ValueError:\n raise ValueError(\n \"Invalid variable aggregation mode: {} for variable: {}\".format(\n aggregation, name))\n if synchronization is None:\n synchronization = VariableSynchronization.AUTO\n else:\n try:\n synchronization = VariableSynchronization(synchronization)\n except ValueError:\n raise ValueError(\n \"Invalid variable synchronization mode: {} for variable: {}\".format(\n synchronization, name))\n if trainable is None:\n trainable = synchronization != VariableSynchronization.ON_READ\n return synchronization, aggregation, trainable\n\n@tf_export(v1=[\"InitializerOption\"])\nclass InitializerOption(object):\n def __init__(self,\n initializer = None,\n default_value_dim = 4096,\n default_value_no_permission = .0):\n self.initializer = initializer\n self.default_value_dim = default_value_dim\n self.default_value_no_permission = default_value_no_permission\n if default_value_dim <=0:\n print(\"default value dim must larger than 1, the default value dim is set to default 4096.\")\n default_value_dim = 4096\n \nclass MultihashOption(object):\n def __init__(self,\n num_of_partitions = None,\n strategy=\"\",\n operation=\"\",\n size = []):\n self.num_of_partitions = num_of_partitions\n self.strategy = strategy\n self.operation = operation\n self.size = size\n\n@tf_export(v1=[\"GlobalStepEvict\"])\nclass GlobalStepEvict(object):\n def __init__(self,\n steps_to_live = None):\n self.steps_to_live = steps_to_live\n\n@tf_export(v1=[\"L2WeightEvict\"])\nclass L2WeightEvict(object):\n def __init__(self,\n l2_weight_threshold = -1.0):\n self.l2_weight_threshold = l2_weight_threshold\n if l2_weight_threshold <= 0 and l2_weight_threshold != -1.0:\n logging.warning(\"l2_weight_threshold is invalid, l2_weight-based eviction is disabled\")\n\n@tf_export(v1=[\"CheckpointOption\"])\nclass CheckpointOption(object):\n def __init__(self,\n ckpt_to_load_from=None,\n tensor_name_in_ckpt=None,\n always_load_from_specific_ckpt=False,\n init_data_source=None):\n self.ckpt_to_load_from = ckpt_to_load_from\n self.tensor_name_in_ckpt = tensor_name_in_ckpt\n self.always_load_from_specific_ckpt = always_load_from_specific_ckpt\n self.init_data_source = init_data_source\n\n@tf_export(v1=[\"StorageOption\"])\nclass StorageOption(object):\n def __init__(self,\n storage_type=None,\n storage_path=None,\n storage_size=[1024*1024*1024],\n cache_strategy = config_pb2.CacheStrategy.LFU,\n layout=None):\n self.storage_type = storage_type\n self.storage_path = storage_path\n self.storage_size = storage_size\n self.cache_strategy = cache_strategy\n self.layout = layout\n if not isinstance(storage_size, list):\n raise ValueError(\"storage_size should be list type\")\n if len(storage_size) < 4:\n for i in range(len(storage_size), 4):\n storage_size.append(1024*1024*1024)\n if storage_path is not None:\n if storage_type is None:\n raise ValueError(\"storage_type musnt'be None when storage_path is set\")\n else:\n if not file_io.file_exists(storage_path):\n file_io.recursive_create_dir(storage_path)\n else:\n if storage_type is not None and storage_type in [config_pb2.StorageType.LEVELDB,\n config_pb2.StorageType.SSDHASH,\n config_pb2.StorageType.DRAM_SSDHASH,\n config_pb2.StorageType.DRAM_LEVELDB]:\n raise ValueError(\"storage_path musnt'be None when storage_type is set\")\n\n@tf_export(v1=[\"EmbeddingVariableOption\"])\nclass EmbeddingVariableOption(object):\n def __init__(self,\n ht_type=\"\",\n ht_partition_num = 1000,\n evict_option = None,\n ckpt = None,\n filter_option = None,\n storage_option = StorageOption(),\n init_option = InitializerOption()):\n self.ht_type = ht_type\n self.ht_partition_num = ht_partition_num\n self.evict = evict_option\n self.ckpt = ckpt\n self.filter_strategy = filter_option\n self.storage_option = storage_option\n self.init = init_option\n \n@tf_export(v1=[\"CounterFilter\"])\nclass CounterFilter(object):\n def __init__(self, filter_freq = 0):\n self.filter_freq = filter_freq\n\n@tf_export(v1=[\"CBFFilter\"])\nclass CBFFilter(object):\n def __init__(self,\n filter_freq = 0,\n max_element_size = 0,\n false_positive_probability = -1.0,\n counter_type = dtypes.uint64):\n if false_positive_probability != -1.0:\n if false_positive_probability <= 0.0:\n raise ValueError(\"false_positive_probablity must larger than 0\")\n else:\n if max_element_size <= 0:\n raise ValueError(\"max_element_size must larger than 0 when false_positive_probability is not -1.0\")\n else:\n if max_element_size != 0:\n raise ValueError(\"max_element_size can't be set when false_probability is -1.0\")\n self.max_element_size = max_element_size\n self.false_positive_probability = false_positive_probability\n self.counter_type = counter_type\n self.filter_freq = filter_freq\n\nclass EmbeddingVariableConfig(object):\n def __init__(self,\n steps_to_live=None, steps_to_live_l2reg=None,\n l2reg_theta=None, l2reg_lambda=None,\n l2_weight_threshold = -1.0,\n ht_type=None,\n filter_strategy=None,\n ckpt_to_load_from=None,\n tensor_name_in_ckpt=None,\n always_load_from_specific_ckpt=False,\n init_data_source=None,\n handle_name=None,\n emb_index=None,\n slot_index=None,\n block_num=None,\n primary=None,\n slot_num=None,\n storage_type=config_pb2.StorageType.DRAM,\n storage_path=None,\n storage_size=None,\n storage_cache_strategy=config_pb2.CacheStrategy.LFU,\n layout=None,\n default_value_dim=4096,\n default_value_no_permission=.0):\n self.steps_to_live = steps_to_live\n self.steps_to_live_l2reg = steps_to_live_l2reg\n self.l2reg_theta = l2reg_theta\n self.l2reg_lambda = l2reg_lambda\n self.ckpt_to_load_from = ckpt_to_load_from\n self.tensor_name_in_ckpt = tensor_name_in_ckpt\n self.always_load_from_specific_ckpt = always_load_from_specific_ckpt\n self.init_data_source = init_data_source\n self.handle_name = handle_name\n self.emb_index = emb_index\n self.slot_index = slot_index\n self.block_num = block_num\n self.primary = primary\n self.slot_num = slot_num\n self.ht_type = ht_type\n self.l2_weight_threshold = l2_weight_threshold\n self.filter_strategy = filter_strategy\n self.storage_type = storage_type\n self.storage_path = storage_path\n self.storage_size = storage_size\n self.storage_cache_strategy = storage_cache_strategy\n self.layout = layout\n self.default_value_dim = default_value_dim\n self.default_value_no_permission = default_value_no_permission\n\n def reveal(self):\n if self.steps_to_live is None:\n self.steps_to_live = 0\n if self.steps_to_live_l2reg is None:\n self.steps_to_live_l2reg = 0\n if self.l2reg_theta is None:\n self.l2reg_theta = 0\n if self.l2reg_lambda is None:\n self.l2reg_lambda = 0\n if self.ht_type is None:\n self.ht_type = ''\n if self.emb_index is None:\n self.emb_index = 0\n if self.slot_index is None:\n self.slot_index = 0\n\nclass VariableMetaclass(type):\n \"\"\"Metaclass to allow construction of tf.Variable to be overridden.\"\"\"\n\n def _variable_v1_call(cls,\n initial_value=None,\n trainable=None,\n collections=None,\n validate_shape=True,\n caching_device=None,\n name=None,\n variable_def=None,\n dtype=None,\n embedding_block_num=None,\n expected_shape=None,\n import_scope=None,\n constraint=None,\n use_resource=None,\n synchronization=VariableSynchronization.AUTO,\n aggregation=VariableAggregation.NONE,\n shape=None,\n invalid_key=None,\n evconfig=EmbeddingVariableConfig(),\n embedding_initializer=None,\n ht_partition_num=1000):\n \"\"\"Call on Variable class. Useful to force the signature.\"\"\"\n previous_getter = lambda **kwargs: default_variable_creator(None, **kwargs)\n for _, getter in ops.get_default_graph()._variable_creator_stack: # pylint: disable=protected-access\n previous_getter = _make_getter(getter, previous_getter)\n\n # Reset `aggregation` that is explicitly set as `None` to the enum NONE.\n if aggregation is None:\n aggregation = VariableAggregation.NONE\n return previous_getter(\n initial_value=initial_value,\n trainable=trainable,\n collections=collections,\n validate_shape=validate_shape,\n caching_device=caching_device,\n name=name,\n variable_def=variable_def,\n dtype=dtype,\n embedding_block_num=embedding_block_num,\n expected_shape=expected_shape,\n import_scope=import_scope,\n constraint=constraint,\n use_resource=use_resource,\n synchronization=synchronization,\n aggregation=aggregation,\n shape=shape,\n invalid_key=invalid_key,\n evconfig=evconfig,\n embedding_initializer=embedding_initializer,\n ht_partition_num=ht_partition_num)\n\n def _variable_v2_call(cls,\n initial_value=None,\n trainable=None,\n validate_shape=True,\n caching_device=None,\n name=None,\n variable_def=None,\n dtype=None,\n import_scope=None,\n constraint=None,\n synchronization=VariableSynchronization.AUTO,\n aggregation=VariableAggregation.NONE,\n shape=None):\n \"\"\"Call on Variable class. Useful to force the signature.\"\"\"\n previous_getter = lambda **kws: default_variable_creator_v2(None, **kws)\n for _, getter in ops.get_default_graph()._variable_creator_stack: # pylint: disable=protected-access\n previous_getter = _make_getter(getter, previous_getter)\n\n # Reset `aggregation` that is explicitly set as `None` to the enum NONE.\n if aggregation is None:\n aggregation = VariableAggregation.NONE\n return previous_getter(\n initial_value=initial_value,\n trainable=trainable,\n validate_shape=validate_shape,\n caching_device=caching_device,\n name=name,\n variable_def=variable_def,\n dtype=dtype,\n import_scope=import_scope,\n constraint=constraint,\n synchronization=synchronization,\n aggregation=aggregation,\n shape=shape)\n\n def __call__(cls, *args, **kwargs):\n if cls is VariableV1:\n return cls._variable_v1_call(*args, **kwargs)\n elif cls is Variable:\n return cls._variable_v2_call(*args, **kwargs)\n else:\n return super(VariableMetaclass, cls).__call__(*args, **kwargs)\n\n\n@tf_export(\"Variable\", v1=[])\nclass Variable(six.with_metaclass(VariableMetaclass, trackable.Trackable)):\n \"\"\"See the [Variables Guide](https://tensorflow.org/guide/variables).\n\n A variable maintains state in the graph across calls to `run()`. You add a\n variable to the graph by constructing an instance of the class `Variable`.\n\n The `Variable()` constructor requires an initial value for the variable,\n which can be a `Tensor` of any type and shape. The initial value defines the\n type and shape of the variable. After construction, the type and shape of\n the variable are fixed. The value can be changed using one of the assign\n methods.\n\n If you want to change the shape of a variable later you have to use an\n `assign` Op with `validate_shape=False`.\n\n Just like any `Tensor`, variables created with `Variable()` can be used as\n inputs for other Ops in the graph. Additionally, all the operators\n overloaded for the `Tensor` class are carried over to variables, so you can\n also add nodes to the graph by just doing arithmetic on variables.\n\n ```python\n import tensorflow as tf\n\n # Create a variable.\n w = tf.Variable(, name=)\n\n # Use the variable in the graph like any Tensor.\n y = tf.matmul(w, ...another variable or tensor...)\n\n # The overloaded operators are available too.\n z = tf.sigmoid(w + y)\n\n # Assign a new value to the variable with `assign()` or a related method.\n w.assign(w + 1.0)\n w.assign_add(1.0)\n ```\n\n When you launch the graph, variables have to be explicitly initialized before\n you can run Ops that use their value. You can initialize a variable by\n running its *initializer op*, restoring the variable from a save file, or\n simply running an `assign` Op that assigns a value to the variable. In fact,\n the variable *initializer op* is just an `assign` Op that assigns the\n variable's initial value to the variable itself.\n\n ```python\n # Launch the graph in a session.\n with tf.compat.v1.Session() as sess:\n # Run the variable initializer.\n sess.run(w.initializer)\n # ...you now can run ops that use the value of 'w'...\n ```\n\n The most common initialization pattern is to use the convenience function\n `global_variables_initializer()` to add an Op to the graph that initializes\n all the variables. You then run that Op after launching the graph.\n\n ```python\n # Add an Op to initialize global variables.\n init_op = tf.compat.v1.global_variables_initializer()\n\n # Launch the graph in a session.\n with tf.compat.v1.Session() as sess:\n # Run the Op that initializes global variables.\n sess.run(init_op)\n # ...you can now run any Op that uses variable values...\n ```\n\n If you need to create a variable with an initial value dependent on another\n variable, use the other variable's `initialized_value()`. This ensures that\n variables are initialized in the right order.\n\n All variables are automatically collected in the graph where they are\n created. By default, the constructor adds the new variable to the graph\n collection `GraphKeys.GLOBAL_VARIABLES`. The convenience function\n `global_variables()` returns the contents of that collection.\n\n When building a machine learning model it is often convenient to distinguish\n between variables holding the trainable model parameters and other variables\n such as a `global step` variable used to count training steps. To make this\n easier, the variable constructor supports a `trainable=` parameter. If\n `True`, the new variable is also added to the graph collection\n `GraphKeys.TRAINABLE_VARIABLES`. The convenience function\n `trainable_variables()` returns the contents of this collection. The\n various `Optimizer` classes use this collection as the default list of\n variables to optimize.\n \"\"\"\n\n def __init__(self,\n initial_value=None,\n trainable=None,\n validate_shape=True,\n caching_device=None,\n name=None,\n variable_def=None,\n dtype=None,\n import_scope=None,\n constraint=None,\n synchronization=VariableSynchronization.AUTO,\n aggregation=VariableAggregation.NONE,\n shape=None):\n \"\"\"Creates a new variable with value `initial_value`.\n\n The new variable is added to the graph collections listed in `collections`,\n which defaults to `[GraphKeys.GLOBAL_VARIABLES]`.\n\n If `trainable` is `True` the variable is also added to the graph collection\n `GraphKeys.TRAINABLE_VARIABLES`.\n\n This constructor creates both a `variable` Op and an `assign` Op to set the\n variable to its initial value.\n\n Args:\n initial_value: A `Tensor`, or Python object convertible to a `Tensor`,\n which is the initial value for the Variable. The initial value must have\n a shape specified unless `validate_shape` is set to False. Can also be a\n callable with no argument that returns the initial value when called. In\n that case, `dtype` must be specified. (Note that initializer functions\n from init_ops.py must first be bound to a shape before being used here.)\n trainable: If `True`, GradientTapes automatically watch uses of this\n variable. Defaults to `True`, unless `synchronization` is set to\n `ON_READ`, in which case it defaults to `False`.\n validate_shape: If `False`, allows the variable to be initialized with a\n value of unknown shape. If `True`, the default, the shape of\n `initial_value` must be known.\n caching_device: Optional device string describing where the Variable\n should be cached for reading. Defaults to the Variable's device. If not\n `None`, caches on another device. Typical use is to cache on the device\n where the Ops using the Variable reside, to deduplicate copying through\n `Switch` and other conditional statements.\n name: Optional name for the variable. Defaults to `'Variable'` and gets\n uniquified automatically.\n variable_def: `VariableDef` protocol buffer. If not `None`, recreates the\n Variable object with its contents, referencing the variable's nodes in\n the graph, which must already exist. The graph is not changed.\n `variable_def` and the other arguments are mutually exclusive.\n dtype: If set, initial_value will be converted to the given type. If\n `None`, either the datatype will be kept (if `initial_value` is a\n Tensor), or `convert_to_tensor` will decide.\n import_scope: Optional `string`. Name scope to add to the `Variable.` Only\n used when initializing from protocol buffer.\n constraint: An optional projection function to be applied to the variable\n after being updated by an `Optimizer` (e.g. used to implement norm\n constraints or value constraints for layer weights). The function must\n take as input the unprojected Tensor representing the value of the\n variable and return the Tensor for the projected value (which must have\n the same shape). Constraints are not safe to use when doing asynchronous\n distributed training.\n synchronization: Indicates when a distributed a variable will be\n aggregated. Accepted values are constants defined in the class\n `tf.VariableSynchronization`. By default the synchronization is set to\n `AUTO` and the current `DistributionStrategy` chooses when to\n synchronize.\n aggregation: Indicates how a distributed variable will be aggregated.\n Accepted values are constants defined in the class\n `tf.VariableAggregation`.\n shape: (optional) The shape of this variable. If None, the shape of\n `initial_value` will be used. When setting this argument to\n `tf.TensorShape(None)` (representing an unspecified shape), the variable\n can be assigned with values of different shapes.\n\n Raises:\n ValueError: If both `variable_def` and initial_value are specified.\n ValueError: If the initial value is not specified, or does not have a\n shape and `validate_shape` is `True`.\n RuntimeError: If eager execution is enabled.\n \"\"\"\n raise NotImplementedError\n\n def __repr__(self):\n raise NotImplementedError\n\n def value(self):\n \"\"\"Returns the last snapshot of this variable.\n\n You usually do not need to call this method as all ops that need the value\n of the variable call it automatically through a `convert_to_tensor()` call.\n\n Returns a `Tensor` which holds the value of the variable. You can not\n assign a new value to this tensor as it is not a reference to the variable.\n\n To avoid copies, if the consumer of the returned value is on the same device\n as the variable, this actually returns the live value of the variable, not\n a copy. Updates to the variable are seen by the consumer. If the consumer\n is on a different device it will get a copy of the variable.\n\n Returns:\n A `Tensor` containing the value of the variable.\n \"\"\"\n raise NotImplementedError\n\n def read_value(self):\n \"\"\"Returns the value of this variable, read in the current context.\n\n Can be different from value() if it's on another device, with control\n dependencies, etc.\n\n Returns:\n A `Tensor` containing the value of the variable.\n \"\"\"\n raise NotImplementedError\n\n def set_shape(self, shape):\n \"\"\"Overrides the shape for this variable.\n\n Args:\n shape: the `TensorShape` representing the overridden shape.\n \"\"\"\n raise NotImplementedError\n\n @property\n def trainable(self):\n raise NotImplementedError\n\n @property\n def synchronization(self):\n raise NotImplementedError\n\n @property\n def aggregation(self):\n raise NotImplementedError\n\n def eval(self, session=None):\n \"\"\"In a session, computes and returns the value of this variable.\n\n This is not a graph construction method, it does not add ops to the graph.\n\n This convenience method requires a session where the graph\n containing this variable has been launched. If no session is\n passed, the default session is used. See `tf.compat.v1.Session` for more\n information on launching a graph and on sessions.\n\n ```python\n v = tf.Variable([1, 2])\n init = tf.compat.v1.global_variables_initializer()\n\n with tf.compat.v1.Session() as sess:\n sess.run(init)\n # Usage passing the session explicitly.\n print(v.eval(sess))\n # Usage with the default session. The 'with' block\n # above makes 'sess' the default session.\n print(v.eval())\n ```\n\n Args:\n session: The session to use to evaluate this variable. If none, the\n default session is used.\n\n Returns:\n A numpy `ndarray` with a copy of the value of this variable.\n \"\"\"\n raise NotImplementedError\n\n @deprecated(\n None, \"Use Variable.read_value. Variables in 2.X are initialized \"\n \"automatically both in eager and graph (inside tf.defun) contexts.\")\n def initialized_value(self):\n \"\"\"Returns the value of the initialized variable.\n\n You should use this instead of the variable itself to initialize another\n variable with a value that depends on the value of this variable.\n\n ```python\n # Initialize 'v' with a random tensor.\n v = tf.Variable(tf.random.truncated_normal([10, 40]))\n # Use `initialized_value` to guarantee that `v` has been\n # initialized before its value is used to initialize `w`.\n # The random values are picked only once.\n w = tf.Variable(v.initialized_value() * 2.0)\n ```\n\n Returns:\n A `Tensor` holding the value of this variable after its initializer\n has run.\n \"\"\"\n with ops.init_scope():\n # optimize node placement policy in initialized_value stage.\n with ops.colocate_with(self):\n return control_flow_ops.cond(is_variable_initialized(self),\n self.read_value,\n lambda: self.initial_value)\n\n @property\n def initial_value(self):\n \"\"\"Returns the Tensor used as the initial value for the variable.\n\n Note that this is different from `initialized_value()` which runs\n the op that initializes the variable before returning its value.\n This method returns the tensor that is used by the op that initializes\n the variable.\n\n Returns:\n A `Tensor`.\n \"\"\"\n raise NotImplementedError\n\n @property\n def constraint(self):\n \"\"\"Returns the constraint function associated with this variable.\n\n Returns:\n The constraint function that was passed to the variable constructor.\n Can be `None` if no constraint was passed.\n \"\"\"\n raise NotImplementedError\n\n def assign(self, value, use_locking=False, name=None, read_value=True):\n \"\"\"Assigns a new value to the variable.\n\n This is essentially a shortcut for `assign(self, value)`.\n\n Args:\n value: A `Tensor`. The new value for this variable.\n use_locking: If `True`, use locking during the assignment.\n name: The name of the operation to be created\n read_value: if True, will return something which evaluates to the new\n value of the variable; if False will return the assign op.\n\n Returns:\n A `Tensor` that will hold the new value of this variable after\n the assignment has completed.\n \"\"\"\n raise NotImplementedError\n\n def assign_add(self, delta, use_locking=False, name=None, read_value=True):\n \"\"\"Adds a value to this variable.\n\n This is essentially a shortcut for `assign_add(self, delta)`.\n\n Args:\n delta: A `Tensor`. The value to add to this variable.\n use_locking: If `True`, use locking during the operation.\n name: The name of the operation to be created\n read_value: if True, will return something which evaluates to the new\n value of the variable; if False will return the assign op.\n\n Returns:\n A `Tensor` that will hold the new value of this variable after\n the addition has completed.\n \"\"\"\n raise NotImplementedError\n\n def assign_sub(self, delta, use_locking=False, name=None, read_value=True):\n \"\"\"Subtracts a value from this variable.\n\n This is essentially a shortcut for `assign_sub(self, delta)`.\n\n Args:\n delta: A `Tensor`. The value to subtract from this variable.\n use_locking: If `True`, use locking during the operation.\n name: The name of the operation to be created\n read_value: if True, will return something which evaluates to the new\n value of the variable; if False will return the assign op.\n\n Returns:\n A `Tensor` that will hold the new value of this variable after\n the subtraction has completed.\n \"\"\"\n raise NotImplementedError\n\n def scatter_sub(self, sparse_delta, use_locking=False, name=None):\n \"\"\"Subtracts `tf.IndexedSlices` from this variable.\n\n Args:\n sparse_delta: `tf.IndexedSlices` to be subtracted from this variable.\n use_locking: If `True`, use locking during the operation.\n name: the name of the operation.\n\n Returns:\n A `Tensor` that will hold the new value of this variable after\n the scattered subtraction has completed.\n\n Raises:\n TypeError: if `sparse_delta` is not an `IndexedSlices`.\n \"\"\"\n raise NotImplementedError\n\n def scatter_add(self, sparse_delta, use_locking=False, name=None):\n \"\"\"Adds `tf.IndexedSlices` to this variable.\n\n Args:\n sparse_delta: `tf.IndexedSlices` to be added to this variable.\n use_locking: If `True`, use locking during the operation.\n name: the name of the operation.\n\n Returns:\n A `Tensor` that will hold the new value of this variable after\n the scattered addition has completed.\n\n Raises:\n TypeError: if `sparse_delta` is not an `IndexedSlices`.\n \"\"\"\n raise NotImplementedError\n\n def scatter_max(self, sparse_delta, use_locking=False, name=None):\n \"\"\"Updates this variable with the max of `tf.IndexedSlices` and itself.\n\n Args:\n sparse_delta: `tf.IndexedSlices` to use as an argument of max with this\n variable.\n use_locking: If `True`, use locking during the operation.\n name: the name of the operation.\n\n Returns:\n A `Tensor` that will hold the new value of this variable after\n the scattered maximization has completed.\n\n Raises:\n TypeError: if `sparse_delta` is not an `IndexedSlices`.\n \"\"\"\n raise NotImplementedError\n\n def scatter_min(self, sparse_delta, use_locking=False, name=None):\n \"\"\"Updates this variable with the min of `tf.IndexedSlices` and itself.\n\n Args:\n sparse_delta: `tf.IndexedSlices` to use as an argument of min with this\n variable.\n use_locking: If `True`, use locking during the operation.\n name: the name of the operation.\n\n Returns:\n A `Tensor` that will hold the new value of this variable after\n the scattered minimization has completed.\n\n Raises:\n TypeError: if `sparse_delta` is not an `IndexedSlices`.\n \"\"\"\n raise NotImplementedError\n\n def scatter_mul(self, sparse_delta, use_locking=False, name=None):\n \"\"\"Multiply this variable by `tf.IndexedSlices`.\n\n Args:\n sparse_delta: `tf.IndexedSlices` to multiply this variable by.\n use_locking: If `True`, use locking during the operation.\n name: the name of the operation.\n\n Returns:\n A `Tensor` that will hold the new value of this variable after\n the scattered multiplication has completed.\n\n Raises:\n TypeError: if `sparse_delta` is not an `IndexedSlices`.\n \"\"\"\n raise NotImplementedError\n\n def scatter_div(self, sparse_delta, use_locking=False, name=None):\n \"\"\"Divide this variable by `tf.IndexedSlices`.\n\n Args:\n sparse_delta: `tf.IndexedSlices` to divide this variable by.\n use_locking: If `True`, use locking during the operation.\n name: the name of the operation.\n\n Returns:\n A `Tensor` that will hold the new value of this variable after\n the scattered division has completed.\n\n Raises:\n TypeError: if `sparse_delta` is not an `IndexedSlices`.\n \"\"\"\n raise NotImplementedError\n\n def scatter_update(self, sparse_delta, use_locking=False, name=None):\n \"\"\"Assigns `tf.IndexedSlices` to this variable.\n\n Args:\n sparse_delta: `tf.IndexedSlices` to be assigned to this variable.\n use_locking: If `True`, use locking during the operation.\n name: the name of the operation.\n\n Returns:\n A `Tensor` that will hold the new value of this variable after\n the scattered assignment has completed.\n\n Raises:\n TypeError: if `sparse_delta` is not an `IndexedSlices`.\n \"\"\"\n raise NotImplementedError\n\n def batch_scatter_update(self, sparse_delta, use_locking=False, name=None):\n \"\"\"Assigns `tf.IndexedSlices` to this variable batch-wise.\n\n Analogous to `batch_gather`. This assumes that this variable and the\n sparse_delta IndexedSlices have a series of leading dimensions that are the\n same for all of them, and the updates are performed on the last dimension of\n indices. In other words, the dimensions should be the following:\n\n `num_prefix_dims = sparse_delta.indices.ndims - 1`\n `batch_dim = num_prefix_dims + 1`\n `sparse_delta.updates.shape = sparse_delta.indices.shape + var.shape[\n batch_dim:]`\n\n where\n\n `sparse_delta.updates.shape[:num_prefix_dims]`\n `== sparse_delta.indices.shape[:num_prefix_dims]`\n `== var.shape[:num_prefix_dims]`\n\n And the operation performed can be expressed as:\n\n `var[i_1, ..., i_n,\n sparse_delta.indices[i_1, ..., i_n, j]] = sparse_delta.updates[\n i_1, ..., i_n, j]`\n\n When sparse_delta.indices is a 1D tensor, this operation is equivalent to\n `scatter_update`.\n\n To avoid this operation one can looping over the first `ndims` of the\n variable and using `scatter_update` on the subtensors that result of slicing\n the first dimension. This is a valid option for `ndims = 1`, but less\n efficient than this implementation.\n\n Args:\n sparse_delta: `tf.IndexedSlices` to be assigned to this variable.\n use_locking: If `True`, use locking during the operation.\n name: the name of the operation.\n\n Returns:\n A `Tensor` that will hold the new value of this variable after\n the scattered assignment has completed.\n\n Raises:\n TypeError: if `sparse_delta` is not an `IndexedSlices`.\n \"\"\"\n raise NotImplementedError\n\n def scatter_nd_sub(self, indices, updates, name=None):\n \"\"\"Applies sparse subtraction to individual values or slices in a Variable.\n\n Assuming the variable has rank `P` and `indices` is a `Tensor` of rank `Q`.\n\n `indices` must be integer tensor, containing indices into self.\n It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`.\n\n The innermost dimension of `indices` (with length `K`) corresponds to\n indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th\n dimension of self.\n\n `updates` is `Tensor` of rank `Q-1+P-K` with shape:\n\n ```\n [d_0, ..., d_{Q-2}, self.shape[K], ..., self.shape[P-1]].\n ```\n\n For example, say we want to add 4 scattered elements to a rank-1 tensor to\n 8 elements. In Python, that update would look like this:\n\n ```python\n v = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8])\n indices = tf.constant([[4], [3], [1] ,[7]])\n updates = tf.constant([9, 10, 11, 12])\n op = v.scatter_nd_sub(indices, updates)\n with tf.compat.v1.Session() as sess:\n print sess.run(op)\n ```\n\n The resulting update to v would look like this:\n\n [1, -9, 3, -6, -6, 6, 7, -4]\n\n See `tf.scatter_nd` for more details about how to make updates to\n slices.\n\n Args:\n indices: The indices to be used in the operation.\n updates: The values to be used in the operation.\n name: the name of the operation.\n\n Returns:\n A `Tensor` that will hold the new value of this variable after\n the scattered subtraction has completed.\n \"\"\"\n raise NotImplementedError\n\n def scatter_nd_add(self, indices, updates, name=None):\n \"\"\"Applies sparse addition to individual values or slices in a Variable.\n\n The Variable has rank `P` and `indices` is a `Tensor` of rank `Q`.\n\n `indices` must be integer tensor, containing indices into self.\n It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`.\n\n The innermost dimension of `indices` (with length `K`) corresponds to\n indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th\n dimension of self.\n\n `updates` is `Tensor` of rank `Q-1+P-K` with shape:\n\n ```\n [d_0, ..., d_{Q-2}, self.shape[K], ..., self.shape[P-1]].\n ```\n\n For example, say we want to add 4 scattered elements to a rank-1 tensor to\n 8 elements. In Python, that update would look like this:\n\n ```python\n v = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8])\n indices = tf.constant([[4], [3], [1] ,[7]])\n updates = tf.constant([9, 10, 11, 12])\n add = v.scatter_nd_add(indices, updates)\n with tf.compat.v1.Session() as sess:\n print sess.run(add)\n ```\n\n The resulting update to v would look like this:\n\n [1, 13, 3, 14, 14, 6, 7, 20]\n\n See `tf.scatter_nd` for more details about how to make updates to\n slices.\n\n Args:\n indices: The indices to be used in the operation.\n updates: The values to be used in the operation.\n name: the name of the operation.\n\n Returns:\n A `Tensor` that will hold the new value of this variable after\n the scattered addition has completed.\n \"\"\"\n raise NotImplementedError\n\n def scatter_nd_update(self, indices, updates, name=None):\n \"\"\"Applies sparse assignment to individual values or slices in a Variable.\n\n The Variable has rank `P` and `indices` is a `Tensor` of rank `Q`.\n\n `indices` must be integer tensor, containing indices into self.\n It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`.\n\n The innermost dimension of `indices` (with length `K`) corresponds to\n indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th\n dimension of self.\n\n `updates` is `Tensor` of rank `Q-1+P-K` with shape:\n\n ```\n [d_0, ..., d_{Q-2}, self.shape[K], ..., self.shape[P-1]].\n ```\n\n For example, say we want to add 4 scattered elements to a rank-1 tensor to\n 8 elements. In Python, that update would look like this:\n\n ```python\n v = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8])\n indices = tf.constant([[4], [3], [1] ,[7]])\n updates = tf.constant([9, 10, 11, 12])\n op = v.scatter_nd_assign(indices, updates)\n with tf.compat.v1.Session() as sess:\n print sess.run(op)\n ```\n\n The resulting update to v would look like this:\n\n [1, 11, 3, 10, 9, 6, 7, 12]\n\n See `tf.scatter_nd` for more details about how to make updates to\n slices.\n\n Args:\n indices: The indices to be used in the operation.\n updates: The values to be used in the operation.\n name: the name of the operation.\n\n Returns:\n A `Tensor` that will hold the new value of this variable after\n the scattered assignment has completed.\n \"\"\"\n raise NotImplementedError\n\n def sparse_read(self, indices, name=None, ev_init_value=None):\n r\"\"\"Gather slices from params axis axis according to indices.\n\n This function supports a subset of tf.gather, see tf.gather for details on\n usage.\n\n Args:\n indices: The index `Tensor`. Must be one of the following types: `int32`,\n `int64`. Must be in range `[0, params.shape[axis])`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor`. Has the same type as `params`.\n \"\"\"\n raise AttributeError\n\n def gather_nd(self, indices, name=None):\n r\"\"\"Gather slices from `params` into a Tensor with shape specified by `indices`.\n\n See tf.gather_nd for details.\n\n Args:\n indices: A `Tensor`. Must be one of the following types: `int32`, `int64`.\n Index tensor.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor`. Has the same type as `params`.\n \"\"\"\n raise AttributeError\n\n @deprecated(None, \"Prefer Dataset.range instead.\")\n def count_up_to(self, limit):\n \"\"\"Increments this variable until it reaches `limit`.\n\n When that Op is run it tries to increment the variable by `1`. If\n incrementing the variable would bring it above `limit` then the Op raises\n the exception `OutOfRangeError`.\n\n If no error is raised, the Op outputs the value of the variable before\n the increment.\n\n This is essentially a shortcut for `count_up_to(self, limit)`.\n\n Args:\n limit: value at which incrementing the variable raises an error.\n\n Returns:\n A `Tensor` that will hold the variable value before the increment. If no\n other Op modifies this variable, the values produced will all be\n distinct.\n \"\"\"\n raise NotImplementedError\n\n @deprecated(None,\n \"Prefer Variable.assign which has equivalent behavior in 2.X.\")\n def load(self, value, session=None):\n \"\"\"Load new value into this variable.\n\n Writes new value to variable's memory. Doesn't add ops to the graph.\n\n This convenience method requires a session where the graph\n containing this variable has been launched. If no session is\n passed, the default session is used. See `tf.compat.v1.Session` for more\n information on launching a graph and on sessions.\n\n ```python\n v = tf.Variable([1, 2])\n init = tf.compat.v1.global_variables_initializer()\n\n with tf.compat.v1.Session() as sess:\n sess.run(init)\n # Usage passing the session explicitly.\n v.load([2, 3], sess)\n print(v.eval(sess)) # prints [2 3]\n # Usage with the default session. The 'with' block\n # above makes 'sess' the default session.\n v.load([3, 4], sess)\n print(v.eval()) # prints [3 4]\n ```\n\n Args:\n value: New variable value\n session: The session to use to evaluate this variable. If none, the\n default session is used.\n\n Raises:\n ValueError: Session is not passed and no default session\n \"\"\"\n if context.executing_eagerly():\n self.assign(value)\n else:\n session = session or ops.get_default_session()\n if session is None:\n raise ValueError(\n \"Either session argument should be provided or default session \"\n \"should be established\")\n session.run(self.initializer, {self.initializer.inputs[1]: value})\n\n # Conversion to tensor.\n @staticmethod\n def _TensorConversionFunction(v, dtype=None, name=None, as_ref=False): # pylint: disable=invalid-name\n \"\"\"Utility function for converting a Variable to a Tensor.\"\"\"\n _ = name\n if dtype and not dtype.is_compatible_with(v.dtype):\n raise ValueError(\n \"Incompatible type conversion requested to type '%s' for variable \"\n \"of type '%s'\" % (dtype.name, v.dtype.name))\n if as_ref:\n return v._ref() # pylint: disable=protected-access\n else:\n return v.value()\n\n @classmethod\n def _OverloadAllOperators(cls): # pylint: disable=invalid-name\n \"\"\"Register overloads for all operators.\"\"\"\n for operator in ops.Tensor.OVERLOADABLE_OPERATORS:\n cls._OverloadOperator(operator)\n # For slicing, bind getitem differently than a tensor (use SliceHelperVar\n # instead)\n # pylint: disable=protected-access\n setattr(cls, \"__getitem__\", array_ops._SliceHelperVar)\n\n @classmethod\n def _OverloadOperator(cls, operator): # pylint: disable=invalid-name\n \"\"\"Defer an operator overload to `ops.Tensor`.\n\n We pull the operator out of ops.Tensor dynamically to avoid ordering issues.\n\n Args:\n operator: string. The operator name.\n \"\"\"\n # We can't use the overload mechanism on __eq__ & __ne__ since __eq__ is\n # called when adding a variable to sets. As a result we call a.value() which\n # causes infinite recursion when operating within a GradientTape\n # TODO(gjn): Consider removing this\n if operator == \"__eq__\" or operator == \"__ne__\":\n return\n\n tensor_oper = getattr(ops.Tensor, operator)\n\n def _run_op(a, *args, **kwargs):\n # pylint: disable=protected-access\n return tensor_oper(a.value(), *args, **kwargs)\n\n functools.update_wrapper(_run_op, tensor_oper)\n setattr(cls, operator, _run_op)\n\n def __hash__(self):\n if ops.Tensor._USE_EQUALITY and ops.executing_eagerly_outside_functions(): # pylint: disable=protected-access\n raise TypeError(\"Variable is unhashable if Tensor equality is enabled. \"\n \"Instead, use tensor.experimental_ref() as the key.\")\n else:\n return id(self)\n\n # TODO(gjn): duplicate of math_ops.tensor_equals, consider removing\n def __eq__(self, other):\n \"\"\"Compares two variables element-wise for equality.\"\"\"\n if ops.Tensor._USE_EQUALITY and ops.executing_eagerly_outside_functions(): # pylint: disable=protected-access\n if fwd_compat.forward_compatible(2019, 9, 25):\n return gen_math_ops.equal(self, other, incompatible_shape_error=False)\n else:\n return gen_math_ops.equal(self, other)\n else:\n # In legacy graph mode, tensor equality is object equality\n return self is other\n\n # TODO(gjn): duplicate of math_ops.tensor_not_equals, consider removing\n def __ne__(self, other):\n \"\"\"Compares two variables element-wise for equality.\"\"\"\n if ops.Tensor._USE_EQUALITY and ops.executing_eagerly_outside_functions(): # pylint: disable=protected-access\n if fwd_compat.forward_compatible(2019, 9, 25):\n return gen_math_ops.not_equal(\n self, other, incompatible_shape_error=False)\n else:\n return gen_math_ops.not_equal(self, other)\n else:\n # In legacy graph mode, tensor equality is object equality\n return self is not other\n\n def __iter__(self):\n \"\"\"Dummy method to prevent iteration.\n\n Do not call.\n\n NOTE(mrry): If we register __getitem__ as an overloaded operator,\n Python will valiantly attempt to iterate over the variable's Tensor from 0\n to infinity. Declaring this method prevents this unintended behavior.\n\n Raises:\n TypeError: when invoked.\n \"\"\"\n raise TypeError(\"'Variable' object is not iterable.\")\n\n # NOTE(mrry): This enables the Variable's overloaded \"right\" binary\n # operators to run when the left operand is an ndarray, because it\n # accords the Variable class higher priority than an ndarray, or a\n # numpy matrix.\n # TODO(mrry): Convert this to using numpy's __numpy_ufunc__\n # mechanism, which allows more control over how Variables interact\n # with ndarrays.\n __array_priority__ = 100\n\n @property\n def name(self):\n \"\"\"The name of this variable.\"\"\"\n raise NotImplementedError\n\n @property\n def _shared_name(self):\n \"\"\"The shared name of the variable.\n\n Unlike name(), shared_name doesn't have \":0\" suffix. It is user-specified\n name with name scope prefix.\n\n Returns:\n variable name.\n \"\"\"\n return self.name[:self.name.index(\":\")]\n\n @property\n def initializer(self):\n \"\"\"The initializer operation for this variable.\"\"\"\n raise NotImplementedError\n\n @property\n def device(self):\n \"\"\"The device of this variable.\"\"\"\n raise NotImplementedError\n\n @property\n def dtype(self):\n \"\"\"The `DType` of this variable.\"\"\"\n raise NotImplementedError\n\n @property\n def op(self):\n \"\"\"The `Operation` of this variable.\"\"\"\n raise NotImplementedError\n\n @property\n def graph(self):\n \"\"\"The `Graph` of this variable.\"\"\"\n raise NotImplementedError\n\n @property\n def shape(self):\n \"\"\"The `TensorShape` of this variable.\n\n Returns:\n A `TensorShape`.\n \"\"\"\n raise NotImplementedError\n\n def get_shape(self):\n \"\"\"Alias of `Variable.shape`.\"\"\"\n return self.shape\n\n def _gather_saveables_for_checkpoint(self):\n \"\"\"For implementing `Trackable`. This object is saveable on its own.\"\"\"\n return {trackable.VARIABLE_VALUE_KEY: self}\n\n def to_proto(self, export_scope=None):\n \"\"\"Converts a `Variable` to a `VariableDef` protocol buffer.\n\n Args:\n export_scope: Optional `string`. Name scope to remove.\n\n Returns:\n A `VariableDef` protocol buffer, or `None` if the `Variable` is not\n in the specified name scope.\n \"\"\"\n raise NotImplementedError\n\n @staticmethod\n def from_proto(variable_def, import_scope=None):\n \"\"\"Returns a `Variable` object created from `variable_def`.\"\"\"\n return RefVariable(variable_def=variable_def, import_scope=import_scope)\n\n def _set_save_slice_info(self, save_slice_info):\n \"\"\"Sets the slice info for this `Variable`.\n\n Args:\n save_slice_info: A `Variable.SaveSliceInfo` object.\n \"\"\"\n self._save_slice_info = save_slice_info\n\n def _get_save_slice_info(self):\n return self._save_slice_info\n\n def experimental_ref(self):\n # tf.Tensor also has the same experimental_ref() API. If you update the\n # documenation here, please update tf.Tensor.experimental_ref() as well.\n \"\"\"Returns a hashable reference object to this Variable.\n\n Warning: Experimental API that could be changed or removed.\n\n The primary usecase for this API is to put variables in a set/dictionary.\n We can't put variables in a set/dictionary as `variable.__hash__()` is no\n longer available starting Tensorflow 2.0.\n\n ```python\n import tensorflow as tf\n\n x = tf.Variable(5)\n y = tf.Variable(10)\n z = tf.Variable(10)\n\n # The followings will raise an exception starting 2.0\n # TypeError: Variable is unhashable if Variable equality is enabled.\n variable_set = {x, y, z}\n variable_dict = {x: 'five', y: 'ten'}\n ```\n\n Instead, we can use `variable.experimental_ref()`.\n\n ```python\n variable_set = {x.experimental_ref(),\n y.experimental_ref(),\n z.experimental_ref()}\n\n print(x.experimental_ref() in variable_set)\n ==> True\n\n variable_dict = {x.experimental_ref(): 'five',\n y.experimental_ref(): 'ten',\n z.experimental_ref(): 'ten'}\n\n print(variable_dict[y.experimental_ref()])\n ==> ten\n ```\n\n Also, the reference object provides `.deref()` function that returns the\n original Variable.\n\n ```python\n x = tf.Variable(5)\n print(x.experimental_ref().deref())\n ==> \n ```\n \"\"\"\n return object_identity.Reference(self)\n\n class SaveSliceInfo(object):\n \"\"\"Information on how to save this Variable as a slice.\n\n Provides internal support for saving variables as slices of a larger\n variable. This API is not public and is subject to change.\n\n Available properties:\n\n * full_name\n * full_shape\n * var_offset\n * var_shape\n \"\"\"\n\n def __init__(self,\n full_name=None,\n full_shape=None,\n var_offset=None,\n var_shape=None,\n save_slice_info_def=None,\n import_scope=None,\n var_full_name=None):\n \"\"\"Create a `SaveSliceInfo`.\n\n Args:\n full_name: Name of the full variable of which this `Variable` is a\n slice.\n full_shape: Shape of the full variable, as a list of int.\n var_offset: Offset of this `Variable` into the full variable, as a list\n of int.\n var_shape: Shape of this `Variable`, as a list of int.\n save_slice_info_def: `SaveSliceInfoDef` protocol buffer. If not `None`,\n recreates the SaveSliceInfo object its contents. `save_slice_info_def`\n and other arguments are mutually exclusive.\n import_scope: Optional `string`. Name scope to add. Only used when\n initializing from protocol buffer.\n \"\"\"\n if save_slice_info_def:\n assert isinstance(save_slice_info_def, variable_pb2.SaveSliceInfoDef)\n self.full_name = ops.prepend_name_scope(\n save_slice_info_def.full_name, import_scope=import_scope)\n self.full_shape = [i for i in save_slice_info_def.full_shape]\n self.var_offset = [i for i in save_slice_info_def.var_offset]\n self.var_shape = [i for i in save_slice_info_def.var_shape]\n self.var_full_name = var_full_name\n else:\n self.full_name = full_name\n self.full_shape = full_shape\n self.var_offset = var_offset\n self.var_shape = var_shape\n self.var_full_name = var_full_name\n\n @property\n def spec(self):\n \"\"\"Computes the spec string used for saving.\"\"\"\n full_shape_str = \" \".join([\"%d\" % d for d in self.full_shape]) + \" \"\n sl_spec = \":\".join(\n [\"%d,%d\" % (o, s) for o, s in zip(self.var_offset, self.var_shape)])\n return full_shape_str + sl_spec\n\n def to_proto(self, export_scope=None):\n \"\"\"Returns a SaveSliceInfoDef() proto.\n\n Args:\n export_scope: Optional `string`. Name scope to remove.\n\n Returns:\n A `SaveSliceInfoDef` protocol buffer, or None if the `Variable` is not\n in the specified name scope.\n \"\"\"\n if (export_scope is None or self.full_name.startswith(export_scope)):\n save_slice_info_def = variable_pb2.SaveSliceInfoDef()\n save_slice_info_def.full_name = ops.strip_name_scope(\n self.full_name, export_scope)\n for i in self.full_shape:\n save_slice_info_def.full_shape.append(i)\n for i in self.var_offset:\n save_slice_info_def.var_offset.append(i)\n for i in self.var_shape:\n save_slice_info_def.var_shape.append(i)\n return save_slice_info_def\n else:\n return None\n\n\nVariable._OverloadAllOperators() # pylint: disable=protected-access\npywrap_tensorflow.RegisterType(\"Variable\", Variable)\n\n\n@tf_export(v1=[\"Variable\"])\nclass VariableV1(Variable):\n \"\"\"See the [Variables Guide](https://tensorflow.org/guide/variables).\n\n A variable maintains state in the graph across calls to `run()`. You add a\n variable to the graph by constructing an instance of the class `Variable`.\n\n The `Variable()` constructor requires an initial value for the variable,\n which can be a `Tensor` of any type and shape. The initial value defines the\n type and shape of the variable. After construction, the type and shape of\n the variable are fixed. The value can be changed using one of the assign\n methods.\n\n If you want to change the shape of a variable later you have to use an\n `assign` Op with `validate_shape=False`.\n\n Just like any `Tensor`, variables created with `Variable()` can be used as\n inputs for other Ops in the graph. Additionally, all the operators\n overloaded for the `Tensor` class are carried over to variables, so you can\n also add nodes to the graph by just doing arithmetic on variables.\n\n ```python\n import tensorflow as tf\n\n # Create a variable.\n w = tf.Variable(, name=)\n\n # Use the variable in the graph like any Tensor.\n y = tf.matmul(w, ...another variable or tensor...)\n\n # The overloaded operators are available too.\n z = tf.sigmoid(w + y)\n\n # Assign a new value to the variable with `assign()` or a related method.\n w.assign(w + 1.0)\n w.assign_add(1.0)\n ```\n\n When you launch the graph, variables have to be explicitly initialized before\n you can run Ops that use their value. You can initialize a variable by\n running its *initializer op*, restoring the variable from a save file, or\n simply running an `assign` Op that assigns a value to the variable. In fact,\n the variable *initializer op* is just an `assign` Op that assigns the\n variable's initial value to the variable itself.\n\n ```python\n # Launch the graph in a session.\n with tf.compat.v1.Session() as sess:\n # Run the variable initializer.\n sess.run(w.initializer)\n # ...you now can run ops that use the value of 'w'...\n ```\n\n The most common initialization pattern is to use the convenience function\n `global_variables_initializer()` to add an Op to the graph that initializes\n all the variables. You then run that Op after launching the graph.\n\n ```python\n # Add an Op to initialize global variables.\n init_op = tf.compat.v1.global_variables_initializer()\n\n # Launch the graph in a session.\n with tf.compat.v1.Session() as sess:\n # Run the Op that initializes global variables.\n sess.run(init_op)\n # ...you can now run any Op that uses variable values...\n ```\n\n If you need to create a variable with an initial value dependent on another\n variable, use the other variable's `initialized_value()`. This ensures that\n variables are initialized in the right order.\n\n All variables are automatically collected in the graph where they are\n created. By default, the constructor adds the new variable to the graph\n collection `GraphKeys.GLOBAL_VARIABLES`. The convenience function\n `global_variables()` returns the contents of that collection.\n\n When building a machine learning model it is often convenient to distinguish\n between variables holding the trainable model parameters and other variables\n such as a `global step` variable used to count training steps. To make this\n easier, the variable constructor supports a `trainable=` parameter. If\n `True`, the new variable is also added to the graph collection\n `GraphKeys.TRAINABLE_VARIABLES`. The convenience function\n `trainable_variables()` returns the contents of this collection. The\n various `Optimizer` classes use this collection as the default list of\n variables to optimize.\n\n WARNING: tf.Variable objects by default have a non-intuitive memory model. A\n Variable is represented internally as a mutable Tensor which can\n non-deterministically alias other Tensors in a graph. The set of operations\n which consume a Variable and can lead to aliasing is undetermined and can\n change across TensorFlow versions. Avoid writing code which relies on the\n value of a Variable either changing or not changing as other operations\n happen. For example, using Variable objects or simple functions thereof as\n predicates in a `tf.cond` is dangerous and error-prone:\n\n ```\n v = tf.Variable(True)\n tf.cond(v, lambda: v.assign(False), my_false_fn) # Note: this is broken.\n ```\n\n Here, adding `use_resource=True` when constructing the variable will\n fix any nondeterminism issues:\n ```\n v = tf.Variable(True, use_resource=True)\n tf.cond(v, lambda: v.assign(False), my_false_fn)\n ```\n\n To use the replacement for variables which does\n not have these issues:\n\n * Add `use_resource=True` when constructing `tf.Variable`;\n * Call `tf.compat.v1.get_variable_scope().set_use_resource(True)` inside a\n `tf.compat.v1.variable_scope` before the `tf.compat.v1.get_variable()` call.\n \"\"\"\n\n def __init__(\n self, # pylint: disable=super-init-not-called\n initial_value=None,\n trainable=None,\n collections=None,\n validate_shape=True,\n caching_device=None,\n name=None,\n variable_def=None,\n dtype=None,\n expected_shape=None,\n import_scope=None,\n constraint=None,\n use_resource=None,\n synchronization=VariableSynchronization.AUTO,\n aggregation=VariableAggregation.NONE,\n shape=None):\n \"\"\"Creates a new variable with value `initial_value`.\n\n The new variable is added to the graph collections listed in `collections`,\n which defaults to `[GraphKeys.GLOBAL_VARIABLES]`.\n\n If `trainable` is `True` the variable is also added to the graph collection\n `GraphKeys.TRAINABLE_VARIABLES`.\n\n This constructor creates both a `variable` Op and an `assign` Op to set the\n variable to its initial value.\n\n Args:\n initial_value: A `Tensor`, or Python object convertible to a `Tensor`,\n which is the initial value for the Variable. The initial value must have\n a shape specified unless `validate_shape` is set to False. Can also be a\n callable with no argument that returns the initial value when called. In\n that case, `dtype` must be specified. (Note that initializer functions\n from init_ops.py must first be bound to a shape before being used here.)\n trainable: If `True`, also adds the variable to the graph collection\n `GraphKeys.TRAINABLE_VARIABLES`. This collection is used as the default\n list of variables to use by the `Optimizer` classes. Defaults to `True`,\n unless `synchronization` is set to `ON_READ`, in which case it defaults\n to `False`.\n collections: List of graph collections keys. The new variable is added to\n these collections. Defaults to `[GraphKeys.GLOBAL_VARIABLES]`.\n validate_shape: If `False`, allows the variable to be initialized with a\n value of unknown shape. If `True`, the default, the shape of\n `initial_value` must be known.\n caching_device: Optional device string describing where the Variable\n should be cached for reading. Defaults to the Variable's device. If not\n `None`, caches on another device. Typical use is to cache on the device\n where the Ops using the Variable reside, to deduplicate copying through\n `Switch` and other conditional statements.\n name: Optional name for the variable. Defaults to `'Variable'` and gets\n uniquified automatically.\n variable_def: `VariableDef` protocol buffer. If not `None`, recreates the\n Variable object with its contents, referencing the variable's nodes in\n the graph, which must already exist. The graph is not changed.\n `variable_def` and the other arguments are mutually exclusive.\n dtype: If set, initial_value will be converted to the given type. If\n `None`, either the datatype will be kept (if `initial_value` is a\n Tensor), or `convert_to_tensor` will decide.\n expected_shape: A TensorShape. If set, initial_value is expected to have\n this shape.\n import_scope: Optional `string`. Name scope to add to the `Variable.` Only\n used when initializing from protocol buffer.\n constraint: An optional projection function to be applied to the variable\n after being updated by an `Optimizer` (e.g. used to implement norm\n constraints or value constraints for layer weights). The function must\n take as input the unprojected Tensor representing the value of the\n variable and return the Tensor for the projected value (which must have\n the same shape). Constraints are not safe to use when doing asynchronous\n distributed training.\n use_resource: whether to use resource variables.\n synchronization: Indicates when a distributed a variable will be\n aggregated. Accepted values are constants defined in the class\n `tf.VariableSynchronization`. By default the synchronization is set to\n `AUTO` and the current `DistributionStrategy` chooses when to\n synchronize.\n aggregation: Indicates how a distributed variable will be aggregated.\n Accepted values are constants defined in the class\n `tf.VariableAggregation`.\n shape: (optional) The shape of this variable. If None, the shape of\n `initial_value` will be used. When setting this argument to\n `tf.TensorShape(None)` (representing an unspecified shape), the variable\n can be assigned with values of different shapes.\n\n Raises:\n ValueError: If both `variable_def` and initial_value are specified.\n ValueError: If the initial value is not specified, or does not have a\n shape and `validate_shape` is `True`.\n RuntimeError: If eager execution is enabled.\n \"\"\"\n\n SaveSliceInfo = Variable.SaveSliceInfo\n\n\n# TODO(apassos): do not repeat all comments here\nclass RefVariable(VariableV1):\n \"\"\"Ref-based implementation of variables.\"\"\"\n\n def __init__(\n self, # pylint: disable=super-init-not-called\n initial_value=None,\n trainable=None,\n collections=None,\n validate_shape=True,\n caching_device=None,\n name=None,\n variable_def=None,\n dtype=None,\n expected_shape=None,\n import_scope=None,\n constraint=None,\n synchronization=None,\n aggregation=None,\n shape=None):\n \"\"\"Creates a new variable with value `initial_value`.\n\n The new variable is added to the graph collections listed in `collections`,\n which defaults to `[GraphKeys.GLOBAL_VARIABLES]`.\n\n If `trainable` is `True` the variable is also added to the graph collection\n `GraphKeys.TRAINABLE_VARIABLES`.\n\n This constructor creates both a `variable` Op and an `assign` Op to set the\n variable to its initial value.\n\n Args:\n initial_value: A `Tensor`, or Python object convertible to a `Tensor`,\n which is the initial value for the Variable. The initial value must have\n a shape specified unless `validate_shape` is set to False. Can also be a\n callable with no argument that returns the initial value when called. In\n that case, `dtype` must be specified. (Note that initializer functions\n from init_ops.py must first be bound to a shape before being used here.)\n trainable: If `True`, also adds the variable to the graph collection\n `GraphKeys.TRAINABLE_VARIABLES`. This collection is used as the default\n list of variables to use by the `Optimizer` classes. Defaults to `True`,\n unless `synchronization` is set to `ON_READ`, in which case it defaults\n to `False`.\n collections: List of graph collections keys. The new variable is added to\n these collections. Defaults to `[GraphKeys.GLOBAL_VARIABLES]`.\n validate_shape: If `False`, allows the variable to be initialized with a\n value of unknown shape. If `True`, the default, the shape of\n `initial_value` must be known.\n caching_device: Optional device string describing where the Variable\n should be cached for reading. Defaults to the Variable's device. If not\n `None`, caches on another device. Typical use is to cache on the device\n where the Ops using the Variable reside, to deduplicate copying through\n `Switch` and other conditional statements.\n name: Optional name for the variable. Defaults to `'Variable'` and gets\n uniquified automatically.\n variable_def: `VariableDef` protocol buffer. If not `None`, recreates the\n Variable object with its contents, referencing the variable's nodes in\n the graph, which must already exist. The graph is not changed.\n `variable_def` and the other arguments are mutually exclusive.\n dtype: If set, initial_value will be converted to the given type. If\n `None`, either the datatype will be kept (if `initial_value` is a\n Tensor), or `convert_to_tensor` will decide.\n expected_shape: A TensorShape. If set, initial_value is expected to have\n this shape.\n import_scope: Optional `string`. Name scope to add to the `Variable.` Only\n used when initializing from protocol buffer.\n constraint: An optional projection function to be applied to the variable\n after being updated by an `Optimizer` (e.g. used to implement norm\n constraints or value constraints for layer weights). The function must\n take as input the unprojected Tensor representing the value of the\n variable and return the Tensor for the projected value (which must have\n the same shape). Constraints are not safe to use when doing asynchronous\n distributed training.\n synchronization: Indicates when a distributed a variable will be\n aggregated. Accepted values are constants defined in the class\n `tf.VariableSynchronization`. By default the synchronization is set to\n `AUTO` and the current `DistributionStrategy` chooses when to\n synchronize.\n aggregation: Indicates how a distributed variable will be aggregated.\n Accepted values are constants defined in the class\n `tf.VariableAggregation`.\n shape: (optional) The shape of this variable. If None, the shape of\n `initial_value` will be used. When setting this argument to\n `tf.TensorShape(None)` (representing an unspecified shape), the variable\n can be assigned with values of different shapes.\n\n Raises:\n ValueError: If both `variable_def` and initial_value are specified.\n ValueError: If the initial value is not specified, or does not have a\n shape and `validate_shape` is `True`.\n RuntimeError: If eager execution is enabled.\n \"\"\"\n self._in_graph_mode = True\n if variable_def:\n # If variable_def is provided, recreates the variable from its fields.\n if initial_value:\n raise ValueError(\"variable_def and initial_value are mutually \"\n \"exclusive.\")\n self._init_from_proto(variable_def, import_scope=import_scope)\n else:\n # Create from initial_value.\n self._init_from_args(\n initial_value=initial_value,\n trainable=trainable,\n collections=collections,\n validate_shape=validate_shape,\n caching_device=caching_device,\n name=name,\n dtype=dtype,\n expected_shape=expected_shape,\n constraint=constraint,\n synchronization=synchronization,\n aggregation=aggregation,\n shape=shape)\n\n def __repr__(self):\n if context.executing_eagerly() and not self._in_graph_mode:\n return \"\" % (\n self.name, self.get_shape(), self.dtype.name,\n ops.numpy_text(self.read_value(), is_repr=True))\n else:\n return \"\" % (\n self.name, self.get_shape(), self.dtype.name)\n\n def _init_from_args(self,\n initial_value=None,\n trainable=None,\n collections=None,\n validate_shape=True,\n caching_device=None,\n name=None,\n dtype=None,\n expected_shape=None,\n constraint=None,\n synchronization=None,\n aggregation=None,\n shape=None):\n \"\"\"Creates a new variable from arguments.\n\n Args:\n initial_value: A `Tensor`, or Python object convertible to a `Tensor`,\n which is the initial value for the Variable. The initial value must have\n a shape specified unless `validate_shape` is set to False. Can also be a\n callable with no argument that returns the initial value when called.\n (Note that initializer functions from init_ops.py must first be bound to\n a shape before being used here.)\n trainable: If `True`, also adds the variable to the graph collection\n `GraphKeys.TRAINABLE_VARIABLES`. This collection is used as the default\n list of variables to use by the `Optimizer` classes. Defaults to `True`,\n unless `synchronization` is set to `ON_READ`, in which case it defaults\n to `False`.\n collections: List of graph collections keys. The new variable is added to\n these collections. Defaults to `[GraphKeys.GLOBAL_VARIABLES]`.\n validate_shape: If `False`, allows the variable to be initialized with a\n value of unknown shape. If `True`, the default, the shape of\n `initial_value` must be known.\n caching_device: Optional device string or function describing where the\n Variable should be cached for reading. Defaults to the Variable's\n device. If not `None`, caches on another device. Typical use is to\n cache on the device where the Ops using the Variable reside, to\n deduplicate copying through `Switch` and other conditional statements.\n name: Optional name for the variable. Defaults to `'Variable'` and gets\n uniquified automatically.\n dtype: If set, initial_value will be converted to the given type. If None,\n either the datatype will be kept (if initial_value is a Tensor) or\n float32 will be used (if it is a Python object convertible to a Tensor).\n expected_shape: Deprecated. Ignored.\n constraint: An optional projection function to be applied to the variable\n after being updated by an `Optimizer` (e.g. used to implement norm\n constraints or value constraints for layer weights). The function must\n take as input the unprojected Tensor representing the value of the\n variable and return the Tensor for the projected value (which must have\n the same shape). Constraints are not safe to use when doing asynchronous\n distributed training.\n synchronization: Indicates when a distributed a variable will be\n aggregated. Accepted values are constants defined in the class\n `tf.VariableSynchronization`. By default the synchronization is set to\n `AUTO` and the current `DistributionStrategy` chooses when to\n synchronize.\n aggregation: Indicates how a distributed variable will be aggregated.\n Accepted values are constants defined in the class\n `tf.VariableAggregation`.\n shape: (optional) The shape of this variable. If None, the shape of\n `initial_value` will be used. When setting this argument to\n `tf.TensorShape(None)` (representing an unspecified shape), the variable\n can be assigned with values of different shapes.\n\n Raises:\n ValueError: If the initial value is not specified, or does not have a\n shape and `validate_shape` is `True`.\n RuntimeError: If lifted into the eager context.\n \"\"\"\n _ = expected_shape\n if initial_value is None:\n raise ValueError(\"initial_value must be specified.\")\n init_from_fn = callable(initial_value)\n\n if collections is None:\n collections = [ops.GraphKeys.GLOBAL_VARIABLES]\n if not isinstance(collections, (list, tuple, set)):\n raise ValueError(\n \"collections argument to Variable constructor must be a list, tuple, \"\n \"or set. Got %s of type %s\" % (collections, type(collections)))\n if constraint is not None and not callable(constraint):\n raise ValueError(\"The `constraint` argument must be a callable.\")\n\n # Store the graph key so optimizers know how to only retrieve variables from\n # this graph.\n self._graph_key = ops.get_default_graph()._graph_key # pylint: disable=protected-access\n if isinstance(initial_value, trackable.CheckpointInitialValue):\n self._maybe_initialize_trackable()\n self._update_uid = initial_value.checkpoint_position.restore_uid\n initial_value = initial_value.wrapped_value\n\n synchronization, aggregation, trainable = (\n validate_synchronization_aggregation_trainable(synchronization,\n aggregation, trainable,\n name))\n self._synchronization = synchronization\n self._aggregation = aggregation\n self._trainable = trainable\n if trainable and ops.GraphKeys.TRAINABLE_VARIABLES not in collections:\n collections = list(collections) + [ops.GraphKeys.TRAINABLE_VARIABLES]\n with ops.init_scope():\n # Ensure that we weren't lifted into the eager context.\n if context.executing_eagerly():\n raise RuntimeError(\n \"RefVariable not supported when eager execution is enabled. \")\n with ops.name_scope(name, \"Variable\",\n [] if init_from_fn else [initial_value]) as name:\n\n if init_from_fn:\n # Use attr_scope and device(None) to simulate the behavior of\n # colocate_with when the variable we want to colocate with doesn't\n # yet exist.\n true_name = ops.name_from_scope_name(name) # pylint: disable=protected-access\n attr = attr_value_pb2.AttrValue(\n list=attr_value_pb2.AttrValue.ListValue(\n s=[compat.as_bytes(\"loc:@%s\" % true_name)]))\n # pylint: disable=protected-access\n with ops.get_default_graph()._attr_scope({\"_class\": attr}):\n with ops.name_scope(\"Initializer\"), ops.device(None):\n self._initial_value = ops.convert_to_tensor(\n initial_value(), name=\"initial_value\", dtype=dtype)\n if shape is None:\n shape = (\n self._initial_value.get_shape()\n if validate_shape else tensor_shape.unknown_shape())\n self._variable = state_ops.variable_op_v2(\n shape, self._initial_value.dtype.base_dtype, name=name)\n # pylint: enable=protected-access\n\n # Or get the initial value from a Tensor or Python object.\n else:\n self._initial_value = ops.convert_to_tensor(\n initial_value, name=\"initial_value\", dtype=dtype)\n # pylint: disable=protected-access\n if self._initial_value.op._get_control_flow_context() is not None:\n raise ValueError(\n \"Initializer for variable %s is from inside a control-flow \"\n \"construct, such as a loop or conditional. When creating a \"\n \"variable inside a loop or conditional, use a lambda as the \"\n \"initializer.\" % name)\n if shape is None:\n # pylint: enable=protected-access\n shape = (\n self._initial_value.get_shape()\n if validate_shape else tensor_shape.unknown_shape())\n # In this case, the variable op can't be created until after the\n # initial_value has been converted to a Tensor with a known type.\n self._variable = state_ops.variable_op_v2(\n shape, self._initial_value.dtype.base_dtype, name=name)\n self._is_sparse=False\n\n # Manually overrides the variable's shape with the initial value's.\n if validate_shape:\n initial_value_shape = self._initial_value.get_shape()\n if not initial_value_shape.is_fully_defined():\n raise ValueError(\"initial_value must have a shape specified: %s\" %\n self._initial_value)\n\n # If 'initial_value' makes use of other variables, make sure we don't\n # have an issue if these other variables aren't initialized first by\n # using their initialized_value() method.\n self._initializer_op = state_ops.assign(\n self._variable,\n _try_guard_against_uninitialized_dependencies(\n name, self._initial_value),\n validate_shape=validate_shape).op\n\n # TODO(vrv): Change this class to not take caching_device, but\n # to take the op to colocate the snapshot with, so we can use\n # colocation rather than devices.\n if caching_device is not None:\n with ops.device(caching_device):\n self._snapshot = array_ops.identity(self._variable, name=\"read\")\n else:\n with ops.colocate_with(self._variable.op):\n self._snapshot = array_ops.identity(self._variable, name=\"read\")\n ops.add_to_collections(collections, self)\n\n self._caching_device = caching_device\n self._save_slice_info = None\n self._constraint = constraint\n\n def _init_from_proto(self, variable_def, import_scope=None):\n \"\"\"Recreates the Variable object from a `VariableDef` protocol buffer.\n\n Args:\n variable_def: `VariableDef` protocol buffer, describing a variable whose\n nodes already exists in the graph.\n import_scope: Optional `string`. Name scope to add.\n \"\"\"\n assert isinstance(variable_def, variable_pb2.VariableDef)\n # Create from variable_def.\n g = ops.get_default_graph()\n self._variable = g.as_graph_element(\n ops.prepend_name_scope(\n variable_def.variable_name, import_scope=import_scope))\n self._initializer_op = g.as_graph_element(\n ops.prepend_name_scope(\n variable_def.initializer_name, import_scope=import_scope))\n # Tests whether initial_value_name exists first for backwards compatibility.\n if (hasattr(variable_def, \"initial_value_name\") and\n variable_def.initial_value_name):\n self._initial_value = g.as_graph_element(\n ops.prepend_name_scope(\n variable_def.initial_value_name, import_scope=import_scope))\n else:\n self._initial_value = None\n synchronization, aggregation, trainable = (\n validate_synchronization_aggregation_trainable(\n variable_def.synchronization, variable_def.aggregation,\n variable_def.trainable, variable_def.variable_name))\n self._synchronization = synchronization\n self._aggregation = aggregation\n self._trainable = trainable\n self._snapshot = g.as_graph_element(\n ops.prepend_name_scope(\n variable_def.snapshot_name, import_scope=import_scope))\n if variable_def.HasField(\"save_slice_info_def\"):\n self._save_slice_info = Variable.SaveSliceInfo(\n save_slice_info_def=variable_def.save_slice_info_def,\n import_scope=import_scope)\n else:\n self._save_slice_info = None\n self._caching_device = None\n self._constraint = None\n self._is_sparse=False\n\n def _as_graph_element(self):\n \"\"\"Conversion function for Graph.as_graph_element().\"\"\"\n return self._variable\n\n def value(self):\n \"\"\"Returns the last snapshot of this variable.\n\n You usually do not need to call this method as all ops that need the value\n of the variable call it automatically through a `convert_to_tensor()` call.\n\n Returns a `Tensor` which holds the value of the variable. You can not\n assign a new value to this tensor as it is not a reference to the variable.\n\n To avoid copies, if the consumer of the returned value is on the same device\n as the variable, this actually returns the live value of the variable, not\n a copy. Updates to the variable are seen by the consumer. If the consumer\n is on a different device it will get a copy of the variable.\n\n Returns:\n A `Tensor` containing the value of the variable.\n \"\"\"\n return self._snapshot\n\n def read_value(self):\n \"\"\"Returns the value of this variable, read in the current context.\n\n Can be different from value() if it's on another device, with control\n dependencies, etc.\n\n Returns:\n A `Tensor` containing the value of the variable.\n \"\"\"\n return array_ops.identity(self._variable, name=\"read\")\n\n def _ref(self):\n \"\"\"Returns a reference to this variable.\n\n You usually do not need to call this method as all ops that need a reference\n to the variable call it automatically.\n\n Returns is a `Tensor` which holds a reference to the variable. You can\n assign a new value to the variable by passing the tensor to an assign op.\n See `tf.Variable.value` if you want to get the value of the\n variable.\n\n Returns:\n A `Tensor` that is a reference to the variable.\n \"\"\"\n return self._variable\n\n def set_shape(self, shape):\n \"\"\"Overrides the shape for this variable.\n\n Args:\n shape: the `TensorShape` representing the overridden shape.\n \"\"\"\n self._ref().set_shape(shape)\n self.value().set_shape(shape)\n\n @property\n def trainable(self):\n return self._trainable\n\n @property\n def synchronization(self):\n return self._synchronization\n\n @property\n def aggregation(self):\n return self._aggregation\n\n def eval(self, session=None):\n \"\"\"In a session, computes and returns the value of this variable.\n\n This is not a graph construction method, it does not add ops to the graph.\n\n This convenience method requires a session where the graph\n containing this variable has been launched. If no session is\n passed, the default session is used. See `tf.compat.v1.Session` for more\n information on launching a graph and on sessions.\n\n ```python\n v = tf.Variable([1, 2])\n init = tf.compat.v1.global_variables_initializer()\n\n with tf.compat.v1.Session() as sess:\n sess.run(init)\n # Usage passing the session explicitly.\n print(v.eval(sess))\n # Usage with the default session. The 'with' block\n # above makes 'sess' the default session.\n print(v.eval())\n ```\n\n Args:\n session: The session to use to evaluate this variable. If none, the\n default session is used.\n\n Returns:\n A numpy `ndarray` with a copy of the value of this variable.\n \"\"\"\n return self._variable.eval(session=session)\n\n @property\n def initial_value(self):\n \"\"\"Returns the Tensor used as the initial value for the variable.\n\n Note that this is different from `initialized_value()` which runs\n the op that initializes the variable before returning its value.\n This method returns the tensor that is used by the op that initializes\n the variable.\n\n Returns:\n A `Tensor`.\n \"\"\"\n return self._initial_value\n\n @property\n def constraint(self):\n \"\"\"Returns the constraint function associated with this variable.\n\n Returns:\n The constraint function that was passed to the variable constructor.\n Can be `None` if no constraint was passed.\n \"\"\"\n return self._constraint\n\n def assign(self, value, use_locking=False, name=None, read_value=True):\n \"\"\"Assigns a new value to the variable.\n\n This is essentially a shortcut for `assign(self, value)`.\n\n Args:\n value: A `Tensor`. The new value for this variable.\n use_locking: If `True`, use locking during the assignment.\n name: The name of the operation to be created\n read_value: if True, will return something which evaluates to the new\n value of the variable; if False will return the assign op.\n\n Returns:\n A `Tensor` that will hold the new value of this variable after\n the assignment has completed.\n \"\"\"\n assign = state_ops.assign(\n self._variable, value, use_locking=use_locking, name=name)\n if read_value:\n return assign\n return assign.op\n\n def assign_add(self, delta, use_locking=False, name=None, read_value=True):\n \"\"\"Adds a value to this variable.\n\n This is essentially a shortcut for `assign_add(self, delta)`.\n\n Args:\n delta: A `Tensor`. The value to add to this variable.\n use_locking: If `True`, use locking during the operation.\n name: The name of the operation to be created\n read_value: if True, will return something which evaluates to the new\n value of the variable; if False will return the assign op.\n\n Returns:\n A `Tensor` that will hold the new value of this variable after\n the addition has completed.\n \"\"\"\n assign = state_ops.assign_add(\n self._variable, delta, use_locking=use_locking, name=name)\n if read_value:\n return assign\n return assign.op\n\n def assign_sub(self, delta, use_locking=False, name=None, read_value=True):\n \"\"\"Subtracts a value from this variable.\n\n This is essentially a shortcut for `assign_sub(self, delta)`.\n\n Args:\n delta: A `Tensor`. The value to subtract from this variable.\n use_locking: If `True`, use locking during the operation.\n name: The name of the operation to be created\n read_value: if True, will return something which evaluates to the new\n value of the variable; if False will return the assign op.\n\n Returns:\n A `Tensor` that will hold the new value of this variable after\n the subtraction has completed.\n \"\"\"\n assign = state_ops.assign_sub(\n self._variable, delta, use_locking=use_locking, name=name)\n if read_value:\n return assign\n return assign.op\n\n def scatter_sub(self, sparse_delta, use_locking=False, name=None):\n \"\"\"Subtracts `tf.IndexedSlices` from this variable.\n\n Args:\n sparse_delta: `tf.IndexedSlices` to be subtracted from this variable.\n use_locking: If `True`, use locking during the operation.\n name: the name of the operation.\n\n Returns:\n A `Tensor` that will hold the new value of this variable after\n the scattered subtraction has completed.\n\n Raises:\n TypeError: if `sparse_delta` is not an `IndexedSlices`.\n \"\"\"\n if not isinstance(sparse_delta, ops.IndexedSlices):\n raise TypeError(\"sparse_delta is not IndexedSlices: %s\" % sparse_delta)\n return gen_state_ops.scatter_sub(\n self._variable,\n sparse_delta.indices,\n sparse_delta.values,\n use_locking=use_locking,\n name=name)\n\n def scatter_add(self, sparse_delta, use_locking=False, name=None):\n \"\"\"Adds `tf.IndexedSlices` to this variable.\n\n Args:\n sparse_delta: `tf.IndexedSlices` to be added to this variable.\n use_locking: If `True`, use locking during the operation.\n name: the name of the operation.\n\n Returns:\n A `Tensor` that will hold the new value of this variable after\n the scattered addition has completed.\n\n Raises:\n TypeError: if `sparse_delta` is not an `IndexedSlices`.\n \"\"\"\n if not isinstance(sparse_delta, ops.IndexedSlices):\n raise TypeError(\"sparse_delta is not IndexedSlices: %s\" % sparse_delta)\n return gen_state_ops.scatter_add(\n self._variable,\n sparse_delta.indices,\n sparse_delta.values,\n use_locking=use_locking,\n name=name)\n\n def scatter_max(self, sparse_delta, use_locking=False, name=None):\n \"\"\"Updates this variable with the max of `tf.IndexedSlices` and itself.\n\n Args:\n sparse_delta: `tf.IndexedSlices` to use as an argument of max with this\n variable.\n use_locking: If `True`, use locking during the operation.\n name: the name of the operation.\n\n Returns:\n A `Tensor` that will hold the new value of this variable after\n the scattered maximization has completed.\n\n Raises:\n TypeError: if `sparse_delta` is not an `IndexedSlices`.\n \"\"\"\n if not isinstance(sparse_delta, ops.IndexedSlices):\n raise TypeError(\"sparse_delta is not IndexedSlices: %s\" % sparse_delta)\n return gen_state_ops.scatter_max(\n self._variable,\n sparse_delta.indices,\n sparse_delta.values,\n use_locking=use_locking,\n name=name)\n\n def scatter_min(self, sparse_delta, use_locking=False, name=None):\n \"\"\"Updates this variable with the min of `tf.IndexedSlices` and itself.\n\n Args:\n sparse_delta: `tf.IndexedSlices` to use as an argument of min with this\n variable.\n use_locking: If `True`, use locking during the operation.\n name: the name of the operation.\n\n Returns:\n A `Tensor` that will hold the new value of this variable after\n the scattered minimization has completed.\n\n Raises:\n TypeError: if `sparse_delta` is not an `IndexedSlices`.\n \"\"\"\n if not isinstance(sparse_delta, ops.IndexedSlices):\n raise TypeError(\"sparse_delta is not IndexedSlices: %s\" % sparse_delta)\n return gen_state_ops.scatter_min(\n self._variable,\n sparse_delta.indices,\n sparse_delta.values,\n use_locking=use_locking,\n name=name)\n\n def scatter_mul(self, sparse_delta, use_locking=False, name=None):\n \"\"\"Multiply this variable by `tf.IndexedSlices`.\n\n Args:\n sparse_delta: `tf.IndexedSlices` to multiply this variable by.\n use_locking: If `True`, use locking during the operation.\n name: the name of the operation.\n\n Returns:\n A `Tensor` that will hold the new value of this variable after\n the scattered multiplication has completed.\n\n Raises:\n TypeError: if `sparse_delta` is not an `IndexedSlices`.\n \"\"\"\n if not isinstance(sparse_delta, ops.IndexedSlices):\n raise TypeError(\"sparse_delta is not IndexedSlices: %s\" % sparse_delta)\n return gen_state_ops.scatter_mul(\n self._variable,\n sparse_delta.indices,\n sparse_delta.values,\n use_locking=use_locking,\n name=name)\n\n def scatter_div(self, sparse_delta, use_locking=False, name=None):\n \"\"\"Divide this variable by `tf.IndexedSlices`.\n\n Args:\n sparse_delta: `tf.IndexedSlices` to divide this variable by.\n use_locking: If `True`, use locking during the operation.\n name: the name of the operation.\n\n Returns:\n A `Tensor` that will hold the new value of this variable after\n the scattered division has completed.\n\n Raises:\n TypeError: if `sparse_delta` is not an `IndexedSlices`.\n \"\"\"\n if not isinstance(sparse_delta, ops.IndexedSlices):\n raise TypeError(\"sparse_delta is not IndexedSlices: %s\" % sparse_delta)\n return gen_state_ops.scatter_div(\n self._variable,\n sparse_delta.indices,\n sparse_delta.values,\n use_locking=use_locking,\n name=name)\n\n def scatter_update(self, sparse_delta, use_locking=False, name=None):\n \"\"\"Assigns `tf.IndexedSlices` to this variable.\n\n Args:\n sparse_delta: `tf.IndexedSlices` to be assigned to this variable.\n use_locking: If `True`, use locking during the operation.\n name: the name of the operation.\n\n Returns:\n A `Tensor` that will hold the new value of this variable after\n the scattered assignment has completed.\n\n Raises:\n TypeError: if `sparse_delta` is not an `IndexedSlices`.\n \"\"\"\n if not isinstance(sparse_delta, ops.IndexedSlices):\n raise TypeError(\"sparse_delta is not IndexedSlices: %s\" % sparse_delta)\n return gen_state_ops.scatter_update(\n self._variable,\n sparse_delta.indices,\n sparse_delta.values,\n use_locking=use_locking,\n name=name)\n\n def batch_scatter_update(self, sparse_delta, use_locking=False, name=None):\n \"\"\"Assigns `tf.IndexedSlices` to this variable batch-wise.\n\n Analogous to `batch_gather`. This assumes that this variable and the\n sparse_delta IndexedSlices have a series of leading dimensions that are the\n same for all of them, and the updates are performed on the last dimension of\n indices. In other words, the dimensions should be the following:\n\n `num_prefix_dims = sparse_delta.indices.ndims - 1`\n `batch_dim = num_prefix_dims + 1`\n `sparse_delta.updates.shape = sparse_delta.indices.shape + var.shape[\n batch_dim:]`\n\n where\n\n `sparse_delta.updates.shape[:num_prefix_dims]`\n `== sparse_delta.indices.shape[:num_prefix_dims]`\n `== var.shape[:num_prefix_dims]`\n\n And the operation performed can be expressed as:\n\n `var[i_1, ..., i_n,\n sparse_delta.indices[i_1, ..., i_n, j]] = sparse_delta.updates[\n i_1, ..., i_n, j]`\n\n When sparse_delta.indices is a 1D tensor, this operation is equivalent to\n `scatter_update`.\n\n To avoid this operation one can looping over the first `ndims` of the\n variable and using `scatter_update` on the subtensors that result of slicing\n the first dimension. This is a valid option for `ndims = 1`, but less\n efficient than this implementation.\n\n Args:\n sparse_delta: `tf.IndexedSlices` to be assigned to this variable.\n use_locking: If `True`, use locking during the operation.\n name: the name of the operation.\n\n Returns:\n A `Tensor` that will hold the new value of this variable after\n the scattered assignment has completed.\n\n Raises:\n TypeError: if `sparse_delta` is not an `IndexedSlices`.\n \"\"\"\n return state_ops.batch_scatter_update(\n self,\n sparse_delta.indices,\n sparse_delta.values,\n use_locking=use_locking,\n name=name)\n\n def scatter_nd_sub(self, indices, updates, name=None):\n \"\"\"Applies sparse subtraction to individual values or slices in a Variable.\n\n `ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`.\n\n `indices` must be integer tensor, containing indices into `ref`.\n It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`.\n\n The innermost dimension of `indices` (with length `K`) corresponds to\n indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th\n dimension of `ref`.\n\n `updates` is `Tensor` of rank `Q-1+P-K` with shape:\n\n ```\n [d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]].\n ```\n\n For example, say we want to add 4 scattered elements to a rank-1 tensor to\n 8 elements. In Python, that update would look like this:\n\n ```python\n ref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8])\n indices = tf.constant([[4], [3], [1] ,[7]])\n updates = tf.constant([9, 10, 11, 12])\n op = ref.scatter_nd_sub(indices, updates)\n with tf.compat.v1.Session() as sess:\n print sess.run(op)\n ```\n\n The resulting update to ref would look like this:\n\n [1, -9, 3, -6, -6, 6, 7, -4]\n\n See `tf.scatter_nd` for more details about how to make updates to\n slices.\n\n Args:\n indices: The indices to be used in the operation.\n updates: The values to be used in the operation.\n name: the name of the operation.\n\n Returns:\n A `Tensor` that will hold the new value of this variable after\n the scattered subtraction has completed.\n \"\"\"\n return gen_state_ops.scatter_nd_sub(\n self._variable, indices, updates, use_locking=True, name=name)\n\n def scatter_nd_add(self, indices, updates, name=None):\n \"\"\"Applies sparse addition to individual values or slices in a Variable.\n\n `ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`.\n\n `indices` must be integer tensor, containing indices into `ref`.\n It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`.\n\n The innermost dimension of `indices` (with length `K`) corresponds to\n indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th\n dimension of `ref`.\n\n `updates` is `Tensor` of rank `Q-1+P-K` with shape:\n\n ```\n [d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]].\n ```\n\n For example, say we want to add 4 scattered elements to a rank-1 tensor to\n 8 elements. In Python, that update would look like this:\n\n ```python\n ref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8])\n indices = tf.constant([[4], [3], [1] ,[7]])\n updates = tf.constant([9, 10, 11, 12])\n add = ref.scatter_nd_add(indices, updates)\n with tf.compat.v1.Session() as sess:\n print sess.run(add)\n ```\n\n The resulting update to ref would look like this:\n\n [1, 13, 3, 14, 14, 6, 7, 20]\n\n See `tf.scatter_nd` for more details about how to make updates to\n slices.\n\n Args:\n indices: The indices to be used in the operation.\n updates: The values to be used in the operation.\n name: the name of the operation.\n\n Returns:\n A `Tensor` that will hold the new value of this variable after\n the scattered addition has completed.\n \"\"\"\n return gen_state_ops.scatter_nd_add(\n self._variable, indices, updates, use_locking=True, name=name)\n\n def scatter_nd_update(self, indices, updates, name=None):\n \"\"\"Applies sparse assignment to individual values or slices in a Variable.\n\n `ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`.\n\n `indices` must be integer tensor, containing indices into `ref`.\n It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`.\n\n The innermost dimension of `indices` (with length `K`) corresponds to\n indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th\n dimension of `ref`.\n\n `updates` is `Tensor` of rank `Q-1+P-K` with shape:\n\n ```\n [d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]].\n ```\n\n For example, say we want to add 4 scattered elements to a rank-1 tensor to\n 8 elements. In Python, that update would look like this:\n\n ```python\n ref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8])\n indices = tf.constant([[4], [3], [1] ,[7]])\n updates = tf.constant([9, 10, 11, 12])\n op = ref.scatter_nd_update(indices, updates)\n with tf.compat.v1.Session() as sess:\n print sess.run(op)\n ```\n\n The resulting update to ref would look like this:\n\n [1, 11, 3, 10, 9, 6, 7, 12]\n\n See `tf.scatter_nd` for more details about how to make updates to\n slices.\n\n Args:\n indices: The indices to be used in the operation.\n updates: The values to be used in the operation.\n name: the name of the operation.\n\n Returns:\n A `Tensor` that will hold the new value of this variable after\n the scattered assignment has completed.\n \"\"\"\n return gen_state_ops.scatter_nd_update(\n self._variable, indices, updates, use_locking=True, name=name)\n\n def _strided_slice_assign(self, begin, end, strides, value, name, begin_mask,\n end_mask, ellipsis_mask, new_axis_mask,\n shrink_axis_mask):\n return gen_array_ops.strided_slice_assign(\n ref=self._ref(),\n begin=begin,\n end=end,\n strides=strides,\n value=value,\n name=name,\n begin_mask=begin_mask,\n end_mask=end_mask,\n ellipsis_mask=ellipsis_mask,\n new_axis_mask=new_axis_mask,\n shrink_axis_mask=shrink_axis_mask)\n\n @deprecated(None, \"Prefer Dataset.range instead.\")\n def count_up_to(self, limit):\n \"\"\"Increments this variable until it reaches `limit`.\n\n When that Op is run it tries to increment the variable by `1`. If\n incrementing the variable would bring it above `limit` then the Op raises\n the exception `OutOfRangeError`.\n\n If no error is raised, the Op outputs the value of the variable before\n the increment.\n\n This is essentially a shortcut for `count_up_to(self, limit)`.\n\n Args:\n limit: value at which incrementing the variable raises an error.\n\n Returns:\n A `Tensor` that will hold the variable value before the increment. If no\n other Op modifies this variable, the values produced will all be\n distinct.\n \"\"\"\n return state_ops.count_up_to(self._variable, limit=limit)\n\n # Conversion to tensor.\n @staticmethod\n def _TensorConversionFunction(v, dtype=None, name=None, as_ref=False): # pylint: disable=invalid-name\n \"\"\"Utility function for converting a Variable to a Tensor.\"\"\"\n _ = name\n if dtype and not dtype.is_compatible_with(v.dtype):\n raise ValueError(\n \"Incompatible type conversion requested to type '%s' for variable \"\n \"of type '%s'\" % (dtype.name, v.dtype.name))\n if as_ref:\n return v._ref() # pylint: disable=protected-access\n else:\n return v.value()\n\n # NOTE(mrry): This enables the Variable's overloaded \"right\" binary\n # operators to run when the left operand is an ndarray, because it\n # accords the Variable class higher priority than an ndarray, or a\n # numpy matrix.\n # TODO(mrry): Convert this to using numpy's __numpy_ufunc__\n # mechanism, which allows more control over how Variables interact\n # with ndarrays.\n __array_priority__ = 100\n\n @property\n def name(self):\n \"\"\"The name of this variable.\"\"\"\n return self._variable.name\n\n @property\n def initializer(self):\n \"\"\"The initializer operation for this variable.\"\"\"\n return self._initializer_op\n\n @property\n def device(self):\n \"\"\"The device of this variable.\"\"\"\n return self._variable.device\n\n @property\n def dtype(self):\n \"\"\"The `DType` of this variable.\"\"\"\n return self._variable.dtype\n\n @property\n def op(self):\n \"\"\"The `Operation` of this variable.\"\"\"\n return self._variable.op\n\n @property\n def graph(self):\n \"\"\"The `Graph` of this variable.\"\"\"\n return self._variable.graph\n\n @property\n def _distribute_strategy(self):\n \"\"\"The `tf.distribute.Strategy` that this variable was created under.\"\"\"\n return None # Ref variables are never created inside a strategy.\n\n @property\n def shape(self):\n \"\"\"The `TensorShape` of this variable.\n\n Returns:\n A `TensorShape`.\n \"\"\"\n return self._variable.get_shape()\n\n def to_proto(self, export_scope=None):\n \"\"\"Converts a `Variable` to a `VariableDef` protocol buffer.\n\n Args:\n export_scope: Optional `string`. Name scope to remove.\n\n Returns:\n A `VariableDef` protocol buffer, or `None` if the `Variable` is not\n in the specified name scope.\n \"\"\"\n if (export_scope is None or self._variable.name.startswith(export_scope)):\n var_def = variable_pb2.VariableDef()\n var_def.variable_name = ops.strip_name_scope(self._variable.name,\n export_scope)\n if self._initial_value is not None:\n # For backwards compatibility.\n var_def.initial_value_name = ops.strip_name_scope(\n self._initial_value.name, export_scope)\n var_def.trainable = self.trainable\n var_def.synchronization = self.synchronization.value\n var_def.aggregation = self.aggregation.value\n var_def.initializer_name = ops.strip_name_scope(self.initializer.name,\n export_scope)\n var_def.snapshot_name = ops.strip_name_scope(self._snapshot.name,\n export_scope)\n if self._save_slice_info:\n var_def.save_slice_info_def.MergeFrom(\n self._save_slice_info.to_proto(export_scope=export_scope))\n return var_def\n else:\n return None\n\n def __iadd__(self, other):\n logging.log_first_n(\n logging.WARN, \"Variable += will be deprecated. Use variable.assign_add\"\n \" if you want assignment to the variable value or 'x = x + y'\"\n \" if you want a new python Tensor object.\", 1)\n return self + other\n\n def __isub__(self, other):\n logging.log_first_n(\n logging.WARN, \"Variable -= will be deprecated. Use variable.assign_sub\"\n \" if you want assignment to the variable value or 'x = x - y'\"\n \" if you want a new python Tensor object.\", 1)\n return self - other\n\n def __imul__(self, other):\n logging.log_first_n(\n logging.WARN,\n \"Variable *= will be deprecated. Use `var.assign(var * other)`\"\n \" if you want assignment to the variable value or `x = x * y`\"\n \" if you want a new python Tensor object.\", 1)\n return self * other\n\n def __idiv__(self, other):\n logging.log_first_n(\n logging.WARN,\n \"Variable /= will be deprecated. Use `var.assign(var / other)`\"\n \" if you want assignment to the variable value or `x = x / y`\"\n \" if you want a new python Tensor object.\", 1)\n return self / other\n\n def __itruediv__(self, other):\n logging.log_first_n(\n logging.WARN,\n \"Variable /= will be deprecated. Use `var.assign(var / other)`\"\n \" if you want assignment to the variable value or `x = x / y`\"\n \" if you want a new python Tensor object.\", 1)\n return self / other\n\n def __irealdiv__(self, other):\n logging.log_first_n(\n logging.WARN,\n \"Variable /= will be deprecated. Use `var.assign(var / other)`\"\n \" if you want assignment to the variable value or `x = x / y`\"\n \" if you want a new python Tensor object.\", 1)\n return self / other\n\n def __ipow__(self, other):\n logging.log_first_n(\n logging.WARN,\n \"Variable **= will be deprecated. Use `var.assign(var ** other)`\"\n \" if you want assignment to the variable value or `x = x ** y`\"\n \" if you want a new python Tensor object.\", 1)\n return self**other\n\n\ndef _try_guard_against_uninitialized_dependencies(name, initial_value):\n \"\"\"Attempt to guard against dependencies on uninitialized variables.\n\n Replace references to variables in `initial_value` with references to the\n variable's initialized values. The initialized values are essentially\n conditional TensorFlow graphs that return a variable's value if it is\n initialized or its `initial_value` if it hasn't been initialized. This\n replacement is done on a best effort basis:\n\n - If the `initial_value` graph contains cycles, we don't do any\n replacements for that graph.\n - If the variables that `initial_value` depends on are not present in the\n `GLOBAL_VARIABLES` or `LOCAL_VARIABLES` we don't replace them.\n\n In these cases, it is up to the caller to ensure that the `initial_value`\n graph uses initialized variables or that they guard access to variables\n using their `initialized_value` method.\n\n Args:\n name: Variable name.\n initial_value: `Tensor`. The initial value.\n\n Returns:\n A `Tensor` suitable to initialize a variable.\n Raises:\n TypeError: If `initial_value` is not a `Tensor`.\n \"\"\"\n if not isinstance(initial_value, ops.Tensor):\n raise TypeError(\"initial_value needs to be a Tensor: %s\" % initial_value)\n\n # Don't modify initial_value if it contains any cyclic dependencies.\n if _has_cycle(initial_value.op, state={}):\n return initial_value\n return _safe_initial_value_from_tensor(name, initial_value, op_cache={})\n\n\n_UNKNOWN, _STARTED, _FINISHED = range(3)\n\n\ndef _has_cycle(op, state):\n \"\"\"Detect cycles in the dependencies of `initial_value`.\"\"\"\n op_state = state.get(op.name, _UNKNOWN)\n if op_state == _STARTED:\n return True\n elif op_state == _FINISHED:\n return False\n\n state[op.name] = _STARTED\n for i in itertools.chain((i.op for i in op.inputs), op.control_inputs):\n if _has_cycle(i, state):\n return True\n state[op.name] = _FINISHED\n return False\n\n\ndef _safe_initial_value_from_tensor(name, tensor, op_cache):\n \"\"\"Replace dependencies on variables with their initialized values.\n\n Args:\n name: Variable name.\n tensor: A `Tensor`. The tensor to replace.\n op_cache: A dict mapping operation names to `Operation`s. Used to memoize\n the results so as to avoid creating redundant operations.\n\n Returns:\n A `Tensor` compatible with `tensor`. Any inputs that lead to variable\n values will be replaced with a corresponding graph that uses the\n variable's initialized values. This is done on a best-effort basis. If no\n modifications need to be made then `tensor` will be returned unchanged.\n \"\"\"\n op = tensor.op\n new_op = op_cache.get(op.name)\n if new_op is None:\n new_op = _safe_initial_value_from_op(name, op, op_cache)\n op_cache[op.name] = new_op\n return new_op.outputs[tensor.value_index]\n\n\ndef _safe_initial_value_from_op(name, op, op_cache):\n \"\"\"Replace dependencies on variables with their initialized values.\n\n Args:\n name: Variable name.\n op: An `Operation`. The operation to replace.\n op_cache: A dict mapping operation names to `Operation`s. Used to memoize\n the results so as to avoid creating redundant operations.\n\n Returns:\n An `Operation` compatible with `op`. Any inputs that lead to variable\n values will be replaced with a corresponding graph that uses the\n variable's initialized values. This is done on a best-effort basis. If no\n modifications need to be made then `op` will be returned unchanged.\n \"\"\"\n op_type = op.node_def.op\n if op_type in (\"IsVariableInitialized\", \"VarIsInitializedOp\",\n \"ReadVariableOp\", \"If\"):\n return op\n\n # Attempt to find the initialized_value of any variable reference / handles.\n # TODO(b/70206927): Fix handling of ResourceVariables.\n if op_type in (\"Variable\", \"VariableV2\", \"VarHandleOp\"):\n initialized_value = _find_initialized_value_for_variable(op)\n return op if initialized_value is None else initialized_value.op\n\n # Recursively build initializer expressions for inputs.\n modified = False\n new_op_inputs = []\n for op_input in op.inputs:\n new_op_input = _safe_initial_value_from_tensor(name, op_input, op_cache)\n new_op_inputs.append(new_op_input)\n modified = modified or (new_op_input != op_input)\n\n # If at least one input was modified, replace the op.\n if modified:\n new_op_type = op_type\n if new_op_type == \"RefSwitch\":\n new_op_type = \"Switch\"\n new_op_name = op.node_def.name + \"_\" + name\n new_op_name = new_op_name.replace(\":\", \"_\")\n return op.graph.create_op(\n new_op_type,\n new_op_inputs,\n op._output_types, # pylint: disable=protected-access\n name=new_op_name,\n attrs=op.node_def.attr)\n\n return op\n\n\ndef _find_initialized_value_for_variable(variable_op):\n \"\"\"Find the initialized value for a variable op.\n\n To do so, lookup the variable op in the variables collection.\n\n Args:\n variable_op: A variable `Operation`.\n\n Returns:\n A `Tensor` representing the initialized value for the variable or `None`\n if the initialized value could not be found.\n \"\"\"\n try:\n var_names = [variable_op.node_def.name, variable_op.node_def.name + \":0\"]\n for collection_name in (ops.GraphKeys.GLOBAL_VARIABLES,\n ops.GraphKeys.LOCAL_VARIABLES):\n for var in variable_op.graph.get_collection(collection_name):\n if var.name in var_names:\n return var.initialized_value()\n except AttributeError:\n # Return None when an incomplete user-defined variable type was put in\n # the collection.\n return None\n return None\n\n\nclass PartitionedVariable(object):\n \"\"\"A container for partitioned `Variable` objects.\n\n @compatibility(eager) `tf.PartitionedVariable` is not compatible with\n eager execution. Use `tf.Variable` instead which is compatible\n with both eager execution and graph construction. See [the\n TensorFlow Eager Execution\n guide](https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/eager/python/g3doc/guide.md#variables-and-optimizers)\n for details on how variables work in eager execution.\n @end_compatibility\n \"\"\"\n\n def __init__(self, name, shape, dtype, variable_list, partitions):\n \"\"\"Creates a new partitioned variable wrapper.\n\n Variables passed via the variable_list must contain a save_slice_info\n field. Concatenation and iteration is in lexicographic order according\n to the var_offset property of the save_slice_info.\n\n Args:\n name: String. Overall name of the variables.\n shape: List of integers. Overall shape of the variables.\n dtype: Type of the variables.\n variable_list: List of `Variable` that comprise this partitioned variable.\n partitions: List of integers. Number of partitions for each dimension.\n\n Raises:\n TypeError: If `variable_list` is not a list of `Variable` objects, or\n `partitions` is not a list.\n ValueError: If `variable_list` is empty, or the `Variable` shape\n information does not match `shape`, or `partitions` has invalid values.\n \"\"\"\n if not isinstance(variable_list, (list, tuple)):\n raise TypeError(\"variable_list is not a list or tuple: %s\" %\n variable_list)\n if not isinstance(partitions, (list, tuple)):\n raise TypeError(\"partitions is not a list or tuple: %s\" % partitions)\n if not all(p >= 1 for p in partitions):\n raise ValueError(\"partition values must be positive: %s\" % partitions)\n if not variable_list:\n raise ValueError(\"variable_list may not be empty\")\n # pylint: disable=protected-access\n for v in variable_list:\n # Sort the variable_list lexicographically according to var offset value.\n if not all(v._get_save_slice_info() is not None for v in variable_list):\n raise ValueError(\n \"All variables must have a save_slice_info available: %s\" %\n [v.name for v in variable_list])\n if len(shape) != len(partitions):\n raise ValueError(\"len(shape) != len(partitions): %s vs. %s\" %\n (shape, partitions))\n if v._get_save_slice_info().full_shape != shape:\n raise ValueError(\"All variables' full shapes must match shape: %s; \"\n \"but full shapes were: %s\" %\n (shape, str([v._get_save_slice_info().full_shape])))\n self._variable_list = sorted(\n variable_list, key=lambda v: v._get_save_slice_info().var_offset)\n # pylint: enable=protected-access\n\n self._name = name\n self._shape = shape\n self._dtype = dtype\n self._partitions = partitions\n self._as_tensor = None\n\n def __iter__(self):\n \"\"\"Return an iterable for accessing the underlying partition Variables.\"\"\"\n return iter(self._variable_list)\n\n def __len__(self):\n num_partition_axes = len(self._partition_axes())\n if num_partition_axes > 1:\n raise ValueError(\"Cannot get a length for %d > 1 partition axes\" %\n num_partition_axes)\n return len(self._variable_list)\n\n def _partition_axes(self):\n if all(p == 1 for p in self._partitions):\n return [0]\n else:\n return [i for i, p in enumerate(self._partitions) if p > 1]\n\n def _concat(self):\n \"\"\"Returns the overall concatenated value as a `Tensor`.\n\n This is different from using the partitioned variable directly as a tensor\n (through tensor conversion and `as_tensor`) in that it creates a new set of\n operations that keeps the control dependencies from its scope.\n\n Returns:\n `Tensor` containing the concatenated value.\n \"\"\"\n if len(self._variable_list) == 1:\n with ops.name_scope(None):\n return array_ops.identity(self._variable_list[0], name=self._name)\n\n partition_axes = self._partition_axes()\n\n if len(partition_axes) > 1:\n raise NotImplementedError(\n \"Cannot concatenate along more than one dimension: %s. \"\n \"Multi-axis partition concat is not supported\" % str(partition_axes))\n partition_ix = partition_axes[0]\n\n with ops.name_scope(self._name + \"/ConcatPartitions/\"):\n concatenated = array_ops.concat(self._variable_list, partition_ix)\n\n with ops.name_scope(None):\n return array_ops.identity(concatenated, name=self._name)\n\n def as_tensor(self):\n \"\"\"Returns the overall concatenated value as a `Tensor`.\n\n The returned tensor will not inherit the control dependencies from the scope\n where the value is used, which is similar to getting the value of\n `Variable`.\n\n Returns:\n `Tensor` containing the concatenated value.\n \"\"\"\n with ops.control_dependencies(None):\n return self._concat()\n\n @staticmethod\n def _TensorConversionFunction(v, dtype=None, name=None, as_ref=False):\n # pylint: disable=invalid-name\n _ = name\n if dtype is not None and not dtype.is_compatible_with(v.dtype):\n raise ValueError(\n \"Incompatible type conversion requested to type '%s' for variable \"\n \"of type '%s'\" % (dtype.name, v.dtype.name))\n if as_ref:\n raise NotImplementedError(\n \"PartitionedVariable doesn't support being used as a reference.\")\n else:\n return v.as_tensor()\n\n @property\n def name(self):\n return self._name\n\n @property\n def dtype(self):\n return self._dtype\n\n @property\n def shape(self):\n return self.get_shape()\n\n @property\n def _distribute_strategy(self):\n \"\"\"The `tf.distribute.Strategy` that this variable was created under.\"\"\"\n # NOTE(yuefengz): Today, no partitioned variables in a distribute strategy.\n return None\n\n def get_shape(self):\n return self._shape\n\n def _get_variable_list(self):\n return self._variable_list\n\n def _get_partitions(self):\n return self._partitions\n\n def _apply_assign_fn(self, assign_fn, value):\n partition_axes = self._partition_axes()\n if len(partition_axes) > 1:\n raise NotImplementedError(\n \"Cannot do assign action along more than one dimension: %s. \"\n \"Multi-axis partition assign action is not supported \" %\n str(partition_axes))\n if isinstance(value, list):\n assert len(value) == len(self._variable_list)\n value_list = value\n elif isinstance(value, PartitionedVariable):\n value_list = [var_part for var_part in value]\n else:\n partition_ix = partition_axes[0]\n size_splits_list = [\n tensor_shape.dimension_value(var.shape[partition_ix])\n for var in self._variable_list\n ]\n value_list = array_ops.split(value, size_splits_list, axis=partition_ix)\n\n op_list = [\n assign_fn(var, value_list[idx])\n for idx, var in enumerate(self._variable_list)\n ]\n return op_list\n\n def assign(self, value, use_locking=False, name=None, read_value=True):\n assign_fn = lambda var, r_value: var.assign(\n r_value, use_locking=use_locking, name=name, read_value=read_value)\n assign_list = self._apply_assign_fn(assign_fn, value)\n if read_value:\n return assign_list\n return [assign.op for assign in assign_list]\n\n def assign_add(self, value, use_locking=False, name=None, read_value=True):\n assign_fn = lambda var, r_value: var.assign_add(\n r_value, use_locking=use_locking, name=name, read_value=read_value)\n assign_list = self._apply_assign_fn(assign_fn, value)\n if read_value:\n return assign_list\n return [assign.op for assign in assign_list]\n\n def assign_sub(self, value, use_locking=False, name=None, read_value=True):\n assign_fn = lambda var, r_value: var.assign_sub(\n r_value, use_locking=use_locking, name=name, read_value=read_value)\n assign_list = self._apply_assign_fn(assign_fn, value)\n if read_value:\n return assign_list\n return [assign.op for assign in assign_list]\n\n def export(self):\n full_keys = []\n full_values = []\n full_versions = []\n full_freqs = []\n for v in self._variable_list:\n if not isinstance(v, kv_variable_ops.EmbeddingVariable):\n raise Exception(\"The export function does not support variables of type other than ev variable\")\n keys, values, versions, freqs = v.export()\n full_keys.append(keys)\n full_values.append(values)\n full_versions.append(versions)\n full_freqs.append(freqs)\n return array_ops.concat(full_keys, 0), array_ops.concat(full_values, 0), array_ops.concat(full_versions, 0), array_ops.concat(full_freqs, 0)\n\n\n# Register a conversion function which reads the value of the variable,\n# allowing instances of the class to be used as tensors.\nops.register_tensor_conversion_function(RefVariable,\n RefVariable._TensorConversionFunction) # pylint: disable=protected-access\nops.register_dense_tensor_like_type(RefVariable)\n\n\n@tf_export(v1=[\"global_variables\"])\ndef global_variables(scope=None):\n \"\"\"Returns global variables.\n\n Global variables are variables that are shared across machines in a\n distributed environment. The `Variable()` constructor or `get_variable()`\n automatically adds new variables to the graph collection\n `GraphKeys.GLOBAL_VARIABLES`.\n This convenience function returns the contents of that collection.\n\n An alternative to global variables are local variables. See\n `tf.compat.v1.local_variables`\n\n Args:\n scope: (Optional.) A string. If supplied, the resulting list is filtered to\n include only items whose `name` attribute matches `scope` using\n `re.match`. Items without a `name` attribute are never returned if a scope\n is supplied. The choice of `re.match` means that a `scope` without special\n tokens filters by prefix.\n\n Returns:\n A list of `Variable` objects.\n \"\"\"\n return ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES, scope)\n\n\n@tf_export(v1=[\"all_variables\"])\n@deprecated(\"2017-03-02\", \"Please use tf.global_variables instead.\")\ndef all_variables():\n \"\"\"Use `tf.compat.v1.global_variables` instead.\"\"\"\n return global_variables()\n\n\ndef _all_saveable_objects(scope=None):\n \"\"\"Returns all variables and `SaveableObject`s that must be checkpointed.\n\n Args:\n scope: (Optional.) A string. If supplied, the resulting list is filtered to\n include only items whose `name` attribute matches `scope` using\n `re.match`. Items without a `name` attribute are never returned if a scope\n is supplied. The choice of `re.match` means that a `scope` without special\n tokens filters by prefix.\n\n Returns:\n A list of `Variable` and `SaveableObject` to be checkpointed\n \"\"\"\n # TODO(andreasst): make this function public once things are settled.\n return (ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES, scope) +\n ops.get_collection(ops.GraphKeys.SAVEABLE_OBJECTS, scope))\n\n\n@tf_export(v1=[\"local_variables\"])\ndef local_variables(scope=None):\n \"\"\"Returns local variables.\n\n Local variables - per process variables, usually not saved/restored to\n checkpoint and used for temporary or intermediate values.\n For example, they can be used as counters for metrics computation or\n number of epochs this machine has read data.\n The `tf.contrib.framework.local_variable()` function automatically adds the\n new variable to `GraphKeys.LOCAL_VARIABLES`.\n This convenience function returns the contents of that collection.\n\n An alternative to local variables are global variables. See\n `tf.compat.v1.global_variables`\n\n Args:\n scope: (Optional.) A string. If supplied, the resulting list is filtered to\n include only items whose `name` attribute matches `scope` using\n `re.match`. Items without a `name` attribute are never returned if a scope\n is supplied. The choice of `re.match` means that a `scope` without special\n tokens filters by prefix.\n\n Returns:\n A list of local `Variable` objects.\n \"\"\"\n return ops.get_collection(ops.GraphKeys.LOCAL_VARIABLES, scope)\n\n\n@tf_export(v1=[\"model_variables\"])\ndef model_variables(scope=None):\n \"\"\"Returns all variables in the MODEL_VARIABLES collection.\n\n Args:\n scope: (Optional.) A string. If supplied, the resulting list is filtered to\n include only items whose `name` attribute matches `scope` using\n `re.match`. Items without a `name` attribute are never returned if a scope\n is supplied. The choice of `re.match` means that a `scope` without special\n tokens filters by prefix.\n\n Returns:\n A list of local Variable objects.\n \"\"\"\n return ops.get_collection(ops.GraphKeys.MODEL_VARIABLES, scope)\n\n\n@tf_export(v1=[\"trainable_variables\"])\ndef trainable_variables(scope=None):\n \"\"\"Returns all variables created with `trainable=True`.\n\n When passed `trainable=True`, the `Variable()` constructor automatically\n adds new variables to the graph collection\n `GraphKeys.TRAINABLE_VARIABLES`. This convenience function returns the\n contents of that collection.\n\n Args:\n scope: (Optional.) A string. If supplied, the resulting list is filtered to\n include only items whose `name` attribute matches `scope` using\n `re.match`. Items without a `name` attribute are never returned if a scope\n is supplied. The choice of `re.match` means that a `scope` without special\n tokens filters by prefix.\n\n Returns:\n A list of Variable objects.\n \"\"\"\n return ops.get_collection(ops.GraphKeys.TRAINABLE_VARIABLES, scope)\n\n\n@tf_export(v1=[\"moving_average_variables\"])\ndef moving_average_variables(scope=None):\n \"\"\"Returns all variables that maintain their moving averages.\n\n If an `ExponentialMovingAverage` object is created and the `apply()`\n method is called on a list of variables, these variables will\n be added to the `GraphKeys.MOVING_AVERAGE_VARIABLES` collection.\n This convenience function returns the contents of that collection.\n\n Args:\n scope: (Optional.) A string. If supplied, the resulting list is filtered to\n include only items whose `name` attribute matches `scope` using\n `re.match`. Items without a `name` attribute are never returned if a scope\n is supplied. The choice of `re.match` means that a `scope` without special\n tokens filters by prefix.\n\n Returns:\n A list of Variable objects.\n \"\"\"\n return ops.get_collection(ops.GraphKeys.MOVING_AVERAGE_VARIABLES, scope)\n\n\n@tf_export(v1=[\"initializers.variables\", \"variables_initializer\"])\ndef variables_initializer(var_list, name=\"init\"):\n \"\"\"Returns an Op that initializes a list of variables.\n\n After you launch the graph in a session, you can run the returned Op to\n initialize all the variables in `var_list`. This Op runs all the\n initializers of the variables in `var_list` in parallel.\n\n Calling `initialize_variables()` is equivalent to passing the list of\n initializers to `Group()`.\n\n If `var_list` is empty, however, the function still returns an Op that can\n be run. That Op just has no effect.\n\n Args:\n var_list: List of `Variable` objects to initialize.\n name: Optional name for the returned operation.\n\n Returns:\n An Op that run the initializers of all the specified variables.\n \"\"\"\n if var_list and not context.executing_eagerly():\n return control_flow_ops.group(*[v.initializer for v in var_list], name=name)\n return control_flow_ops.no_op(name=name)\n\n\n@tf_export(v1=[\"initialize_variables\"])\n@tf_should_use.should_use_result\n@deprecated(\"2017-03-02\", \"Use `tf.variables_initializer` instead.\")\ndef initialize_variables(var_list, name=\"init\"):\n \"\"\"See `tf.compat.v1.variables_initializer`.\"\"\"\n return variables_initializer(var_list, name=name)\n\n\n@tf_export(v1=[\"initializers.global_variables\", \"global_variables_initializer\"])\ndef global_variables_initializer():\n \"\"\"Returns an Op that initializes global variables.\n\n This is just a shortcut for `variables_initializer(global_variables())`\n\n Returns:\n An Op that initializes global variables in the graph.\n \"\"\"\n if context.executing_eagerly():\n return control_flow_ops.no_op(name=\"global_variables_initializer\")\n return variables_initializer(global_variables())\n\n\n@tf_export(v1=[\"initialize_all_variables\"])\n@tf_should_use.should_use_result\n@deprecated(\"2017-03-02\", \"Use `tf.global_variables_initializer` instead.\")\ndef initialize_all_variables():\n \"\"\"See `tf.compat.v1.global_variables_initializer`.\"\"\"\n return global_variables_initializer()\n\n\n@tf_export(v1=[\"initializers.local_variables\", \"local_variables_initializer\"])\ndef local_variables_initializer():\n \"\"\"Returns an Op that initializes all local variables.\n\n This is just a shortcut for `variables_initializer(local_variables())`\n\n Returns:\n An Op that initializes all local variables in the graph.\n \"\"\"\n if context.executing_eagerly():\n return control_flow_ops.no_op(name=\"local_variables_initializer\")\n return variables_initializer(local_variables())\n\n\n@tf_export(v1=[\"initialize_local_variables\"])\n@tf_should_use.should_use_result\n@deprecated(\"2017-03-02\", \"Use `tf.local_variables_initializer` instead.\")\ndef initialize_local_variables():\n \"\"\"See `tf.compat.v1.local_variables_initializer`.\"\"\"\n return local_variables_initializer()\n\n\n@tf_export(v1=[\"is_variable_initialized\"])\n@tf_should_use.should_use_result\ndef is_variable_initialized(variable):\n \"\"\"Tests if a variable has been initialized.\n\n Args:\n variable: A `Variable`.\n\n Returns:\n Returns a scalar boolean Tensor, `True` if the variable has been\n initialized, `False` otherwise.\n \"\"\"\n return state_ops.is_variable_initialized(variable)\n\n\n@tf_export(v1=[\"assert_variables_initialized\"])\n@tf_should_use.should_use_result\ndef assert_variables_initialized(var_list=None):\n \"\"\"Returns an Op to check if variables are initialized.\n\n NOTE: This function is obsolete and will be removed in 6 months. Please\n change your implementation to use `report_uninitialized_variables()`.\n\n When run, the returned Op will raise the exception `FailedPreconditionError`\n if any of the variables has not yet been initialized.\n\n Note: This function is implemented by trying to fetch the values of the\n variables. If one of the variables is not initialized a message may be\n logged by the C++ runtime. This is expected.\n\n Args:\n var_list: List of `Variable` objects to check. Defaults to the value of\n `global_variables().`\n\n Returns:\n An Op, or None if there are no variables.\n \"\"\"\n if var_list is None:\n var_list = global_variables() + local_variables()\n # Backwards compatibility for old-style variables. TODO(touts): remove.\n if not var_list:\n var_list = []\n for op in ops.get_default_graph().get_operations():\n if op.type in [\"Variable\", \"VariableV2\", \"AutoReloadVariable\"]:\n var_list.append(op.outputs[0])\n if not var_list:\n return None\n else:\n ranks = []\n for var in var_list:\n with ops.colocate_with(var.op):\n ranks.append(array_ops.rank_internal(var, optimize=False))\n if len(ranks) == 1:\n return ranks[0]\n else:\n return array_ops.stack(ranks)\n\n\n@tf_export(v1=[\"report_uninitialized_variables\"])\n@tf_should_use.should_use_result\ndef report_uninitialized_variables(var_list=None,\n name=\"report_uninitialized_variables\"):\n \"\"\"Adds ops to list the names of uninitialized variables.\n\n When run, it returns a 1-D tensor containing the names of uninitialized\n variables if there are any, or an empty array if there are none.\n\n Args:\n var_list: List of `Variable` objects to check. Defaults to the value of\n `global_variables() + local_variables()`\n name: Optional name of the `Operation`.\n\n Returns:\n A 1-D tensor containing names of the uninitialized variables, or an empty\n 1-D tensor if there are no variables or no uninitialized variables.\n \"\"\"\n if var_list is None:\n var_list = global_variables() + local_variables()\n # Backwards compatibility for old-style variables. TODO(touts): remove.\n if not var_list:\n var_list = []\n for op in ops.get_default_graph().get_operations():\n if op.type in [\"Variable\", \"VariableV2\", \"AutoReloadVariable\"]:\n var_list.append(op.outputs[0])\n with ops.name_scope(name):\n # Run all operations on CPU\n if var_list:\n init_vars = [state_ops.is_variable_initialized(v) for v in var_list]\n local_device = os.environ.get(\n \"TF_DEVICE_FOR_UNINITIALIZED_VARIABLE_REPORTING\", \"/cpu:0\")\n with ops.device(local_device):\n if not var_list:\n # Return an empty tensor so we only need to check for returned tensor\n # size being 0 as an indication of model ready.\n return array_ops.constant([], dtype=dtypes.string)\n else:\n # Get a 1-D boolean tensor listing whether each variable is initialized.\n variables_mask = math_ops.logical_not(array_ops.stack(init_vars))\n # Get a 1-D string tensor containing all the variable names.\n variable_names_tensor = array_ops.constant(\n [s.op.name for s in var_list])\n # Return a 1-D tensor containing all the names of\n # uninitialized variables.\n return array_ops.boolean_mask(variable_names_tensor, variables_mask)\n\n\nops.register_tensor_conversion_function(\n PartitionedVariable, PartitionedVariable._TensorConversionFunction) # pylint: disable=protected-access\n\n\nclass AbstractVariableMetaclass(VariableMetaclass, abc.ABCMeta):\n \"\"\"Metaclass combining `VariableMetaclass` and `abc.ABCMeta`.\"\"\"\n pass\n\n\n@six.add_metaclass(AbstractVariableMetaclass)\nclass AbstractVariable(Variable):\n \"\"\"`Variable`, but abstract.\"\"\"\n pass\n","repo_name":"DeepRec-AI/DeepRec","sub_path":"tensorflow/python/ops/variables.py","file_name":"variables.py","file_ext":"py","file_size_in_byte":137317,"program_lang":"python","lang":"en","doc_type":"code","stars":895,"dataset":"github-code","pt":"31"}
+{"seq_id":"31016279107","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\ncsvArray = ['경기도 성남시_주정차 위반 단속 위치 현황_20220927.csv',\n '교통단속카메라.csv',\n '경기도 성남시_공영주차장 월별 입출차 현황_20221122.csv',\n '경기도 성남시_성남시 전통시장_발달상권_골목상권 기본상권정보 현황_20211201.csv',\n '경기도 성남시_성남시 전통시장_발달상권_골목상권 업종별 시장규모 현황_20211201.csv',\n '경기도 성남시_성남시 전통시장_발달상권_골목상권별 이용고객 소비비중 현황_20211201.csv',\n '경기도 성남시_대규모 점포시장현황_20220531.csv',\n ]\npd.set_option('display.max_columns', None)\n\ndef statistical_description(df):\n print('Features types : \\n', df.dtypes)\n print('Dataset describe : \\n', df.describe(include='all'))\n print('Dataset head : \\n', df.head())\n for col in df.columns:\n if df[col].dtype == 'object': # 문자열 데이터에 대해서만 처리\n unique_values = df[col].unique()\n value_counts = df[col].value_counts()\n # print(f\"[{col}] - Unique values: \\n {unique_values}\")\n print(f\"[{col}] - Value counts: \\n {value_counts}\\n\")\n\n\nfor csv in csvArray:\n df = pd.read_csv(csv, encoding='cp949')\n print('Dataset Title : ', csv)\n statistical_description(df)\n\n\n\n","repo_name":"1109min/DataScience-TermProject-Team11","sub_path":"termProject/checkData.py","file_name":"checkData.py","file_ext":"py","file_size_in_byte":1463,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"70192299608","text":"\nimport unittest\nimport numpy as np\nfrom scikit_lag import lag, LagRegressor\n\nclass TestLagRgressor(unittest.TestCase):\n\n def test_lag_nan(self):\n \tx = np.arange(10, dtype=np.float32)\n \tlagged = lag(x, 2)\n \tself.assertEqual(lagged[-1], 7)\n \tself.assertTrue(np.isnan(lagged[1]))\n\n def test_regressor(self):\n \tnp.random.seed(22)\n \tn = 50\n \tX = np.random.normal(0, 1, size=(n, 2))\n \ty = np.random.normal(0, 1, n)\n \treg = LagRegressor(maxlag=2)\n \treg.fit(X, y)\n \tpred = reg.predict(X)\n \tself.assertEqual(len(pred), n)\n\n\nif __name__ == '__main__':\n unittest.main()","repo_name":"dirknbr/scikit_lag_regressor","sub_path":"scikit_lag_test.py","file_name":"scikit_lag_test.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"}
+{"seq_id":"3701397718","text":"from django import template\n\nregister = template.Library()\n\n\n@register.filter(name='range_')\ndef range_(number, diff=1):\n return range(0, number, diff)\n\n\n@register.filter(name='querysetToList')\ndef querysetToList(queryset, index=None):\n if not index:\n if queryset.count() > 0:\n return [element for element in queryset]\n return []\n else:\n list_ = [element for element in queryset]\n return list_[index]\n\n\n@register.filter(name='quotient')\ndef quotient(number, divideby):\n return int(number / divideby)\n\n\n@register.filter(name='remainder')\ndef remainder(number, divideby):\n return number % divideby\n\n\n@register.filter(name='toGrid')\ndef toGrid(querySet, column):\n if querySet.count() > 0:\n list_ = []\n temp = []\n i = 0\n for element in querySet:\n if not i == 0 and i % column == 0:\n list_.append([temp, i])\n temp = []\n temp.append(element)\n i += 1\n if len(temp) > 0:\n list_.append([temp, i])\n return list_\n return []\n\n\n@register.filter(name='upto')\ndef upto(querySet, index):\n if querySet.count() == 0:\n return querySet\n if querySet.count() > 3:\n data = querysetToList(querySet)[:index]\n return [[data[i], i + 1] for i in range(3)]\n data = querysetToList(querySet)\n return [[data[i], i + 1] for i in range(len(data))]\n\n\n@register.filter(name='concat')\ndef concat_(arg1, arg2):\n return str(arg1) + str(arg2)\n\n\n@register.filter(name='maxLength')\ndef maxLength(arg1, arg2):\n return arg1[:int(arg2)]\n","repo_name":"SaadJamilAkhtar/Portfolio","sub_path":"Main/templatetags/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"}
+{"seq_id":"21467069456","text":"import numpy\nimport colorsys\n\nfrom lib import bitmap\n\nznext = lambda z, c : z**2 + c\n\ndef mandelbrot(x_range=(-2, 1), y_range=(-1, 1), resolution=800, color=False):\n\n # lengths of the intervals (ranges)\n x_length = x_range[1] - x_range[0]\n y_length = y_range[1] - y_range[0]\n\n # if the range is not 1:1 recalculate 'y-resolution'\n x_resolution = resolution\n y_resolution = int((y_length / x_length) * resolution)\n\n img = bitmap.PNG(x_resolution, y_resolution)\n\n # steps for x and y axis so we produce 'enough pixels' to fill the image\n x_step = x_length / x_resolution\n y_step = y_length / y_resolution\n\n for real in numpy.arange(x_range[0], x_range[1], x_step):\n print(real)\n for imag in numpy.arange(y_range[0], y_range[1], y_step):\n\n c = complex(real, imag)\n z = complex(0, 0)\n\n i = 0\n while i < 30:\n z = znext(z, c)\n\n if abs(z) > 2:\n break\n\n i += 1\n\n # pixel coordinates -- make sure to start with 0 and end with x/y-resoltion\n if x_range[0] <= 0:\n px = (real + abs(x_range[0])) * (x_resolution / x_length)\n else:\n px = (real - abs(x_range[0])) * (x_resolution / x_length)\n if y_range[0] <= 0:\n py = (imag + abs(y_range[0])) * (y_resolution / y_length)\n else:\n py = (imag - abs(y_range[0])) * (y_resolution / y_length)\n\n # color or greyscale\n if color:\n hsv_color = (1 - (i / 30), 0.75, 0.75)\n rgb_color = [int(255 * j) for j in colorsys.hsv_to_rgb(*hsv_color)]\n else:\n rgb_color = [255 - (i * 10), 255 - (i * 10), 255 - (i * 10)]\n img.draw_pixel(bitmap.Point(px, py), color=(rgb_color[0], rgb_color[1], rgb_color[2]))\n\n img.show()\n\n\nmandelbrot()\nmandelbrot(color=True)\nmandelbrot(x_range=(0.25, 0.45), y_range=(0.45, 0.60), color=True)\n","repo_name":"vojtechtrefny/iv122","sub_path":"cv7/mandelbrot.py","file_name":"mandelbrot.py","file_ext":"py","file_size_in_byte":2003,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"38820840672","text":"from functools import cache\nfrom typing import List\n\n\nclass Solution:\n def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:\n @cache\n def work_break_healper(string: str) -> List[List[str]]:\n if not string:\n return [[]]\n\n combinations = []\n for length in range(1, len(string)+1):\n word = string[:length]\n if word in word_set:\n for sub_word in work_break_healper(string[length:]):\n combinations.append([word] + sub_word)\n\n return combinations\n\n word_set = set(wordDict)\n result = work_break_healper(s)\n return [\" \".join(i) for i in result]\n","repo_name":"yuchia0221/Leetcode","sub_path":"Dynamic Programming/140-WordBreakII/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"}
+{"seq_id":"15917841638","text":"from PIL import Image\nfrom io import BytesIO\nfrom django.core.files import File\nfrom django.db import models\n\n\nclass Location(models.Model):\n name = models.CharField(max_length=255, verbose_name=\"Название\")\n url_name = models.CharField(max_length=255, verbose_name=\"Название латиница\", null=True, blank=True)\n location = models.CharField(max_length=255, verbose_name=\"Местоположение\")\n\n def __str__(self):\n return self.name\n\n class Meta:\n verbose_name = \"Локацию\"\n verbose_name_plural = \"Локации\"\n ordering = [\"id\"]\n\n\ndef compress(image):\n im = Image.open(image)\n if im.mode != 'RGB':\n im = im.convert('RGB')\n im_io = BytesIO()\n im.save(im_io, 'JPEG', quality=60)\n new_image = File(im_io, name=image.name)\n return new_image\n\n\nclass LocationImage(models.Model):\n location = models.ForeignKey(Location, models.SET_NULL, 'images', null=True, blank=True,\n verbose_name=\"фотографии услуги\")\n img = models.ImageField(upload_to=\"locations\", verbose_name=\"Фото\")\n\n def save(self, *args, **kwargs):\n new_image = compress(self.img)\n self.img = new_image\n super().save(*args, **kwargs)\n\n def __str__(self):\n return str(self.id)\n\n class Meta:\n verbose_name = \"Фотография\"\n verbose_name_plural = \"Фотографии\"\n","repo_name":"aycanmuratbekova/kg","sub_path":"locations/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1445,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"31346255942","text":"from setuptools import find_packages, setup\n\nREQUIRED_PACKAGES = [\n \"colorcet\",\n # \"giskard @ https://github.com/bdpedigo/giskard.git#egg=giskard\",\n \"graspologic\",\n \"matplotlib\",\n \"networkx>=2.5\",\n \"numpy>=1.19\",\n \"pandas>=1.0\",\n # \"python-catmaid>=2.0.2\",\n \"scikit-learn>=0.24.0\",\n \"scipy>=1.6.0\",\n \"seaborn>=0.11.0\",\n \"umap-learn>=0.5\",\n]\n\nsetup(\n name=\"pkg\",\n packages=find_packages(),\n version=\"0.1.0\",\n description=\"Local package for bilateral-connectome paper\",\n author=\"Neurodata\",\n license=\"MIT\",\n install_requires=REQUIRED_PACKAGES,\n dependency_links=[],\n)\n","repo_name":"bdpedigo/networks-course","sub_path":"pkg/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"31"}
+{"seq_id":"7535037602","text":"from datetime import date\nfrom importlib import import_module\nimport requests\nfrom bs4 import BeautifulSoup\n\n\nclass DOceanHtmlScrapy:\n req = requests.get(\"https://www.digitalocean.com/pricing/\").text # requisição get ao enpoint, com retorno em text\n soup = BeautifulSoup(req, 'html.parser') # formatação do texto para html\n text_lines = soup.select('ul.priceBox') # seleciona tag\n\n dict_terminal = {}\n\n @classmethod\n def save_scrapy(cls):\n for count in range(6):\n top_box = cls.text_lines[0].select('div.topBox')[count].get_text().split(' ')\n bottom_box_one = cls.text_lines[0].select('a > div:nth-child(2) > ul > li:nth-child(1)'\n '')[count].get_text().split('/')\n bottom_box_two = cls.text_lines[0].select('a > div:nth-child(2) > ul > li:nth-child(2)')[count].get_text()\n bottom_box_thr = cls.text_lines[0].select('a > div:nth-child(2) > ul > li:nth-child(3)')[count].get_text()\n\n data = {\n 'score': 'N/A',\n 'storage': bottom_box_two,\n 'cpu': bottom_box_one[1],\n 'memory': bottom_box_one[0],\n 'bandwidth': bottom_box_thr,\n 'price': top_box[0],\n 'hr_price': top_box[1],\n 'date': str(date.today()),\n 'tipo': 'regular',\n 'scraped_page': 'https://www.digitalocean.com/pricing/'\n }\n local_db = import_module(f'models.LocalDB')\n local_db.DB.fill_db(**data)\n cls.dict_terminal.update({count: data})\n return cls.dict_terminal\n","repo_name":"Carlos-rof/web_crawler","sub_path":"resources/DOceanHtmlScrapy.py","file_name":"DOceanHtmlScrapy.py","file_ext":"py","file_size_in_byte":1661,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"74257719128","text":"def checkio(data):\n\ty=len(data)\n\tx=len(data[0])\n\tm=[[0]*x for i in range(y)]\n\tfor j in range(y):\n\t\tr=0\n\t\tfor i in range(x):\n\t\t\tif data[j][i]=='G' or data[j][i]=='S': r+=1\n\t\t\telse: r=0\n\t\t\tm[j][i]=r\n\tr=0\n\tfor i in range(x):\n\t\tfor j in range(y):\n\t\t\tM=9999999\n\t\t\tfor k in range(j,y):\n\t\t\t\tM=min(M,m[k][i])\n\t\t\t\tr=max(r,M*(k-j+1))\n\treturn r\n\nif __name__ == '__main__':\n\tassert checkio(['G']) == 1, 'One cell - one variant'\n\tassert checkio(['GS',\n\t\t\t\t\t'GS']) == 4, 'Four good cells'\n\tassert checkio(['GT',\n\t\t\t\t\t'GG']) == 2, 'Four cells, but with a tree'\n\tassert checkio(['GGTGG',\n\t\t\t\t\t'TGGGG',\n\t\t\t\t\t'GSSGT',\n\t\t\t\t\t'GGGGT',\n\t\t\t\t\t'GWGGG',\n\t\t\t\t\t'RGTRT',\n\t\t\t\t\t'RTGWT',\n\t\t\t\t\t'WTWGR']) == 9, 'Classic'","repo_name":"cielavenir/checkio","sub_path":"scientific-expedition/spaceship-landing-strip.py","file_name":"spaceship-landing-strip.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"70399163288","text":"import os\n\nfrom decouple import config\n\n# The prefix that will be used to parse commands.\n# It doesn't have to be a single character!\nCOMMAND_PREFIX = config(\"BOT_DEFAULT_PREFIX\")\n\n# The bot token. Keep this secret!\nBOT_TOKEN = config(\"DISCORD_API_BOT_TOKEN\")\nBOT_CLIENT_ID = config(\"DISCORD_CLIENT_ID\")\n# The now playing game. Set this to anything false-y (\"\", None) to disable it\nNOW_PLAYING = COMMAND_PREFIX + \"commands\"\n\n# Base directory. Feel free to use it if you want.\nBASE_DIR = os.path.dirname(os.path.realpath(__file__))\n\nWARCRAFTLOGS_REGEX = \"(?:http:\\/\\/|https:\\/\\/)(?:www.warcraftlogs.)(?:com|fr)(?:\\/)(?:reports)(?:\\/)(?:(\\w)*)(?:\\/)\"\n","repo_name":"benftwc/lydros-bot","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"72905359768","text":"num = int(input(\"Enter number: \"))\n\nflag = False\nif num > 1:\n for i in range(2, num):\n # mathematically here, should use num/2, but can leave for now\n if num % 2:\n flag = True\n break\n\nif flag:\n print(\"Not prime\")\nelse:\n print(\"Prime\")","repo_name":"gargchirayu/Python-basic-projects","sub_path":"prime.py","file_name":"prime.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"18307026929","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nhtml = '''Content-type: text/html;\n\n\n\n\n \n クエリベクトル作成\n\n\n
キーワードを入力してください
\n\n
%s
\n\n\n'''\n\nimport cgi\nimport os, sys\nimport read_wakachi\nimport numpy as np\nimport pandas as pd\nimport glob\nimport re\nimport MeCab\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\ntry:\n import msvcrt\n msvcrt.setmode(0, os.O_BINARY)\n msvcrt.setmode(1, os.O_BINARY)\nexcept ImportError:\n pass\n\n# metadata.csvの置き場所を指定\ndir='./cgi-bin/metadata.csv'\nqvec=0\n\ndef is_str(v):\n return type(v) is str\n\nf = cgi.FieldStorage()\nkeywords = f.getfirst('keyword', '')\n\n# ここから処理の内容を書く。\nif is_str(keywords):\n keyws=read_wakachi.parsewithelimination(keywords)\n keys=np.array(keyws.split())\n if os.path.isfile(dir):\n df = pd.read_csv(dir, header=0, index_col=0)\n qvec=np.zeros(df.columns.shape)\n for key in keys:\n if np.any(df.columns == key):\n qvec[np.where(df.columns==key)[0][0]]=1\n\nelse:\n keys='キーワードを入力してください'\n\n#num=sum(qvec == 1)\n\n\n\nprint (html % qvec)","repo_name":"MinamiKota/Portfolio","sub_path":"人工知能(AI)アルゴリズムデザイン/index9.py","file_name":"index9.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"10836138345","text":"import tflite_runtime.interpreter as tflite\n# from keras_image_helper import create_preprocessor\nfrom PIL import Image\nimport requests\nimport numpy as np \n\ndef get_image(url):\n img = Image.open(requests.get(url, stream=True).raw)\n img = img.resize((299, 299), Image.Resampling.NEAREST)\n x = np.array(img, dtype='float32')\n return np.array([x])\n\ndef preprocess_input(x):\n x /= 127.5\n x -= 1.\n return x\n\n# preprocessor = create_preprocessor('xception', target_size=(299, 299))\n\ninterpreter = tflite.Interpreter(model_path='clothing-model.tflite')\n# memory allocation\ninterpreter.allocate_tensors()\n\ninput_index = interpreter.get_input_details()[0]['index']\noutput_index = interpreter.get_output_details()[0]['index']\n\nclasses = [\n 'dress',\n 'hat',\n 'longsleeve',\n 'outwear',\n 'pants',\n 'shirt',\n 'shoes',\n 'shorts',\n 'skirt',\n 't-shirt'\n]\n\n# url = 'http://bit.ly/mlbookcamp-pants'\n\ndef predict(url):\n # X = preprocessor.from_url(url)\n img = get_image(url)\n X = preprocess_input(img)\n\n interpreter.set_tensor(input_index, X)\n interpreter.invoke()\n preds = interpreter.get_tensor(output_index)\n\n predictions = preds[0].tolist()\n\n return dict(zip(classes, predictions))\n\n\ndef lambda_handler(event, context):\n url = event['url']\n result = predict(url)\n return result\n","repo_name":"nadia-paz/ML-Zoomcamp","sub_path":"week9/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"28076101035","text":"# 変数のスコープ\n# 関数の中で使っている変数をローカル変数という。\n# 関数の外側で定義している変数をグローバル変数という。\n\n# 非ローカル変数の変更\na = 'グローバル変数a'\ndef funcA():\n a = 'funcA()の変数a'\n b = 'funcA()の変数b'\n def funcB():\n b = 'funcB()の変数b'\n c = 'funcB()の変数c'\n print(a, b, c)\n funcB()\n print(b)\n\nfuncA()\nprint(a)\n\n# 関数の外側の変数を変更したいときは、globalまたはnonlocalを使って、\n# 変数が非ローカルである事を宣言する必要がある。\na = 0\ndef funcA():\n global a\n a = 1\n b = 2\n def funcB():\n nonlocal b\n b = 2\n c = 2\n print(a, b, c)\n funcB()\n print(b)\nfuncA()\nprint(a)\n","repo_name":"Lazurle/Python_Ehon","sub_path":"5,関数/scope01.py","file_name":"scope01.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"14727465533","text":"#\n# file-system.py\n# created by Steven Traversi\n# (c) Steven Traversi 2016\n#\n\nimport re\n\nclass Directory:\n\n def __init__(self, name):\n \"\"\"Set the name of the directory and start an empty dict to hold\n files and other directories.\n \"\"\"\n self.name = name\n self.contents = {}\n\n def add_sub_dir(self, name):\n \"\"\"Add a sub dir, name, of the current dir represented by root.\n Return it.\n \"\"\"\n new_dir = Directory(name)\n self.contents[name] = new_dir\n new_dir.contents[\"..\"] = self\n return new_dir\n\n def add_file(self, name, contents):\n \"\"\"Add a file called name to the current dir. Return it.\"\"\"\n new_file = File(name, contents)\n self.contents[name] = new_file\n return new_file\n\n def search(self, keyword):\n \"\"\"Search the current directory and all of its sub directories (etc.),\n and return the relative paths of any hits. If there are no hits, return\n empty.\n \"\"\"\n assert False, \"Implement me\"\n results = []\n for obj in self.contents:\n if re.search(keyword, obj.name):\n results.append(obj.name)\n if isinstance(obj, Directory):\n results += obj.search(keyword)\n elif isinstance(obj, File) and re.search(keyword, obj.contents):\n results.append(obj.name)\n return [self.name + \"/\" + sub_path for sub_path in results]\n\n def get_dir(self, path):\n \"\"\"Get the directory relative to this directory at path.\n Example:\n self = ~/Documents\n path = Projects/Blog\n RETURN: Directory @ ~/Documents/Projects/Blog\n \"\"\"\n if path == \"\" or path == self.name:\n return self\n dirs = path.split(\"/\")\n for child, reference in self.contents.items():\n if isinstance(reference, Directory) and child == dirs[0]:\n return reference.get_dir(\"/\".join(dirs[1:]))\n raise ValueError(\"Fix me\")\n\n def absolute_path(self):\n if not \"..\" in self.contents:\n return self.name\n return self.contents[\"..\"].absolute_path() + \"/\" + self.name\n\nclass File:\n\n def __init__(self, name, contents):\n \"\"\"Set the name of the file and its contents as a string.\"\"\"\n self.name = name\n self.contents = contents\n","repo_name":"straversi/web-term","sub_path":"file_system.py","file_name":"file_system.py","file_ext":"py","file_size_in_byte":2366,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"}
+{"seq_id":"72683816728","text":"import numpy as np\nfrom icu_benchmarks.common.constants import STEPS_PER_HOUR, BINARY_TSH_URINE\n\n\ndef get_hr_status(hr_col):\n \"\"\"Return a presence feature on HR given the cumulative counts of HR.\n\n Presence at time t is valid if there is a HR measurement in th 15min surrounding the index.\n i.e in [idx-1, idx. idx+1]\n \"\"\"\n\n hr_status_arr = np.zeros_like(hr_col)\n for jdx in range(hr_col.size):\n subarr = hr_col[max(0, jdx - 2):min(hr_col.size - 1, jdx + 2)]\n three_steps_hr_diff = subarr[-1] - subarr[0]\n hr_status_arr[jdx] = 1 if three_steps_hr_diff > 0 else 0\n\n return hr_status_arr\n\n\ndef get_any_resp_label(pre_resp_arr):\n \"\"\"Transforms multiple level of severity annotation of respiratory failure events to a unique binary label\"\"\"\n\n ann_resp_arr = np.zeros_like(pre_resp_arr)\n for jdx in range(ann_resp_arr.size):\n if pre_resp_arr[jdx] in [\"event_1\", \"event_2\", \"event_3\"]:\n ann_resp_arr[jdx] = 1\n elif pre_resp_arr[jdx] in [\"UNKNOWN\"]:\n ann_resp_arr[jdx] = np.nan\n return ann_resp_arr\n\n\ndef convolve_hr(in_arr, hr_status_arr):\n \"\"\" Convolve an array with a HR status arr\"\"\"\n out_arr = np.copy(in_arr)\n out_arr[hr_status_arr == 0] = np.nan\n return out_arr\n\n\ndef transition_to_abs(score_arr, target, lhours, rhours):\n \"\"\" Transition to an absolute value from a value below the target\"\"\"\n out_arr = np.zeros_like(score_arr)\n for jdx in range(out_arr.size):\n if score_arr[jdx] >= target:\n out_arr[jdx] = np.nan\n continue\n low_idx = min(score_arr.size, jdx + 1 + STEPS_PER_HOUR * lhours)\n high_idx = min(score_arr.size, jdx + 1 + STEPS_PER_HOUR * rhours)\n future_arr = score_arr[low_idx:high_idx]\n if future_arr.size == 0:\n out_arr[jdx] = np.nan\n elif np.sum(future_arr >= target) > 0:\n out_arr[jdx] = 1.0\n return out_arr\n\n\ndef unique_label_at_hours(stay_length, status, at_hours=24):\n \"\"\" Unique Label assigned at a fixed time-point\"\"\"\n out_arr = np.zeros(stay_length)\n out_arr[:] = np.nan\n if stay_length >= at_hours * STEPS_PER_HOUR:\n out_arr[at_hours * STEPS_PER_HOUR - 1] = status\n return out_arr\n\n\ndef transition_to_failure(ann_col, lhours=None, rhours=None):\n \"\"\" Transition to failure defined on a binary annotation column\"\"\"\n out_arr = np.zeros_like(ann_col)\n for jdx in range(len(out_arr)):\n if np.isnan(ann_col[jdx]) or ann_col[jdx] == 1:\n out_arr[jdx] = np.nan\n elif ann_col[jdx] == 0:\n low_idx = min(ann_col.size, jdx + 1 + lhours * STEPS_PER_HOUR)\n high_idx = min(ann_col.size, jdx + 1 + rhours * STEPS_PER_HOUR)\n fut_arr = ann_col[low_idx:high_idx]\n if (fut_arr == 1.0).any():\n out_arr[jdx] = 1\n return out_arr\n\n\ndef future_urine_output(urine_col, urine_meas_arr, weight_col, rhours=None):\n \"\"\" Regression and binary classification problems on urine output in the future\"\"\"\n reg_out_arr = np.zeros_like(urine_col)\n binary_out_arr = np.zeros_like(urine_col)\n\n for jdx in range(urine_col.size):\n\n # No valid urine measurement anchor in 2 hours, the task is invalid\n measurement_idx = min(jdx + STEPS_PER_HOUR * rhours, urine_col.size - 1)\n\n end_of_stay_before_2h = measurement_idx == urine_col.size - 1\n urine_diff = urine_meas_arr[measurement_idx] - urine_meas_arr[measurement_idx - 1]\n no_measurement_in_2h = urine_diff <= 0\n\n if end_of_stay_before_2h or no_measurement_in_2h:\n binary_out_arr[jdx] = np.nan\n reg_out_arr[jdx] = np.nan\n continue\n\n current_weight = weight_col[jdx]\n\n cum_increase = 0\n for kdx in range(1, rhours * STEPS_PER_HOUR + 1):\n if jdx + kdx >= urine_col.size:\n break\n cum_increase += urine_col[jdx + kdx]\n std_cum_increase = cum_increase / (current_weight * STEPS_PER_HOUR * rhours)\n reg_out_arr[jdx] = std_cum_increase\n\n # More than 0.5 ml/kg/h\n if std_cum_increase >= BINARY_TSH_URINE:\n binary_out_arr[jdx] = 1.0\n\n return reg_out_arr, binary_out_arr\n\n\ndef merge_apache_groups(apache_ii_group, apache_iv_group, apache_ii_map, apache_iv_map):\n \"\"\"Merges apache II and IV definition to have a unique APACHE label\"\"\"\n\n if np.isfinite(apache_ii_group) and int(apache_ii_group) in apache_ii_map.keys():\n apache_pat_group = apache_ii_map[int(apache_ii_group)]\n elif np.isfinite(apache_iv_group) and int(apache_iv_group) in apache_iv_map.keys():\n apache_pat_group = apache_iv_map[int(apache_iv_group)]\n else:\n apache_pat_group = np.nan\n return apache_pat_group\n","repo_name":"ratschlab/HIRID-ICU-Benchmark","sub_path":"icu_benchmarks/labels/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4735,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"31"}
+{"seq_id":"19170990449","text":"import math\nT = int(input())\nfor tc in range(1, T+1):\n\ta, d, n = map(int, input().split())\n\tm = 1000003\n\tif n >= m and d > 0:\n\t\tanswer = 0\n\telif a == 0 and d == 0:\n\t\tanswer = 0\n\telif a == 1 and d == 0:\n\t\tanswer = 1\n\telif d == 0:\n\t\tanswer = (a ** n)%m\n\telse:\n\t\tg = math.gcd(m-a,d)\n\t\tq = (m-a)//g\n\t\tif q < n:\n\t\t\tanswer = 0\n\t\telse:\n\t\t\tprod = 1\n\t\t\tfor i in range(n//2):\n\t\t\t\tprod *= (a+i*d)*(a+(n-1-i)*d)\n\t\t\t\tif prod > m:\n\t\t\t\t\tprod %= m\n\t\t\tif n%2:\n\t\t\t\tprod =prod * (a + (n//2)*d)\n\t\t\tanswer = prod%m\n\tprint(answer)","repo_name":"hamelin92/TIL","sub_path":"code_/swea/swea13550_product_seq.py","file_name":"swea13550_product_seq.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"41763490761","text":"import cv2\nimport numpy as np\nfrom PIL import Image, ImageDraw\n\n\ndef compute_color_histograms(frames: np.ndarray) -> np.ndarray:\n assert list(frames.shape[1:]) == [27, 48, 3], \"compute_color_histograms works only with frames of shape [27, 48, 3]\"\n histograms = np.empty([len(frames), 12, 6, 6, 6])\n\n for i in range(len(frames)):\n j = 0\n for y_low, y_high in [(0, 9), (9, 18), (18, 27)]:\n for x_low, x_high in [(0, 12), (12, 24), (24, 36), (36, 48)]:\n histograms[i, j] = cv2.calcHist([frames[i, y_low:y_high, x_low:x_high]],\n [0, 1, 2], None, [6, 6, 6], [0, 256, 0, 256, 0, 256])\n j += 1\n return histograms\n\n\ndef visualize_scenes_and_keyframes(frames: np.ndarray, scenes: np.ndarray, keyframes: np.ndarray, clusters: np.ndarray):\n nf, ih, iw, ic = frames.shape\n width = 25\n if len(frames) % width != 0:\n pad_with = width - len(frames) % width\n frames = np.concatenate([frames, np.zeros([pad_with, ih, iw, ic], np.uint8)])\n height = len(frames) // width\n\n scene = frames.reshape([height, width, ih, iw, ic])\n scene = np.concatenate(np.split(\n np.concatenate(np.split(scene, height), axis=2)[0], width\n ), axis=2)[0]\n\n img = Image.fromarray(scene)\n draw = ImageDraw.Draw(img, \"RGBA\")\n\n def draw_start_frame(frame_no):\n w = frame_no % width\n h = frame_no // width\n draw.rectangle([(w * iw, h * ih), (w * iw + 2, h * ih + ih - 1)], fill=(255, 0, 0))\n draw.polygon(\n [(w * iw + 7, h * ih + ih // 2 - 4), (w * iw + 12, h * ih + ih // 2), (w * iw + 7, h * ih + ih // 2 + 4)],\n fill=(255, 0, 0))\n draw.rectangle([(w * iw, h * ih + ih // 2 - 1), (w * iw + 7, h * ih + ih // 2 + 1)], fill=(255, 0, 0))\n\n def draw_end_frame(frame_no):\n w = frame_no % width\n h = frame_no // width\n draw.rectangle([(w * iw + iw - 1, h * ih), (w * iw + iw - 3, h * ih + ih - 1)], fill=(255, 0, 0))\n draw.polygon([(w * iw + iw - 8, h * ih + ih // 2 - 4), (w * iw + iw - 13, h * ih + ih // 2),\n (w * iw + iw - 8, h * ih + ih // 2 + 4)], fill=(255, 0, 0))\n draw.rectangle([(w * iw + iw - 1, h * ih + ih // 2 - 1), (w * iw + iw - 8, h * ih + ih // 2 + 1)],\n fill=(255, 0, 0))\n\n def draw_transition_frame(frame_no):\n w = frame_no % width\n h = frame_no // width\n draw.rectangle([(w * iw, h * ih), (w * iw + iw - 1, h * ih + ih - 1)], fill=(128, 128, 128, 180))\n\n def draw_key_frame(frame_no):\n w = frame_no % width\n h = frame_no // width\n draw.rectangle([(w * iw, h * ih), (w * iw + iw - 1, h * ih + ih - 1)], outline=(255, 255, 0))\n\n def draw_cluster_split(frame_no):\n w = frame_no % width\n h = frame_no // width\n draw.polygon(\n [(w * iw - .5, h * ih + ih // 2 - 6), (w * iw + 5, h * ih + ih // 2), (w * iw - .5, h * ih + ih // 2 + 6),\n (w * iw - 7, h * ih + ih // 2)], fill=(0, 255, 0), outline=(0, 0, 0))\n\n curr_frm, curr_scn, curr_kfm, curr_ctr = 0, 0, 0, 0\n\n while curr_scn < len(scenes):\n start, end = scenes[curr_scn]\n # gray out frames that are not in any scene\n while curr_frm < start:\n draw_transition_frame(curr_frm)\n curr_frm += 1\n\n # draw start and end of a scene\n draw_start_frame(curr_frm)\n draw_end_frame(end)\n\n # draw all keyframes in the scene\n while curr_kfm < len(keyframes) and keyframes[curr_kfm] <= end:\n draw_key_frame(keyframes[curr_kfm])\n curr_kfm += 1\n\n # draw all cluster splits in the scene\n while curr_ctr < len(clusters) and clusters[curr_ctr] <= end:\n draw_cluster_split(clusters[curr_ctr])\n curr_ctr += 1\n\n # go to the next scene\n curr_frm = end + 1\n curr_scn += 1\n\n # gray out the last frames that are not in any scene (if any)\n while curr_frm < nf:\n draw_transition_frame(curr_frm)\n curr_frm += 1\n\n return img\n","repo_name":"siret/somhunter","sub_path":"extractor/keyframe_selection/keyframe_selection_utils.py","file_name":"keyframe_selection_utils.py","file_ext":"py","file_size_in_byte":4092,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"31"}
+{"seq_id":"35586589111","text":"phonebook = {\"Chris\": \"555-1111\", \"Katie\": \"555-2222\", \"Joanne\": \"555-3333\"}\r\n\r\n\"\"\"\r\nprint(phonebook)\r\nprint(len(phonebook))\r\n\"\"\"\r\n\r\n\"\"\"\r\nCREATING A DICTIONARY WITH DICT\r\n\r\nmydictionary = dict(m=8, n=9)\r\nprint(mydictionary)\r\n\"\"\"\r\n\r\n\"\"\"\r\nCALLING AN ITEM IN THE DICTIONARY\r\n\r\nphonebook = {\"Chris\": \"555-1111\", \"Katie\": \"555-2222\", \"Joanne\": \"555-3333\"}\r\nphone = phonebook[\"Chris\"]\r\nprint(phone)\r\n\r\nname = \"Chris\"\r\nif name in phonebook:\r\n print(phonebook[name])\r\nelse:\r\n print(\"Not Found\")\r\n\"\"\"\r\n\r\n\"\"\"\r\nEDITING A DICTIONARY\r\n\r\nphonebook[\"Chris\"] = \"555-4444\"\r\nphonebook[\"Joe\"] = \"555-0123\"\r\nprint(phonebook)\r\n\"\"\"\r\n\r\n\"\"\"\r\nREMOVING THINGS FROM A DICTIONARY. DELETES KEY AND VALUE.\r\n\r\ndel phonebook[\"Chris\"]\r\nprint(phonebook)\r\n\"\"\"\r\n\r\n\"\"\"\r\nITERATE THROUGH KEYS. K IS THE ITERATOR\r\n\r\nfor k in phonebook:\r\n print(phonebook[k])\r\n\"\"\"\r\n\r\n\"\"\"\r\nITERATE THROUGH VALUES\r\n\r\nfor v in phonebook.values():\r\n print(v)\r\n\"\"\"\r\n\r\n\"\"\"\r\nITERATE THROUGH BOTH KEY AND VALUE PAIR WITH ITEMS METHOD. WHEN YOU USE ITEMS, YOU GET BOTH THE KEY AND THE VALUE. THE PARANTHASES THAT ARE RETURNED ARE A TUPLE. \r\n\r\nfor pair in phonebook.items():\r\n print(pair)\r\n\r\nIF YOU DON'T WANT A TUPLE TO BE RETURNED:\r\n\r\nfor k,v in phonebook.items():\r\n print(k,v)\r\n\"\"\"\r\n\r\n\"\"\"\r\nMETHODS\r\n\r\nCLEAR. WIPES DICTIONARY. \r\n\r\nGET METHOD. THE GET METHOD IS UNIQUE BECAUSE YOU CAN SPECIFY A DEFAULT VALUE, WHICH IS WHAT RETURNED IF PYTHON DOESN'T FIND THE KEY IN THE DICTIONARY. \r\nITS AN ERROR AVOIDING TECHNIQUE. \r\n\r\nKEYS. RETURNS ALL THE DICTIONARIES IN A SEQUENCE.\r\n\r\nPOP. RETURNS THE VALUE ASSOCIATED WITH THE SPECIFIED KEY AND THEN REMOVES THAT KEY-VALUE PAIR FROM THE DICTIONARY. \r\nTHINK OF IT AS YOU ARE POPPING THE ITEM OUT OF THE DICTIONARY.\r\n\"\"\"\r\n","repo_name":"Braxton22/MyDictionaries","sub_path":"dictionary start file.py","file_name":"dictionary start file.py","file_ext":"py","file_size_in_byte":1712,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"22201496034","text":"import math\n\nimport torch\n\n__all__ = [\n \"check_task_1\",\n \"check_task_2\",\n \"check_task_3\",\n \"check_task_4\"\n]\n\n\ndef check_task_1(pred_res, pred_attn):\n true_res = torch.tensor([[0.1212, 0.5156, -0.2394, -0.1912],\n [0.0999, 0.5376, -0.2558, -0.1143],\n [0.1348, 0.5492, -0.3327, -0.3267]])\n\n true_attn = torch.tensor([[0.3017, 0.3098, 0.3884],\n [0.2451, 0.3801, 0.3748],\n [0.2938, 0.2293, 0.4769]])\n\n assert torch.allclose(pred_res, true_res, rtol=1e-4, atol=1e-4), \"\\033[91m Something is wrong :(\"\n assert torch.allclose(pred_attn, true_attn, rtol=1e-4, atol=1e-4), \"\\033[91m Something is wrong :(\"\n print('\\033[92m Well done :)')\n\n\ndef check_task_2(pred_attn_output):\n true_attn_output = torch.tensor([[[0.0196, -0.0128, -0.0029, 0.0166],\n [0.0181, -0.0118, -0.0026, 0.0153],\n [0.0150, -0.0098, -0.0022, 0.0126]]])\n\n assert torch.allclose(pred_attn_output, true_attn_output, rtol=1e-4, atol=1e-4), \"\\033[91m Something is wrong :(\"\n print('\\033[92m Well done :)')\n\n\ndef check_task_3(pred_pe):\n true_pe = torch.zeros(128, 64)\n position = torch.arange(0, 128, dtype=torch.float).unsqueeze(1)\n div_term = torch.exp(torch.arange(0, 64, 2).float() * (-math.log(10000.0) / 64))\n true_pe[:, 0::2] = torch.sin(position * div_term)\n true_pe[:, 1::2] = torch.cos(position * div_term)\n assert torch.allclose(pred_pe, true_pe, rtol=1e-4, atol=1e-4), \"\\033[91m Something is wrong :(\"\n print('\\033[92m Well done :)')\n\n\ndef check_task_4(positional_encoding):\n x = torch.randn(1, 50, 64)\n diff = positional_encoding(x) - positional_encoding.pe[:, :x.shape[1]]\n assert torch.allclose(x, diff, rtol=1e-4, atol=1e-4), \"\\033[91m Something is wrong :(\"\n print('\\033[92m Well done :)')\n","repo_name":"mryab/dl-hse-ami","sub_path":"week08_transformers/check.py","file_name":"check.py","file_ext":"py","file_size_in_byte":1918,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"31"}
+{"seq_id":"71551163287","text":"\"\"\"\nGiven a linked list, reverse the nodes of a linked list k at a time and return its modified list.\n\nk is a positive integer and is less than or equal to the length of the linked list.\nIf the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.\n\nYou may not alter the values in the nodes, only nodes itself may be changed.\n\nOnly constant memory is allowed.\n\nFor example,\nGiven this linked list: 1->2->3->4->5\n\nFor k = 2, you should return: 2->1->4->3->5\n\nFor k = 3, you should return: 3->2->1->4->5\n\"\"\"\n\n# Definition for singly-linked list.\nimport time\n\n\nclass ListNode(object):\n\n def __init__(self, x):\n self.val = x\n self.next = None\n\n def __repr__(self):\n repr_str = ''\n node = self\n while node:\n repr_str += str(node.val) + ' -> '\n node = node.next\n return repr_str + 'None'\n\n\nclass Solution(object):\n\n def reverseKGroup(self, head, k):\n if not self.needReverse(head, k):\n return head\n head = self.reverseKNodes(head, k)\n i, prev, node = 0, None, head\n while i < k:\n prev = node\n node = node.next\n i += 1\n prev.next = self.reverseKGroup(node, k)\n return head\n\n def reverseKNodes(self, head, k):\n if head is None or head.next is None:\n return head\n prev, curr = None, head\n while curr and k:\n next = curr.next\n curr.next = prev\n prev = curr\n curr = next\n k -= 1\n node = prev\n while node.next:\n node = node.next\n node.next = curr\n return prev\n\n def needReverse(self, head, k):\n while k > 0:\n if not head:\n return False\n head = head.next\n k -= 1\n return True\n\n\na, b, c, d, e, f, g = (ListNode(i) for i in 'abcdefg')\ns = Solution()\na.next, b.next, c.next = b, c, d\nd.next, e.next, f.next = e, f, g\nprint(s.reverseKGroup(a, 5))\n","repo_name":"alphafan/LeetCode_Solution","sub_path":"025_Reverse_Nodes_in_k_Group.py","file_name":"025_Reverse_Nodes_in_k_Group.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"10798892613","text":"# /right/image_mono\nimport os\nimport rclpy\nfrom rclpy.node import Node\nimport json\nfrom std_msgs.msg import String\nfrom sensor_msgs.msg import Image\nfrom nav_msgs.msg import Odometry\nimport cv2 as cv\nfrom cv_bridge import CvBridge\nimport numpy as np\nfrom operator import add\nfrom statistics import mean\nfrom math import cos, sin\nimport math\nfrom theta_interfaces.srv import Passloc\nfrom rclpy.exceptions import ParameterNotDeclaredException\nfrom rcl_interfaces.msg import ParameterType\n\nclass NpEncoder(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(NpEncoder, self).default(obj)\n\n\nclass CoordsFilterMatcher(Node):\n\n\tdef __init__(self):\n\t\tsuper().__init__('coord_filter_match')\n\t\tself.subscription = self.create_subscription(\n\t\t\tString,\n\t\t\t'/centroid_depth',\n\t\t\tself.model_callback,\n\t\t\t10)\n\t\tself.subscription # prevent unused variable warning\n\n\t\tself.cli = self.create_client(Passloc, 'pass_loc')\n\t\twhile not self.cli.wait_for_service(timeout_sec=1.0):\n\t\t\tself.get_logger().info('service not available, waiting again...')\n\t\tself.req = Passloc.Request()\n\t\tself.main_dict = {}\n\t\tself.declare_parameter('threshold', '0.8')\n\n\n\tdef model_callback(self, msg):\n\t\tself.threshold = float(self.get_parameter('threshold').get_parameter_value().string_value)\n\t\tdata = json.loads(msg.data)\n\t\tif len(data)==0:\n\t\t\treturn\n\n\t\tnew_dict = {}\n\t\tfor key in data:\n\t\t\tsub_data = data[key]\n\t\t\tnew_coords =[]\n\t\t\tif key not in self.main_dict.keys():\n\t\t\t\tself.main_dict[key]=[]\n\t\t\t\tfor item in sub_data:\n\t\t\t\t\t self.main_dict[key].append(item)\n\t\t\t\t\t self.main_dict[key][-1].append(2)\n\t\t\telse:\n\t\t\t\tfor item in sub_data:\n\t\t\t\t\tmatch_found = False\n\t\t\t\t\tfor main_item in self.main_dict[key]:\n\t\t\t\t\t\tif match_found:\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\tif dist(main_item,item)= 5:\n\t\t\t\t\t\t# This is where it will go to the main database\n\t\t\t\t\t\tself.send_request(self.main_dict[key][i],key)\n\t\t\t\t\t\tindexes.append(i)\n\t\t\t\t\t\tself.get_logger().info(\"DATABASE NEW UPDATE\")\n\t\t\t\tindexes.reverse()\n\t\t\t\tfor i in indexes:\n\t\t\t\t\tself.main_dict[key].pop(i)\n\n\tdef send_request(self,data,key):\n\t\tself.req.class_id = int(key)\n\t\tself.req.x = float(data[0])\n\t\tself.req.y = float(data[1])\n\t\tself.req.z = float(data[2])\n\t\taccept = self.cli.call_async(self.req)\n\t\tself.get_logger().info(str(accept))\ndef dist(a,b):\n\ta2 = (a[0]/a[3]**2+a[1]/a[3]**2+a[2]/a[3]**2)**0.5\n\tb2 = (b[0]**2+b[1]**2+b[2]**2)**0.5\n\treturn ((a2-b2)**2)**0.5\n\n\ndef main(args=None):\n\tprint(os.getcwd())\n\trclpy.init(args=args)\n\n\tcoord_filter_match = CoordsFilterMatcher()\n\n\trclpy.spin(coord_filter_match)\n\n\t# Destroy the node explicitly\n\t# (optional - otherwise it will be done automatically\n\t# when the garbage collector destroys the node object)\n\tcoord_filter_match.destroy_node()\n\trclpy.shutdown()\n\n\nif __name__ == '__main__':\n\tprint(os.getcwd())\n\tmain()\n\n","repo_name":"VidishMehta001/Project_Theta","sub_path":"theta_pkgs/theta_pkgs/coords_filter_match.py","file_name":"coords_filter_match.py","file_ext":"py","file_size_in_byte":3521,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"32819808356","text":"import torch\nimport torch.nn as nn\nfrom . import resnet_module\nfrom . import blocks\n\nclass spacialFeatureExtractor(nn.Module):\n '''\n The spacial feature extractor part of the network\n '''\n def __init__(self, \n Encoder, \n encoder_block_dims = [256, 512, 1024, 2048],\n **kwargs\n ):\n '''\n Args:\n Encoder: \n The encoder network of the extractor\n encoder_block_dims: \n The dimensions of outputs from each block of the encoder\n \n Note:\n 1. The input_dim of DECODER is encoder_block_dims[-1]\n 2. The in_channel_list of MFF is encoder_block_dims\n 3. The out_channels of MFF is encoder_block_dims[-1] // 32\n '''\n super().__init__()\n # if the encoder is a resnet, \n # the output has init_decoder_channels of feature maps\n \n # by default, use resnet50 as encoder\n self.encoder = Encoder\n \n self.Decoder = blocks.Decoder(in_channels=encoder_block_dims[-1])\n self.MFF = blocks.MFF(in_channel_list=encoder_block_dims,\n out_channels=encoder_block_dims[-1] // 32)\n \n # the input_dim of refineblock is determined\n # by the decoder and mff, which is determined by the encoder\n # if the encoder is not resnet50\n # decoder, mff, refinement block should be changed accordingly\n self.refine = blocks.RefineBlock()\n \n def forward(self, x):\n x_b1, x_b2, x_b3, x_b4 = self.encoder(x)\n # params are used to acquire the upsampling shape\n up1_shape = [2 * x_b3.size(2), 2 * x_b3.size(3)]\n up2_shape = [2 * x_b2.size(2), 2 * x_b2.size(3)] \n up3_shape = [2 * x_b1.size(2), 2 * x_b1.size(3)]\n # up4 reconstruct to the shape before encoder's first conv2d\n up4_shape = [4 * x_b1.size(2), 4 * x_b1.size(3)]\n \n x_D = self.Decoder(x_b4, up1_shape, up2_shape, up3_shape, up4_shape)\n x_mff = self.MFF(x_b1, x_b2, x_b3, x_b4)\n \n # concat the x_D and x_mff\n depth = self.refine(torch.cat((x_D, x_mff), 1))\n \n # (B, 1, H, W) image\n return depth\n\n\n\ndef get_model(**kwargs):\n base_resnet50 = resnet_module.get_resnet50(pretrained=True)\n # encoder output a tuple of each block's output\n if kwargs == None or kwargs['encoder'] == 'resnet50':\n E = blocks.Encoder_resnet50(base=base_resnet50)\n model = spacialFeatureExtractor(Encoder=E,\n encoder_block_dims=[256, 512, 1024, 2048])\n return model","repo_name":"Ji-Xinyou/DIP-proj-DepthEstimation","sub_path":"model/Spacial_plan1/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2666,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"28150818312","text":"import cv2\nimport sys\nimport time\nimport numpy as np\nfrom absl import logging\nimport numpy as np\n\ndef reorder_image(img, input_order=\"HWC\"):\n \"\"\"Reorder images to 'HWC' order.\n\n If the input_order is (h, w), return (h, w, 1);\n If the input_order is (c, h, w), return (h, w, c);\n If the input_order is (h, w, c), return as it is.\n\n Args:\n img (ndarray): Input image.\n input_order (str): Whether the input order is 'HWC' or 'CHW'.\n If the input image shape is (h, w), input_order will not have\n effects. Default: 'HWC'.\n\n Returns:\n ndarray: reordered image.\n \"\"\"\n\n if input_order not in [\"HWC\", \"CHW\"]:\n raise ValueError(\n f\"Wrong input_order {input_order}. Supported input_orders are \"\n \"'HWC' and 'CHW'\"\n )\n if len(img.shape) == 2:\n img = img[..., None]\n if input_order == \"CHW\":\n img = img.transpose(1, 2, 0)\n return img\n\n\ndef to_y_channel(img):\n \"\"\"Change to Y channel of YCbCr.\n\n Args:\n img (ndarray): Images with range [0, 255].\n\n Returns:\n (ndarray): Images with range [0, 255] (float type) without round.\n \"\"\"\n img = img.astype(np.float32) / 255.0\n if img.ndim == 3 and img.shape[2] == 3:\n img = bgr2ycbcr(img, y_only=True)\n img = img[..., None]\n return img * 255.0\n\n\n###############################################################################\n# These processing code is copied and modified from official implement: #\n# https://github.com/open-mmlab/mmsr #\n###############################################################################\ndef imresize_np(img, scale, antialiasing=True):\n # Now the scale should be the same for H and W\n # input: img: Numpy, HWC RBG [0,1]\n # output: HWC RBG [0,1] w/o round\n # (Modified from\n # https://github.com/open-mmlab/mmsr/blob/master/codes/data/util.py)\n in_H, in_W, in_C = img.shape\n\n _, out_H, out_W = in_C, np.ceil(in_H * scale), np.ceil(in_W * scale)\n out_H, out_W = out_H.astype(np.int64), out_W.astype(np.int64)\n kernel_width = 4\n kernel = \"cubic\"\n\n # Return the desired dimension order for performing the resize. The\n # strategy is to perform the resize first along the dimension with the\n # smallest scale factor.\n # Now we do not support this.\n\n # get weights and indices\n weights_H, indices_H, sym_len_Hs, sym_len_He = _calculate_weights_indices(\n in_H, out_H, scale, kernel, kernel_width, antialiasing\n )\n weights_W, indices_W, sym_len_Ws, sym_len_We = _calculate_weights_indices(\n in_W, out_W, scale, kernel, kernel_width, antialiasing\n )\n # process H dimension\n # symmetric copying\n img_aug = np.zeros(((in_H + sym_len_Hs + sym_len_He), in_W, in_C))\n img_aug[sym_len_Hs : sym_len_Hs + in_H] = img\n\n sym_patch = img[:sym_len_Hs, :, :]\n sym_patch_inv = sym_patch[::-1]\n img_aug[0:sym_len_Hs] = sym_patch_inv\n\n sym_patch = img[-sym_len_He:, :, :]\n sym_patch_inv = sym_patch[::-1]\n img_aug[sym_len_Hs + in_H : sym_len_Hs + in_H + sym_len_He] = sym_patch_inv\n\n out_1 = np.zeros((out_H, in_W, in_C))\n kernel_width = weights_H.shape[1]\n for i in range(out_H):\n idx = int(indices_H[i][0])\n out_1[i, :, 0] = weights_H[i].dot(\n img_aug[idx : idx + kernel_width, :, 0].transpose(0, 1)\n )\n out_1[i, :, 1] = weights_H[i].dot(\n img_aug[idx : idx + kernel_width, :, 1].transpose(0, 1)\n )\n out_1[i, :, 2] = weights_H[i].dot(\n img_aug[idx : idx + kernel_width, :, 2].transpose(0, 1)\n )\n\n # process W dimension\n # symmetric copying\n out_1_aug = np.zeros((out_H, in_W + sym_len_Ws + sym_len_We, in_C))\n out_1_aug[:, sym_len_Ws : sym_len_Ws + in_W] = out_1\n\n sym_patch = out_1[:, :sym_len_Ws, :]\n sym_patch_inv = sym_patch[:, ::-1]\n out_1_aug[:, 0:sym_len_Ws] = sym_patch_inv\n\n sym_patch = out_1[:, -sym_len_We:, :]\n sym_patch_inv = sym_patch[:, ::-1]\n out_1_aug[:, sym_len_Ws + in_W : sym_len_Ws + in_W + sym_len_We] = sym_patch_inv\n\n out_2 = np.zeros((out_H, out_W, in_C))\n kernel_width = weights_W.shape[1]\n for i in range(out_W):\n idx = int(indices_W[i][0])\n out_2[:, i, 0] = out_1_aug[:, idx : idx + kernel_width, 0].dot(weights_W[i])\n out_2[:, i, 1] = out_1_aug[:, idx : idx + kernel_width, 1].dot(weights_W[i])\n out_2[:, i, 2] = out_1_aug[:, idx : idx + kernel_width, 2].dot(weights_W[i])\n\n return out_2.clip(0, 255)\n\n\ndef _cubic(x):\n absx = np.abs(x)\n absx2 = absx ** 2\n absx3 = absx ** 3\n return (1.5 * absx3 - 2.5 * absx2 + 1) * ((absx <= 1).astype(np.float64)) + (\n -0.5 * absx3 + 2.5 * absx2 - 4 * absx + 2\n ) * (((absx > 1) * (absx <= 2)).astype(np.float64))\n\n\ndef _calculate_weights_indices(\n in_length, out_length, scale, kernel, kernel_width, antialiasing\n):\n if (scale < 1) and (antialiasing):\n # Use a modified kernel to simultaneously interpolate and antialias\n # larger kernel width\n kernel_width = kernel_width / scale\n\n # Output-space coordinates\n x = np.linspace(1, out_length, out_length)\n\n # Input-space coordinates. Calculate the inverse mapping such that 0.5\n # in output space maps to 0.5 in input space, and 0.5+scale in output\n # space maps to 1.5 in input space.\n u = x / scale + 0.5 * (1 - 1 / scale)\n\n # What is the left-most pixel that can be involved in the computation?\n left = np.floor(u - kernel_width / 2)\n\n # What is the maximum number of pixels that can be involved in the\n # computation? Note: it's OK to use an extra pixel here; if the\n # corresponding weights are all zero, it will be eliminated at the end\n # of this function.\n P = (np.ceil(kernel_width) + 2).astype(np.int32)\n\n # The indices of the input pixels involved in computing the k-th output\n # pixel are in row k of the indices matrix.\n indices = left.reshape(int(out_length), 1).repeat(P, axis=1) + np.linspace(\n 0, P - 1, P\n ).reshape(1, int(P)).repeat(out_length, axis=0)\n\n # The weights used to compute the k-th output pixel are in row k of the\n # weights matrix.\n distance_to_center = u.reshape(int(out_length), 1).repeat(P, axis=1) - indices\n # apply cubic kernel\n if (scale < 1) and (antialiasing):\n weights = scale * _cubic(distance_to_center * scale)\n else:\n weights = _cubic(distance_to_center)\n # Normalize the weights matrix so that each row sums to 1.\n weights_sum = np.sum(weights, 1).reshape(int(out_length), 1)\n weights = weights / weights_sum.repeat(P, axis=1)\n\n # If a column in weights is all zero, get rid of it. only consider the\n # first and last column.\n weights_zero_tmp = np.sum((weights == 0), 0)\n if not np.isclose(weights_zero_tmp[0], 0, rtol=1e-6):\n indices = indices[:, 1 : 1 + int(P) - 2]\n weights = weights[:, 1 : 1 + int(P) - 2]\n if not np.isclose(weights_zero_tmp[-1], 0, rtol=1e-6):\n indices = indices[:, 0 : 0 + int(P) - 2]\n weights = weights[:, 0 : 0 + int(P) - 2]\n weights = weights.copy()\n indices = indices.copy()\n sym_len_s = -indices.min() + 1\n sym_len_e = indices.max() - in_length\n indices = indices + sym_len_s - 1\n return weights, indices, int(sym_len_s), int(sym_len_e)\n\n\ndef calculate_psnr(img1, img2):\n # img1 and img2 have range [0, 255]\n img1 = img1.astype(np.float64)\n img2 = img2.astype(np.float64)\n mse = np.mean((img1 - img2) ** 2)\n if mse == 0:\n return float(\"inf\")\n return 20 * np.log10(255.0 / np.sqrt(mse))\n\n\ndef _ssim(img1, img2):\n C1 = (0.01 * 255) ** 2\n C2 = (0.03 * 255) ** 2\n\n img1 = img1.astype(np.float64)\n img2 = img2.astype(np.float64)\n kernel = cv2.getGaussianKernel(11, 1.5)\n window = np.outer(kernel, kernel.transpose())\n\n mu1 = cv2.filter2D(img1, -1, window)[5:-5, 5:-5] # valid\n mu2 = cv2.filter2D(img2, -1, window)[5:-5, 5:-5]\n mu1_sq = mu1 ** 2\n mu2_sq = mu2 ** 2\n mu1_mu2 = mu1 * mu2\n sigma1_sq = cv2.filter2D(img1 ** 2, -1, window)[5:-5, 5:-5] - mu1_sq\n sigma2_sq = cv2.filter2D(img2 ** 2, -1, window)[5:-5, 5:-5] - mu2_sq\n sigma12 = cv2.filter2D(img1 * img2, -1, window)[5:-5, 5:-5] - mu1_mu2\n\n ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / (\n (mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2)\n )\n return ssim_map.mean()\n\n\ndef calculate_ssim(img1, img2):\n \"\"\"calculate SSIM\n the same outputs as MATLAB's\n img1, img2: [0, 255]\n \"\"\"\n if not img1.shape == img2.shape:\n raise ValueError(\"Input images must have the same dimensions.\")\n if img1.ndim == 2:\n return _ssim(img1, img2)\n elif img1.ndim == 3:\n if img1.shape[2] == 3:\n ssims = []\n for _ in range(3):\n ssims.append(_ssim(img1, img2))\n return np.array(ssims).mean()\n elif img1.shape[2] == 1:\n return _ssim(np.squeeze(img1), np.squeeze(img2))\n else:\n raise ValueError(\"Wrong input image dimensions.\")\n\n\ndef rgb2ycbcr(img, only_y=True):\n \"\"\"Convert rgb to ycbcr\n only_y: only return Y channel\n Input:\n uint8, [0, 255]\n float, [0, 1]\n \"\"\"\n in_img_type = img.dtype\n img.astype(np.float32)\n if in_img_type != np.uint8:\n img *= 255.0\n img = img[:, :, ::-1]\n\n # convert\n if only_y:\n rlt = np.dot(img, [24.966, 128.553, 65.481]) / 255.0 + 16.0\n else:\n rlt = np.matmul(\n img,\n [\n [24.966, 112.0, -18.214],\n [128.553, -74.203, -93.786],\n [65.481, -37.797, 112.0],\n ],\n ) / 255.0 + [16, 128, 128]\n if in_img_type == np.uint8:\n rlt = rlt.round()\n else:\n rlt /= 255.0\n return rlt.astype(in_img_type)","repo_name":"Mind23-2/MindCode-40","sub_path":"src/utils/eval_util.py","file_name":"eval_util.py","file_ext":"py","file_size_in_byte":9849,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"14861457036","text":"import numpy.polynomial\n\nclass G2Polynomial:\n \"\"\"\n This class represents a polynomial in GF(2). It wraps and extends numpy's\n Polynomial class.\n\n The constructor for this class takes a string of binary digits, rather than\n the list of coefficients used by Polynomial. To create a G2Polynomial for\n x^5 + x^3 + 1, do:\n\n myPolynomial = G2Polynomial(\"101001\")\n\n \"\"\"\n\n def __init__(self, initValue):\n if isinstance(initValue, str):\n coefficients = list()\n for digit in initValue:\n coefficients.insert(0, int(digit))\n self.polynomial = numpy.polynomial.Polynomial(coefficients)\n\n elif isinstance(initValue, numpy.polynomial.Polynomial):\n self.polynomial = initValue\n\n else:\n self.polynomial = None\n\n self.reduce()\n\n def reduce(self):\n if self.polynomial:\n coefficients = list()\n for coefficient in self.polynomial:\n coefficients.append(coefficient % 2)\n self.polynomial = numpy.polynomial.Polynomial(coefficients)\n\n def __str__(self):\n power = self.polynomial.degree()\n first = True\n polynomialString = \"\"\n for coefficient in reversed(list(self.polynomial)):\n if coefficient != 0 or (power == 0 and first):\n if first:\n first = False\n else:\n polynomialString += \" + \"\n\n if power == 0 or coefficient > 1:\n polynomialString += str(int(coefficient))\n if power >= 1:\n polynomialString += \"x\"\n if power >= 2:\n polynomialString += \"^\" + str(power)\n\n power -= 1\n\n return polynomialString\n\n def toBinaryString(self, minDigits = 0):\n binaryString = \"\"\n\n for coefficient in reversed(list(self.polynomial)):\n binaryString += str(int(coefficient))\n\n while len(binaryString) < minDigits:\n binaryString = \"0\" + binaryString;\n\n return binaryString\n\n def degree(self):\n return self.polynomial.degree()\n\n def __add__(self, other):\n return G2Polynomial(self.polynomial.__add__(other.polynomial))\n\n def __mul__(self, other):\n return G2Polynomial(self.polynomial.__mul__(other.polynomial))\n\n def __mod__(self, other):\n return G2Polynomial(self.polynomial.__mod__(other.polynomial))\n\n def __pow__(self, other):\n return G2Polynomial(self.polynomial.__pow__(other))\n\n","repo_name":"tommythorsen/documents","sub_path":"generating-s-boxes/scripts/auxiliary/g2polynomial.py","file_name":"g2polynomial.py","file_ext":"py","file_size_in_byte":2558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"8649415910","text":"import logging\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable, NamedTuple, Protocol\n\nimport numpy as np\nimport numpy.typing as npt\n\nfrom ..cli_utils import wrap_main\nfrom ..io_utils import get_stripped_lines\nfrom ..logs import setup_logging\n\nlogger = logging.getLogger(__name__)\n\n\nclass Position(NamedTuple):\n y: int\n x: int\n\n\n@dataclass\nclass Board:\n tiles: npt.NDArray[np.uint8]\n start_position: Position\n end_position: Position\n\n\ndef parse_board(filename: Path) -> Board:\n start_position: Position | None = None\n end_position: Position | None = None\n lines: list[list[int]] = []\n a_ord = ord(\"a\")\n for row_idx, line in enumerate(get_stripped_lines(filename)):\n if \"S\" in line:\n assert start_position is None\n start_position = Position(x=line.index(\"S\"), y=row_idx)\n line = line.replace(\"S\", \"a\")\n if \"E\" in line:\n assert end_position is None\n end_position = Position(x=line.index(\"E\"), y=row_idx)\n line = line.replace(\"E\", \"z\")\n elevations = [ord(c) - a_ord for c in line]\n lines.append(elevations)\n tiles = np.array(lines, dtype=np.uint8)\n assert start_position is not None\n assert end_position is not None\n return Board(tiles=tiles, start_position=start_position, end_position=end_position)\n\n\ndef argmin2d(array: npt.NDArray[np.uint32]) -> Position:\n y, x = np.unravel_index(np.argmin(array), array.shape)\n return Position(y=int(y), x=int(x))\n\n\nclass CanClimbCallback(Protocol):\n def __call__(self, current_elevation: int, neighbor_elevation: int) -> bool:\n ...\n\n\nclass EarlyStoppingCallback(Protocol):\n def __call__(self, neighbor_position: Position, neighbor_elevation: int) -> bool:\n ...\n\n\ndef find_path(\n tiles: npt.NDArray[np.uint8],\n *,\n start_position: Position,\n can_climb_callback: CanClimbCallback,\n early_stopping_callback: EarlyStoppingCallback,\n) -> int:\n logger.debug(\"Searching for best path from %s\", start_position)\n height, width = tiles.shape\n visited = np.zeros_like(tiles, dtype=bool)\n costs = np.full_like(tiles, fill_value=np.iinfo(np.uint32).max, dtype=np.uint32)\n costs[start_position] = 0\n\n def get_unvisited_neighbors(position: Position) -> Iterable[Position]:\n current_elevation = tiles[position]\n north = Position(y=position.y - 1, x=position.x)\n if (\n north.y >= 0\n and not visited[north]\n and can_climb_callback(current_elevation, tiles[north])\n ):\n yield north\n south = Position(y=position.y + 1, x=position.x)\n if (\n south.y < height\n and not visited[south]\n and can_climb_callback(current_elevation, tiles[south])\n ):\n yield south\n west = Position(y=position.y, x=position.x - 1)\n if (\n west.x >= 0\n and not visited[west]\n and can_climb_callback(current_elevation, tiles[west])\n ):\n yield west\n east = Position(y=position.y, x=position.x + 1)\n if (\n east.x < width\n and not visited[east]\n and can_climb_callback(current_elevation, tiles[east])\n ):\n yield east\n\n while not np.all(visited):\n # get 2d index of lowest cost item\n lowest_cost_index = argmin2d(np.where(visited, np.inf, costs))\n lowest_cost = costs[lowest_cost_index]\n logger.debug(\"Visiting %s with cost %d\", lowest_cost_index, lowest_cost)\n unvisited_neighbors = get_unvisited_neighbors(lowest_cost_index)\n neighbor_cost: int = lowest_cost + 1\n for neighbor_idx in unvisited_neighbors:\n costs[neighbor_idx] = neighbor_cost\n logger.debug(\"Found neighbor %s with cost %d\", neighbor_idx, neighbor_cost)\n if early_stopping_callback(neighbor_idx, tiles[neighbor_idx]):\n logger.debug(\"Early stopping at %s\", neighbor_idx)\n return neighbor_cost\n visited[lowest_cost_index] = True\n\n raise AssertionError(\"Algorithm should have stopped early\")\n\n\n@wrap_main\ndef main(filename: Path) -> str:\n board = parse_board(filename)\n cost = find_path(\n board.tiles,\n start_position=board.start_position,\n can_climb_callback=(\n lambda current_elevation, neighbor_elevation: neighbor_elevation\n <= current_elevation + 1\n ),\n early_stopping_callback=(\n lambda neighbor_position, neighbor_elevation: neighbor_position\n == board.end_position\n ),\n )\n return str(cost)\n\n\nif __name__ == \"__main__\":\n setup_logging()\n main()\n","repo_name":"kurazu/advent_of_code_2022","sub_path":"advent/day_12/task_1.py","file_name":"task_1.py","file_ext":"py","file_size_in_byte":4728,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"19903232581","text":"import sys\nfrom Hilltools import *\n\n# Scorrere in fondo al programma per leggerne il funzionamento passo passo\n\ndef create_indexes(block):\n indexes = []\n for ch in block:\n indexes.append(indexof(ch))\n return indexes\n\n\ndef create_characters(ciphervalues):\n chars = []\n for val in ciphervalues:\n chars.append(gamma[int(val)])\n return ''.join(chars)\n\n\ndef cipher_block(plainblock, key):\n blockvalues = create_indexes(plainblock)\n ciphervalues = dot_product(key, blockvalues)\n cipherblock = create_characters(ciphervalues)\n return cipherblock\n\n\ndef encrypt(text, key):\n text = clean(text)\n m = len(key)\n blocks = []\n cipherblocks = []\n for i in range(0,len(text),m):\n blocks.append(text[i:i+m])\n if len(blocks[-1])!= m:\n for i in range(len(blocks[-1]),m):\n blocks[-1] = blocks[-1] + 'a'\n for block in blocks:\n cipherblocks.append(cipher_block(block,key))\n return ''.join(cipherblocks)\n\n\ndef decrypt(text, key):\n key = modMatInv(key, len(gamma))\n return encrypt(text,key)\n\n\ndef shiftLeft(v):\n temp = v[0]\n for i in range(0,len(v)-1):\n v[i] = v[i+1]\n v[-1] = temp\n\n\ndef find_key(pt, ct, m): # pt e ct sono liste di indici. Questa funzione prova a rompere il cifrario di Hill\n pairs = []\n for i in range(0,len(pt),m):\n pairs.append((create_indexes(pt[i:i+m]),create_indexes(ct[i:i+m])))\n if len(pairs) < m:\n raise Exception(\"Non ci sono abbastanza coppie plaintext-ciphertext\")\n k = 0\n while k < len(pairs):\n pstar = []\n cstar = []\n for i in range(0,m):\n pstar.append(pairs[i][0]) # P* è una matrice m x m dove ogni riga è il known plaintext\n cstar.append(pairs[i][1]) # C* è una matrice m x m dove cstar[i] = ciphertext(plaintext[i])\n try:\n key = dot_product(numpy.transpose(cstar),modMatInv(numpy.transpose(pstar),len(gamma))) # applico la formula\n print(\"!!FOUND THE KEY!!\")\n return key\n except:\n shiftLeft(pairs) # Provo a vedere che chiave riesco a ottenere shiftando a sinistra il vettore delle coppie, aggiornando quindi P* e C*\n k = k + 1\n return None\n\ndef key2str(key):\n k2s = []\n for row in key:\n k2srow = ''\n for val in row:\n k2srow = k2srow + str(val) + ' '\n k2s.append(k2srow)\n return str(k2s).replace(\",\",\"\\r\\n\").replace(\"[\",\"\\r\\n\").replace(\"]\",\"\")\n\n\n##################################################################################################################\n\nmainKey = [ [1,2,3]\n ,[3,1,1]\n ,[1,2,4] ]\n\n\n# Il programma riceve come input da riga di comando il nome del file da cui leggere il testo da cifrare\n\n\nf = open(sys.argv[1])\ntxt = \"\"\nfor line in f.readlines():\n txt += line\ntxt = clean(txt)\n\n# E' possibile definire chiavi differenti ridefinendo \"mainKey\"\nkey = mainKey\n\n# Dimostrazione del funzionamento del cifrario di Hill\nciphertext = encrypt(txt,key)\nprint(\"Input text: \"+txt)\nprint(\"Ciphertext: \"+ciphertext)\ndecrypted = decrypt(ciphertext,key)\nprint(\"Decrypted: \"+decrypt(ciphertext,key))\n\n\n# Avendo a disposizione coppie di plaintext - ciphertext proviamo a ricavare la chiave che abbiamo utilizzato a partire dai appena calcolati\n\nprint(\"*********** ATTACKING HILL CIPHER ***********\")\nguessed_key = find_key(txt,ciphertext,len(key))\nif guessed_key is not None:\n print(\"Decryption of ciphertext using the guessed key:\" + key2str(guessed_key))\n print(decrypt(ciphertext,guessed_key))\n\n","repo_name":"FrancescoTerrosi/DSP","sub_path":"set-1/es3-2/Hill.py","file_name":"Hill.py","file_ext":"py","file_size_in_byte":3559,"program_lang":"python","lang":"it","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"1560862331","text":"import sys\n\ninput = sys.stdin.readline\n\nT = int(input())\n\nfor t in range(1,T+1):\n n = int(input())\n price = list(map(int,input().split()))\n\n price.reverse()\n\n max_p = -1\n money = 0\n for p in price:\n if p > max_p:\n max_p = p\n else:\n money += max_p - p\n print('#' + str(t), money)","repo_name":"TRASALBY/Problem-Solving","sub_path":"SW Expert Academy/1859_백만장자 프로젝트.py","file_name":"1859_백만장자 프로젝트.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"9958848644","text":"from django.conf.urls import url\n\nfrom . import views\n\napp_name = 'login'\n\nurlpatterns = [\n url(r'^auth/register', views.register, name='register'),\n url(r'^auth/login$', views.enter, name='enter'),\n url(r'^auth/logout$', views.logout, name='logout'),\n]","repo_name":"Konstantin1996/Django","sub_path":"project_blog/Scripts/blog/login/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"18813674979","text":"class Node:\n def __init__(self,data):\n self.data = data\n self.next = None\n self.prev = None\n\nclass DoubleLinkList:\n def __init__(self):\n self.start = None\n # self.end = None\n \n \n\n def insert_at_last(self,data):\n if self.start == None:\n new_node = Node(data)\n self.start = new_node\n else:\n new_node = Node(data)\n temp = self.start\n while temp.next != None:\n temp = temp.next\n temp.next = new_node\n new_node.prev = temp\n\n \n def reverse(self):\n curr = self.start\n back = None\n while curr != None :\n forword = curr.next\n curr.next = back\n curr.prev = forword\n back = curr\n curr = forword\n self.start = back\n\n def view_list(self):\n if self.start == None:\n print(\"Link list is empty.\")\n return\n else:\n temp = self.start\n while temp != None:\n print(temp.data,end=\" \")\n temp = temp.next\n print()\n\nif __name__ == '__main__':\n DL = DoubleLinkList()\n DL.insert_at_last(10)\n DL.insert_at_last(20)\n DL.insert_at_last(30)\n DL.insert_at_last(40)\n DL.reverse()\n \n DL.view_list()","repo_name":"Saurabh1Barasiya/100_days_of_code","sub_path":"DSA/LinkList/reverse_double_linklist.py","file_name":"reverse_double_linklist.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"41180785569","text":"# %% set up environment\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\njoin = os.path.join\nfrom tqdm import tqdm\nimport torch\nfrom torch.utils.data import Dataset, DataLoader\nimport monai\nfrom segment_anything import sam_model_registry\nfrom segment_anything.utils.transforms import ResizeLongestSide\nimport argparse\n# set seeds\ntorch.manual_seed(2023)\nnp.random.seed(2023)\n\n\n#%% create a dataset class to load npz data and return back image embeddings and ground truth\nclass NpyDataset(Dataset): \n def __init__(self, data_root):\n self.data_root = data_root\n self.gt_path = join(data_root, 'npy_gts')\n self.embed_path = join(data_root, 'npy_embs')\n self.npy_files = sorted(os.listdir(self.gt_path))\n \n def __len__(self):\n return len(self.npy_files)\n\n def __getitem__(self, index):\n gt2D = np.load(join(self.gt_path, self.npy_files[index]))\n img_embed = np.load(join(self.embed_path, self.npy_files[index]))\n y_indices, x_indices = np.where(gt2D > 0)\n x_min, x_max = np.min(x_indices), np.max(x_indices)\n y_min, y_max = np.min(y_indices), np.max(y_indices)\n # add perturbation to bounding box coordinates\n H, W = gt2D.shape\n x_min = max(0, x_min - np.random.randint(0, 20))\n x_max = min(W, x_max + np.random.randint(0, 20))\n y_min = max(0, y_min - np.random.randint(0, 20))\n y_max = min(H, y_max + np.random.randint(0, 20))\n bboxes = np.array([x_min, y_min, x_max, y_max])\n # convert img embedding, mask, bounding box to torch tensor\n return torch.tensor(img_embed).float(), torch.tensor(gt2D[None, :,:]).long(), torch.tensor(bboxes).float()\n\n# %% set up parser\nparser = argparse.ArgumentParser()\nparser.add_argument('-i', '--tr_npy_path', type=str, default='data/Tr_npy', help='path to training npy files; two subfolders: npy_gts and npy_embs')\nparser.add_argument('--task_name', type=str, default='SAM-ViT-B')\nparser.add_argument('--model_type', type=str, default='vit_b')\nparser.add_argument('--checkpoint', type=str, default='work_dir/SAM/sam_vit_b_01ec64.pth')\nparser.add_argument('--device', type=str, default='cuda:0')\nparser.add_argument('--work_dir', type=str, default='./work_dir')\n# train\nparser.add_argument('--num_epochs', type=int, default=1000)\nparser.add_argument('--batch_size', type=int, default=8)\nparser.add_argument('--lr', type=float, default=1e-5)\nparser.add_argument('--weight_decay', type=float, default=0)\nargs = parser.parse_args()\n\n\n# %% set up model for fine-tuning \ndevice = args.device\nmodel_save_path = join(args.work_dir, args.task_name)\nos.makedirs(model_save_path, exist_ok=True)\nsam_model = sam_model_registry[args.model_type](checkpoint=args.checkpoint).to(device)\nsam_model.train()\n\n# Set up the optimizer, hyperparameter tuning will improve performance here\noptimizer = torch.optim.Adam(sam_model.mask_decoder.parameters(), lr=args.lr, weight_decay=args.weight_decay)\nseg_loss = monai.losses.DiceCELoss(sigmoid=True, squared_pred=True, reduction='mean')\n# regress loss for IoU/DSC prediction; (ignored for simplicity but will definitely included in the near future)\n# regress_loss = torch.nn.MSELoss(reduction='mean')\n#%% train\nnum_epochs = args.num_epochs\nlosses = []\nbest_loss = 1e10\ntrain_dataset = NpyDataset(args.tr_npy_path)\ntrain_dataloader = DataLoader(train_dataset, batch_size=args.batch_size, shuffle=True)\nfor epoch in range(num_epochs):\n epoch_loss = 0\n # Just train on the first 20 examples\n for step, (image_embedding, gt2D, boxes) in enumerate(tqdm(train_dataloader)):\n # do not compute gradients for image encoder and prompt encoder\n with torch.no_grad():\n # convert box to 1024x1024 grid\n box_np = boxes.numpy()\n sam_trans = ResizeLongestSide(sam_model.image_encoder.img_size)\n box = sam_trans.apply_boxes(box_np, (gt2D.shape[-2], gt2D.shape[-1]))\n box_torch = torch.as_tensor(box, dtype=torch.float, device=device)\n if len(box_torch.shape) == 2:\n box_torch = box_torch[:, None, :] # (B, 1, 4)\n \n sparse_embeddings, dense_embeddings = sam_model.prompt_encoder(\n points=None,\n boxes=box_torch,\n masks=None,\n )\n low_res_masks, iou_predictions = sam_model.mask_decoder(\n image_embeddings=image_embedding.to(device), # (B, 256, 64, 64)\n image_pe=sam_model.prompt_encoder.get_dense_pe(), # (1, 256, 64, 64)\n sparse_prompt_embeddings=sparse_embeddings, # (B, 2, 256)\n dense_prompt_embeddings=dense_embeddings, # (B, 256, 64, 64)\n multimask_output=False,\n )\n\n loss = seg_loss(low_res_masks, gt2D.to(device))\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n epoch_loss += loss.item()\n epoch_loss /= step\n losses.append(epoch_loss)\n print(f'EPOCH: {epoch}, Loss: {epoch_loss}')\n # save the model checkpoint\n torch.save(sam_model.state_dict(), join(model_save_path, 'sam_model_latest.pth'))\n # save the best model\n if epoch_loss < best_loss:\n best_loss = epoch_loss\n torch.save(sam_model.state_dict(), join(model_save_path, 'sam_model_best.pth'))\n\n # %% plot loss\n plt.plot(losses)\n plt.title('Dice + Cross Entropy Loss')\n plt.xlabel('Epoch')\n plt.ylabel('Loss')\n # plt.show() # comment this line if you are running on a server\n plt.savefig(join(model_save_path, 'train_loss.png'))\n plt.close()\n\n","repo_name":"Minjaeun/MedSAM","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5557,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"}
+{"seq_id":"10052347667","text":"\"\"\"Python API for the lab streaming layer.\n\nThe lab streaming layer provides a set of functions to make instrument data\naccessible in real time within a lab network. From there, streams can be\npicked up by recording programs, viewing programs or custom experiment\napplications that access data streams in real time.\n\nThe API covers two areas:\n- The \"push API\" allows to create stream outlets and to push data (regular\n or irregular measurement time series, event data, coded audio/video frames,\n etc.) into them.\n- The \"pull API\" allows to create stream inlets and read time-synched\n experiment data from them (for recording, viewing or experiment control).\n\npylsl has been tested with Python 2.7 and 3.4.\n\n\"\"\"\n\nimport os\nimport platform\nimport struct\nfrom ctypes import CDLL, util, byref, c_char_p, c_void_p, c_double, c_int, \\\n c_long, c_float, c_short, c_byte, c_longlong, cast, POINTER\n\n__all__ = ['IRREGULAR_RATE', 'DEDUCED_TIMESTAMP', 'FOREVER', 'cf_float32',\n 'cf_double64', 'cf_string', 'cf_int32', 'cf_int16', 'cf_int8',\n 'cf_int64', 'cf_undefined', 'protocol_version', 'library_version',\n 'local_clock', 'StreamInfo', 'StreamOutlet', 'resolve_streams',\n 'resolve_byprop', 'resolve_bypred', 'StreamInlet', 'XMLElement',\n 'ContinuousResolver', 'TimeoutError', 'LostError',\n 'InvalidArgumentError', 'InternalError', 'stream_info',\n 'stream_outlet', 'stream_inlet', 'xml_element', 'timeout_error',\n 'lost_error', 'vectorf', 'vectord', 'vectorl', 'vectori',\n 'vectors', 'vectorc', 'vectorstr', 'resolve_stream']\n\n# =================\n# === Constants ===\n# =================\n\n# Constant to indicate that a stream has variable sampling rate.\nIRREGULAR_RATE = 0.0\n\n# Constant to indicate that a sample has the next successive time stamp\n# according to the stream's defined sampling rate. Optional optimization to\n# transmit less data per sample.\nDEDUCED_TIMESTAMP = -1.0\n\n# A very large time value (ca. 1 year); can be used in timeouts.\nFOREVER = 32000000.0\n\n# Value formats supported by LSL. LSL data streams are sequences of samples,\n# each of which is a same-size vector of values with one of the below types.\n\n# For up to 24-bit precision measurements in the appropriate physical unit (\n# e.g., microvolts). Integers from -16777216 to 16777216 are represented\n# accurately.\ncf_float32 = 1\n# For universal numeric data as long as permitted by network and disk budget.\n# The largest representable integer is 53-bit.\ncf_double64 = 2\n# For variable-length ASCII strings or data blobs, such as video frames,\n# complex event descriptions, etc.\ncf_string = 3\n# For high-rate digitized formats that require 32-bit precision. Depends\n# critically on meta-data to represent meaningful units. Useful for\n# application event codes or other coded data.\ncf_int32 = 4\n# For very high bandwidth signals or CD quality audio (for professional audio\n# float is recommended).\ncf_int16 = 5\n# For binary signals or other coded data.\ncf_int8 = 6\n# For now only for future compatibility. Support for this type is not\n# available on all languages and platforms.\ncf_int64 = 7\n# Can not be transmitted.\ncf_undefined = 0\n\n# Post processing flags\nproc_none = 0\nproc_clocksync = 1\nproc_dejitter = 2\nproc_monotonize = 4\nproc_threadsafe = 8\nproc_ALL = proc_none | proc_clocksync | proc_dejitter | proc_monotonize | proc_threadsafe\n\n\n# ==========================================================\n# === Free Functions provided by the lab streaming layer ===\n# ==========================================================\n\ndef protocol_version():\n \"\"\"Protocol version.\n\n The major version is protocol_version() / 100;\n The minor version is protocol_version() % 100;\n\n Clients with different minor versions are protocol-compatible with each \n other while clients with different major versions will refuse to work \n together.\n\n \"\"\"\n return lib.lsl_protocol_version()\n\n\ndef library_version():\n \"\"\"Version of the underlying liblsl library.\n\n The major version is library_version() / 100;\n The minor version is library_version() % 100;\n\n \"\"\"\n return lib.lsl_library_version()\n\n \ndef local_clock():\n \"\"\"Obtain a local system time stamp in seconds.\n\n The resolution is better than a milisecond. This reading can be used to \n assign time stamps to samples as they are being acquired.\n\n If the \"age\" of a sample is known at a particular time (e.g., from USB \n transmission delays), it can be used as an offset to lsl_local_clock() to \n obtain a better estimate of when a sample was actually captured. See \n StreamOutlet.push_sample() for a use case.\n\n \"\"\"\n return lib.lsl_local_clock()\n\n \n# ==========================\n# === Stream Declaration ===\n# ==========================\n \nclass StreamInfo:\n \"\"\"The StreamInfo object stores the declaration of a data stream.\n\n Represents the following information:\n a) stream data format (#channels, channel format)\n b) core information (stream name, content type, sampling rate)\n c) optional meta-data about the stream content (channel labels, \n measurement units, etc.)\n\n Whenever a program wants to provide a new stream on the lab network it will \n typically first create a StreamInfo to describe its properties and then \n construct a StreamOutlet with it to create the stream on the network. \n Recipients who discover the outlet can query the StreamInfo; it is also \n written to disk when recording the stream (playing a similar role as a file \n header).\n\n \"\"\"\n\n def __init__(self, name='untitled', type='', channel_count=1,\n nominal_srate=IRREGULAR_RATE, channel_format=cf_float32,\n source_id='', handle=None):\n \"\"\"Construct a new StreamInfo object.\n\n Core stream information is specified here. Any remaining meta-data can \n be added later.\n \n Keyword arguments:\n name -- Name of the stream. Describes the device (or product series) \n that this stream makes available (for use by programs, \n experimenters or data analysts). Cannot be empty.\n type -- Content type of the stream. By convention LSL uses the content \n types defined in the XDF file format specification where \n applicable (https://github.com/sccn/xdf). The content type is the \n preferred way to find streams (as opposed to searching by name).\n channel_count -- Number of channels per sample. This stays constant for \n the lifetime of the stream. (default 1)\n nominal_srate -- The sampling rate (in Hz) as advertised by the data \n source, regular (otherwise set to IRREGULAR_RATE).\n (default IRREGULAR_RATE)\n channel_format -- Format/type of each channel. If your channels have \n different formats, consider supplying multiple \n streams or use the largest type that can hold \n them all (such as cf_double64). It is also allowed \n to pass this as a string, without the cf_ prefix,\n e.g., 'float32' (default cf_float32)\n source_id -- Unique identifier of the device or source of the data, if \n available (such as the serial number). This is critical \n for system robustness since it allows recipients to \n recover from failure even after the serving app, device or \n computer crashes (just by finding a stream with the same \n source id on the network again). Therefore, it is highly \n recommended to always try to provide whatever information \n can uniquely identify the data source itself.\n (default '')\n\n \"\"\"\n if handle is not None:\n self.obj = c_void_p(handle)\n else:\n if isinstance(channel_format, str):\n channel_format = string2fmt[channel_format]\n self.obj = lib.lsl_create_streaminfo(c_char_p(str.encode(name)),\n c_char_p(str.encode(type)),\n channel_count,\n c_double(nominal_srate),\n channel_format,\n c_char_p(str.encode(source_id)))\n self.obj = c_void_p(self.obj)\n if not self.obj:\n raise RuntimeError(\"could not create stream description \"\n \"object.\")\n \n def __del__(self):\n \"\"\" Destroy a previously created StreamInfo object. \"\"\"\n # noinspection PyBroadException\n try:\n lib.lsl_destroy_streaminfo(self.obj)\n except:\n pass\n\n # === Core Information (assigned at construction) ===\n \n def name(self):\n \"\"\"Name of the stream.\n\n This is a human-readable name. For streams offered by device modules, \n it refers to the type of device or product series that is generating \n the data of the stream. If the source is an application, the name may \n be a more generic or specific identifier. Multiple streams with the \n same name can coexist, though potentially at the cost of ambiguity (for \n the recording app or experimenter).\n\n \"\"\"\n return lib.lsl_get_name(self.obj).decode('utf-8')\n\n def type(self):\n \"\"\"Content type of the stream.\n\n The content type is a short string such as \"EEG\", \"Gaze\" which \n describes the content carried by the channel (if known). If a stream \n contains mixed content this value need not be assigned but may instead \n be stored in the description of channel types. To be useful to \n applications and automated processing systems using the recommended \n content types is preferred.\n\n \"\"\"\n return lib.lsl_get_type(self.obj).decode('utf-8')\n \n def channel_count(self):\n \"\"\"Number of channels of the stream.\n\n A stream has at least one channel; the channel count stays constant for\n all samples.\n\n \"\"\"\n return lib.lsl_get_channel_count(self.obj)\n \n def nominal_srate(self):\n \"\"\"Sampling rate of the stream, according to the source (in Hz).\n\n If a stream is irregularly sampled, this should be set to\n IRREGULAR_RATE.\n\n Note that no data will be lost even if this sampling rate is incorrect \n or if a device has temporary hiccups, since all samples will be \n transmitted anyway (except for those dropped by the device itself). \n However, when the recording is imported into an application, a good \n data importer may correct such errors more accurately if the advertised \n sampling rate was close to the specs of the device.\n\n \"\"\"\n return lib.lsl_get_nominal_srate(self.obj)\n\n def channel_format(self):\n \"\"\"Channel format of the stream.\n\n All channels in a stream have the same format. However, a device might \n offer multiple time-synched streams each with its own format.\n\n \"\"\"\n return lib.lsl_get_channel_format(self.obj)\n\n def source_id(self):\n \"\"\"Unique identifier of the stream's source, if available.\n\n The unique source (or device) identifier is an optional piece of \n information that, if available, allows that endpoints (such as the \n recording program) can re-acquire a stream automatically once it is \n back online.\n\n \"\"\"\n return lib.lsl_get_source_id(self.obj).decode('utf-8')\n \n # === Hosting Information (assigned when bound to an outlet/inlet) ===\n \n def version(self):\n \"\"\"Protocol version used to deliver the stream.\"\"\"\n return lib.lsl_get_version(self.obj)\n \n def created_at(self):\n \"\"\"Creation time stamp of the stream.\n\n This is the time stamp when the stream was first created\n (as determined via local_clock() on the providing machine).\n\n \"\"\"\n return lib.lsl_get_created_at(self.obj)\n \n def uid(self):\n \"\"\"Unique ID of the stream outlet instance (once assigned).\n\n This is a unique identifier of the stream outlet, and is guaranteed to \n be different across multiple instantiations of the same outlet (e.g., \n after a re-start).\n\n \"\"\"\n return lib.lsl_get_uid(self.obj).decode('utf-8')\n\n def session_id(self):\n \"\"\"Session ID for the given stream.\n\n The session id is an optional human-assigned identifier of the \n recording session. While it is rarely used, it can be used to prevent \n concurrent recording activitites on the same sub-network (e.g., in \n multiple experiment areas) from seeing each other's streams \n (can be assigned in a configuration file read by liblsl, see also \n Network Connectivity in the LSL wiki).\n\n \"\"\"\n return lib.lsl_get_session_id(self.obj).decode('utf-8')\n \n def hostname(self):\n \"\"\"Hostname of the providing machine.\"\"\"\n return lib.lsl_get_hostname(self.obj).decode('utf-8')\n \n # === Data Description (can be modified) ===\n \n def desc(self):\n \"\"\"Extended description of the stream.\n\n It is highly recommended that at least the channel labels are described \n here. See code examples on the LSL wiki. Other information, such \n as amplifier settings, measurement units if deviating from defaults, \n setup information, subject information, etc., can be specified here, as \n well. Meta-data recommendations follow the XDF file format project\n (github.com/sccn/xdf/wiki/Meta-Data or web search for: XDF meta-data).\n \n Important: if you use a stream content type for which meta-data \n recommendations exist, please try to lay out your meta-data in \n agreement with these recommendations for compatibility with other \n applications.\n\n \"\"\"\n return XMLElement(lib.lsl_get_desc(self.obj))\n \n def as_xml(self):\n \"\"\"Retrieve the entire stream_info in XML format.\n\n This yields an XML document (in string form) whose top-level element is \n . The description element contains one element for each\n field of the stream_info class, including:\n a) the core elements , , , , \n , \n b) the misc elements , , , , \n , , , , \n , \n c) the extended description element with user-defined \n sub-elements.\n\n \"\"\"\n return lib.lsl_get_xml(self.obj).decode('utf-8')\n \n\n# ===================== \n# === Stream Outlet ===\n# =====================\n \nclass StreamOutlet:\n \"\"\"A stream outlet.\n\n Outlets are used to make streaming data (and the meta-data) available on \n the lab network.\n\n \"\"\" \n \n def __init__(self, info, chunk_size=0, max_buffered=360):\n \"\"\"Establish a new stream outlet. This makes the stream discoverable.\n \n Keyword arguments:\n description -- The StreamInfo object to describe this stream. Stays\n constant over the lifetime of the outlet.\n chunk_size --- Optionally the desired chunk granularity (in samples) \n for transmission. If unspecified, each push operation \n yields one chunk. Inlets can override this setting.\n (default 0)\n max_buffered -- Optionally the maximum amount of data to buffer (in \n seconds if there is a nominal sampling rate, otherwise \n x100 in samples). The default is 6 minutes of data. \n Note that, for high-bandwidth data, you will want to \n use a lower value here to avoid running out of RAM.\n (default 360)\n\n \"\"\"\n self.obj = lib.lsl_create_outlet(info.obj, chunk_size, max_buffered)\n self.obj = c_void_p(self.obj)\n if not self.obj:\n raise RuntimeError(\"could not create stream outlet.\")\n self.channel_format = info.channel_format()\n self.channel_count = info.channel_count()\n self.do_push_sample = fmt2push_sample[self.channel_format]\n self.do_push_chunk = fmt2push_chunk[self.channel_format]\n self.value_type = fmt2type[self.channel_format]\n self.sample_type = self.value_type*self.channel_count\n \n def __del__(self):\n \"\"\"Destroy an outlet.\n\n The outlet will no longer be discoverable after destruction and all \n connected inlets will stop delivering data.\n\n \"\"\"\n # noinspection PyBroadException\n try:\n lib.lsl_destroy_outlet(self.obj)\n except:\n pass\n \n def push_sample(self, x, timestamp=0.0, pushthrough=True):\n \"\"\"Push a sample into the outlet.\n\n Each entry in the list corresponds to one channel.\n\n Keyword arguments:\n x -- A list of values to push (one per channel).\n timestamp -- Optionally the capture time of the sample, in agreement \n with local_clock(); if omitted, the current \n time is used. (default 0.0)\n pushthrough -- Whether to push the sample through to the receivers \n instead of buffering it with subsequent samples. \n Note that the chunk_size, if specified at outlet \n construction, takes precedence over the pushthrough flag.\n (default True)\n\n \"\"\"\n if len(x) == self.channel_count:\n if self.channel_format == cf_string:\n x = [v.encode('utf-8') for v in x]\n handle_error(self.do_push_sample(self.obj, self.sample_type(*x),\n c_double(timestamp),\n c_int(pushthrough)))\n else:\n raise ValueError(\"length of the data must correspond to the \"\n \"stream's channel count.\")\n\n def push_chunk(self, x, timestamp=0.0, pushthrough=True):\n \"\"\"Push a list of samples into the outlet.\n\n samples -- A list of samples, either as a list of lists or a list of \n multiplexed values.\n timestamp -- Optionally the capture time of the most recent sample, in \n agreement with local_clock(); if omitted, the current \n time is used. The time stamps of other samples are \n automatically derived according to the sampling rate of \n the stream. (default 0.0)\n pushthrough Whether to push the chunk through to the receivers instead \n of buffering it with subsequent samples. Note that the \n chunk_size, if specified at outlet construction, takes \n precedence over the pushthrough flag. (default True)\n\n \"\"\"\n try:\n n_values = self.channel_count * len(x)\n data_buff = (self.value_type * n_values).from_buffer(x)\n handle_error(self.do_push_chunk(self.obj, data_buff,\n c_long(n_values),\n c_double(timestamp),\n c_int(pushthrough)))\n except TypeError:\n if len(x):\n if type(x[0]) is list:\n x = [v for sample in x for v in sample]\n if self.channel_format == cf_string:\n x = [v.encode('utf-8') for v in x]\n if len(x) % self.channel_count == 0:\n constructor = self.value_type*len(x)\n # noinspection PyCallingNonCallable\n handle_error(self.do_push_chunk(self.obj, constructor(*x),\n c_long(len(x)),\n c_double(timestamp),\n c_int(pushthrough)))\n else:\n raise ValueError(\"each sample must have the same number of \"\n \"channels.\")\n \n def have_consumers(self):\n \"\"\"Check whether consumers are currently registered.\n\n While it does not hurt, there is technically no reason to push samples \n if there is no consumer.\n\n \"\"\"\n return bool(lib.lsl_have_consumers(self.obj))\n \n def wait_for_consumers(self, timeout):\n \"\"\"Wait until some consumer shows up (without wasting resources).\n\n Returns True if the wait was successful, False if the timeout expired.\n\n \"\"\"\n return bool(lib.lsl_wait_for_consumers(self.obj, c_double(timeout)))\n\n \n# =========================\n# === Resolve Functions ===\n# =========================\n\ndef resolve_streams(wait_time=1.0):\n \"\"\"Resolve all streams on the network.\n\n This function returns all currently available streams from any outlet on \n the network. The network is usually the subnet specified at the local \n router, but may also include a group of machines visible to each other via \n multicast packets (given that the network supports it), or list of \n hostnames. These details may optionally be customized by the experimenter \n in a configuration file (see Network Connectivity in the LSL wiki). \n \n Keyword arguments:\n wait_time -- The waiting time for the operation, in seconds, to search for \n streams. Warning: If this is too short (<0.5s) only a subset \n (or none) of the outlets that are present on the network may \n be returned. (default 1.0)\n \n Returns a list of StreamInfo objects (with empty desc field), any of which \n can subsequently be used to open an inlet. The full description can be\n retrieved from the inlet.\n\n \"\"\"\n # noinspection PyCallingNonCallable\n buffer = (c_void_p*1024)()\n num_found = lib.lsl_resolve_all(byref(buffer), 1024, c_double(wait_time))\n return [StreamInfo(handle=buffer[k]) for k in range(num_found)]\n\n\ndef resolve_byprop(prop, value, minimum=1, timeout=FOREVER):\n \"\"\"Resolve all streams with a specific value for a given property.\n\n If the goal is to resolve a specific stream, this method is preferred over \n resolving all streams and then selecting the desired one.\n \n Keyword arguments:\n prop -- The StreamInfo property that should have a specific value (e.g., \n \"name\", \"type\", \"source_id\", or \"desc/manufaturer\").\n value -- The string value that the property should have (e.g., \"EEG\" as \n the type property).\n minimum -- Return at least this many streams. (default 1)\n timeout -- Optionally a timeout of the operation, in seconds. If the \n timeout expires, less than the desired number of streams \n (possibly none) will be returned. (default FOREVER)\n \n Returns a list of matching StreamInfo objects (with empty desc field), any \n of which can subsequently be used to open an inlet.\n \n Example: results = resolve_Stream_byprop(\"type\",\"EEG\")\n\n \"\"\"\n # noinspection PyCallingNonCallable\n buffer = (c_void_p*1024)()\n num_found = lib.lsl_resolve_byprop(byref(buffer), 1024,\n c_char_p(str.encode(prop)),\n c_char_p(str.encode(value)),\n minimum,\n c_double(timeout))\n return [StreamInfo(handle=buffer[k]) for k in range(num_found)]\n\n\ndef resolve_bypred(predicate, minimum=1, timeout=FOREVER):\n \"\"\"Resolve all streams that match a given predicate.\n\n Advanced query that allows to impose more conditions on the retrieved \n streams; the given string is an XPath 1.0 predicate for the \n node (omitting the surrounding []'s), see also\n http://en.wikipedia.org/w/index.php?title=XPath_1.0&oldid=474981951.\n \n Keyword arguments:\n predicate -- The predicate string, e.g. \"name='BioSemi'\" or \n \"type='EEG' and starts-with(name,'BioSemi') and \n count(description/desc/channels/channel)=32\"\n minimum -- Return at least this many streams. (default 1)\n timeout -- Optionally a timeout of the operation, in seconds. If the \n timeout expires, less than the desired number of streams \n (possibly none) will be returned. (default FOREVER)\n \n Returns a list of matching StreamInfo objects (with empty desc field), any \n of which can subsequently be used to open an inlet.\n\n \"\"\"\n # noinspection PyCallingNonCallable\n buffer = (c_void_p*1024)()\n num_found = lib.lsl_resolve_bypred(byref(buffer), 1024,\n c_char_p(str.encode(predicate)),\n minimum,\n c_double(timeout))\n return [StreamInfo(handle=buffer[k]) for k in range(num_found)]\n\n\n# ====================\n# === Memory functions\n# ====================\ndef free_char_p_array_memory(char_p_array,num_elements):\n pointers = cast(char_p_array, POINTER(c_void_p))\n for p in range(num_elements):\n if pointers[p] is not None: # only free initialized pointers\n lib.lsl_destroy_string(pointers[p])\n\n# ====================\n# === Stream Inlet ===\n# ====================\n \nclass StreamInlet:\n \"\"\"A stream inlet.\n\n Inlets are used to receive streaming data (and meta-data) from the lab \n network.\n\n \"\"\"\n \n def __init__(self, info, max_buflen=360, max_chunklen=0, recover=True, processing_flags=0):\n \"\"\"Construct a new stream inlet from a resolved stream description.\n \n Keyword arguments:\n description -- A resolved stream description object (as coming from one\n of the resolver functions). Note: the stream_inlet may also be\n constructed with a fully-specified stream_info, if the desired \n channel format and count is already known up-front, but this is \n strongly discouraged and should only ever be done if there is \n no time to resolve the stream up-front (e.g., due to \n limitations in the client program).\n max_buflen -- Optionally the maximum amount of data to buffer (in \n seconds if there is a nominal sampling rate, otherwise \n x100 in samples). Recording applications want to use a \n fairly large buffer size here, while real-time \n applications would only buffer as much as they need to \n perform their next calculation. (default 360)\n max_chunklen -- Optionally the maximum size, in samples, at which \n chunks are transmitted (the default corresponds to the \n chunk sizes used by the sender). Recording programs \n can use a generous size here (leaving it to the network \n how to pack things), while real-time applications may \n want a finer (perhaps 1-sample) granularity. If left \n unspecified (=0), the sender determines the chunk \n granularity. (default 0)\n recover -- Try to silently recover lost streams that are recoverable \n (=those that that have a source_id set). In all other cases \n (recover is False or the stream is not recoverable) \n functions may throw a lost_error if the stream's source is \n lost (e.g., due to an app or computer crash). (default True)\n\n \"\"\"\n if type(info) is list:\n raise TypeError(\"description needs to be of type StreamInfo, \"\n \"got a list.\")\n self.obj = lib.lsl_create_inlet(info.obj, max_buflen, max_chunklen,\n recover)\n self.obj = c_void_p(self.obj)\n if not self.obj: \n raise RuntimeError(\"could not create stream inlet.\")\n if processing_flags > 0:\n handle_error(lib.lsl_set_postprocessing(self.obj, processing_flags))\n self.channel_format = info.channel_format()\n self.channel_count = info.channel_count()\n self.do_pull_sample = fmt2pull_sample[self.channel_format]\n self.do_pull_chunk = fmt2pull_chunk[self.channel_format]\n self.value_type = fmt2type[self.channel_format]\n self.sample_type = self.value_type*self.channel_count\n self.sample = self.sample_type()\n self.buffers = {}\n\n def __del__(self):\n \"\"\"Destructor. The inlet will automatically disconnect if destroyed.\"\"\"\n # noinspection PyBroadException\n try:\n lib.lsl_destroy_inlet(self.obj)\n except:\n pass\n \n def info(self, timeout=FOREVER):\n \"\"\"Retrieve the complete information of the given stream.\n\n This includes the extended description. Can be invoked at any time of\n the stream's lifetime.\n \n Keyword arguments:\n timeout -- Timeout of the operation. (default FOREVER)\n \n Throws a TimeoutError (if the timeout expires), or LostError (if the \n stream source has been lost).\n\n \"\"\"\n errcode = c_int()\n result = lib.lsl_get_fullinfo(self.obj, c_double(timeout),\n byref(errcode))\n handle_error(errcode)\n return StreamInfo(handle=result)\n\n def open_stream(self, timeout=FOREVER):\n \"\"\"Subscribe to the data stream.\n\n All samples pushed in at the other end from this moment onwards will be \n queued and eventually be delivered in response to pull_sample() or \n pull_chunk() calls. Pulling a sample without some preceding open_stream \n is permitted (the stream will then be opened implicitly).\n \n Keyword arguments:\n timeout -- Optional timeout of the operation (default FOREVER).\n \n Throws a TimeoutError (if the timeout expires), or LostError (if the \n stream source has been lost).\n\n \"\"\"\n errcode = c_int()\n lib.lsl_open_stream(self.obj, c_double(timeout), byref(errcode))\n handle_error(errcode)\n \n def close_stream(self):\n \"\"\"Drop the current data stream.\n\n All samples that are still buffered or in flight will be dropped and \n transmission and buffering of data for this inlet will be stopped. If \n an application stops being interested in data from a source \n (temporarily or not) but keeps the outlet alive, it should call \n lsl_close_stream() to not waste unnecessary system and network \n resources.\n\n \"\"\"\n lib.lsl_close_stream(self.obj)\n\n def time_correction(self, timeout=FOREVER):\n \"\"\"Retrieve an estimated time correction offset for the given stream.\n\n The first call to this function takes several miliseconds until a \n reliable first estimate is obtained. Subsequent calls are instantaneous \n (and rely on periodic background updates). The precision of these \n estimates should be below 1 ms (empirically within +/-0.2 ms).\n \n Keyword arguments: \n timeout -- Timeout to acquire the first time-correction estimate \n (default FOREVER).\n \n Returns the current time correction estimate. This is the number that \n needs to be added to a time stamp that was remotely generated via \n local_clock() to map it into the local clock domain of this \n machine.\n\n Throws a TimeoutError (if the timeout expires), or LostError (if the \n stream source has been lost).\n\n \"\"\"\n errcode = c_int()\n result = lib.lsl_time_correction(self.obj, c_double(timeout),\n byref(errcode))\n handle_error(errcode)\n return result\n \n def pull_sample(self, timeout=FOREVER, sample=None):\n \"\"\"Pull a sample from the inlet and return it.\n \n Keyword arguments:\n timeout -- The timeout for this operation, if any. (default FOREVER)\n If this is passed as 0.0, then the function returns only a \n sample if one is buffered for immediate pickup.\n \n Returns a tuple (sample,timestamp) where sample is a list of channel \n values and timestamp is the capture time of the sample on the remote \n machine, or (None,None) if no new sample was available. To remap this \n time stamp to the local clock, add the value returned by \n .time_correction() to it. \n \n Throws a LostError if the stream source has been lost. Note that, if \n the timeout expires, no TimeoutError is thrown (because this case is \n not considered an error).\n\n \"\"\"\n \n # support for the legacy API\n if type(timeout) is list:\n assign_to = timeout\n timeout = sample if type(sample) is float else 0.0\n else:\n assign_to = None\n \n errcode = c_int()\n timestamp = self.do_pull_sample(self.obj, byref(self.sample),\n self.channel_count, c_double(timeout),\n byref(errcode))\n handle_error(errcode)\n if timestamp:\n sample = [v for v in self.sample]\n if self.channel_format == cf_string:\n sample = [v.decode('utf-8') for v in sample]\n if assign_to is not None:\n assign_to[:] = sample\n return sample, timestamp\n else:\n return None, None\n \n def pull_chunk(self, timeout=0.0, max_samples=1024, dest_obj=None):\n \"\"\"Pull a chunk of samples from the inlet.\n \n Keyword arguments:\n timeout -- The timeout of the operation; if passed as 0.0, then only \n samples available for immediate pickup will be returned. \n (default 0.0)\n max_samples -- Maximum number of samples to return. (default \n 1024)\n dest_obj -- A Python object that supports the buffer interface.\n If this is provided then the dest_obj will be updated in place\n and the samples list returned by this method will be empty.\n It is up to the caller to trim the buffer to the appropriate\n number of samples.\n A numpy buffer must be order='C'\n (default None)\n \n Returns a tuple (samples,timestamps) where samples is a list of samples \n (each itself a list of values), and timestamps is a list of time-stamps.\n\n Throws a LostError if the stream source has been lost.\n\n \"\"\"\n # look up a pre-allocated buffer of appropriate length \n num_channels = self.channel_count\n max_values = max_samples*num_channels\n\n if max_samples not in self.buffers:\n # noinspection PyCallingNonCallable\n self.buffers[max_samples] = ((self.value_type*max_values)(),\n (c_double*max_samples)())\n if dest_obj is not None:\n data_buff = (self.value_type * max_values).from_buffer(dest_obj)\n else:\n data_buff = self.buffers[max_samples][0]\n ts_buff = self.buffers[max_samples][1]\n\n # read data into it\n errcode = c_int()\n # noinspection PyCallingNonCallable\n num_elements = self.do_pull_chunk(self.obj, byref(data_buff),\n byref(ts_buff), max_values,\n max_samples, c_double(timeout),\n byref(errcode))\n handle_error(errcode)\n # return results (note: could offer a more efficient format in the \n # future, e.g., a numpy array)\n num_samples = num_elements/num_channels\n if dest_obj is None:\n samples = [[data_buff[s*num_channels+c] for c in range(num_channels)]\n for s in range(int(num_samples))]\n if self.channel_format == cf_string:\n samples = [[v.decode('utf-8') for v in s] for s in samples]\n free_char_p_array_memory(data_buff, max_values)\n else:\n samples = None\n timestamps = [ts_buff[s] for s in range(int(num_samples))]\n return samples, timestamps\n \n def samples_available(self):\n \"\"\"Query whether samples are currently available for immediate pickup.\n\n Note that it is not a good idea to use samples_available() to determine \n whether a pull_*() call would block: to be sure, set the pull timeout \n to 0.0 or an acceptably low value. If the underlying implementation \n supports it, the value will be the number of samples available \n (otherwise it will be 1 or 0).\n\n \"\"\"\n return lib.lsl_samples_available(self.obj)\n \n def was_clock_reset(self):\n \"\"\"Query whether the clock was potentially reset since the last call.\n\n This is rarely-used function is only needed for applications that\n combine multiple time_correction values to estimate precise clock\n drift if they should tolerate cases where the source machine was\n hot-swapped or restarted.\n\n \"\"\"\n return bool(lib.lsl_was_clock_reset(self.obj))\n\n\n# ===================\n# === XML Element ===\n# ===================\n \nclass XMLElement:\n \"\"\"A lightweight XML element tree modeling the .desc() field of StreamInfo.\n\n Has a name and can have multiple named children or have text content as \n value; attributes are omitted. Insider note: The interface is modeled after \n a subset of pugixml's node type and is compatible with it. See also \n http://pugixml.googlecode.com/svn/tags/latest/docs/manual/access.html for \n additional documentation.\n\n \"\"\"\n \n def __init__(self, handle):\n \"\"\"Construct new XML element from existing handle.\"\"\"\n self.e = c_void_p(handle)\n \n # === Tree Navigation ===\n \n def first_child(self):\n \"\"\"Get the first child of the element.\"\"\"\n return XMLElement(lib.lsl_first_child(self.e))\n \n def last_child(self):\n \"\"\"Get the last child of the element.\"\"\"\n return XMLElement(lib.lsl_last_child(self.e))\n\n def child(self, name):\n \"\"\"Get a child with a specified name.\"\"\"\n return XMLElement(lib.lsl_child(self.e, str.encode(name)))\n \n def next_sibling(self, name=None):\n \"\"\"Get the next sibling in the children list of the parent node.\n\n If a name is provided, the next sibling with the given name is returned.\n\n \"\"\"\n if name is None:\n return XMLElement(lib.lsl_next_sibling(self.e))\n else:\n return XMLElement(lib.lsl_next_sibling_n(self.e, str.encode(name)))\n \n def previous_sibling(self, name=None):\n \"\"\"Get the previous sibling in the children list of the parent node.\n\n If a name is provided, the previous sibling with the given name is\n returned.\n\n \"\"\"\n if name is None:\n return XMLElement(lib.lsl_previous_sibling(self.e))\n else:\n return XMLElement(lib.lsl_previous_sibling_n(self.e,\n str.encode(name)))\n \n def parent(self):\n \"\"\"Get the parent node.\"\"\"\n return XMLElement(lib.lsl_parent(self.e))\n \n # === Content Queries ===\n \n def empty(self):\n \"\"\"Whether this node is empty.\"\"\"\n return bool(lib.lsl_empty(self.e))\n \n def is_text(self):\n \"\"\"Whether this is a text body (instead of an XML element).\n\n True both for plain char data and CData.\n\n \"\"\"\n return bool(lib.lsl_is_text(self.e))\n \n def name(self):\n \"\"\"Name of the element.\"\"\"\n return lib.lsl_name(self.e).decode('utf-8')\n \n def value(self):\n \"\"\"Value of the element.\"\"\"\n return lib.lsl_value(self.e).decode('utf-8')\n \n def child_value(self, name=None):\n \"\"\"Get child value (value of the first child that is text).\n\n If a name is provided, then the value of the first child with the\n given name is returned.\n\n \"\"\"\n if name is None:\n res = lib.lsl_child_value(self.e)\n else:\n res = lib.lsl_child_value_n(self.e, str.encode(name))\n return res.decode('utf-8')\n\n # === Modification ===\n \n def append_child_value(self, name, value):\n \"\"\"Append a child node with a given name, which has a (nameless) \n plain-text child with the given text value.\"\"\"\n return XMLElement(lib.lsl_append_child_value(self.e,\n str.encode(name),\n str.encode(value)))\n \n def prepend_child_value(self, name, value):\n \"\"\"Prepend a child node with a given name, which has a (nameless) \n plain-text child with the given text value.\"\"\"\n return XMLElement(lib.lsl_prepend_child_value(self.e,\n str.encode(name),\n str.encode(value)))\n\n def set_child_value(self, name, value):\n \"\"\"Set the text value of the (nameless) plain-text child of a named \n child node.\"\"\"\n return XMLElement(lib.lsl_set_child_value(self.e,\n str.encode(name),\n str.encode(value)))\n \n def set_name(self, name):\n \"\"\"Set the element's name. Returns False if the node is empty.\"\"\"\n return bool(lib.lsl_set_name(self.e, str.encode(name)))\n \n def set_value(self, value):\n \"\"\"Set the element's value. Returns False if the node is empty.\"\"\"\n return bool(lib.lsl_set_value(self.e, str.encode(value)))\n \n def append_child(self, name):\n \"\"\"Append a child element with the specified name.\"\"\"\n return XMLElement(lib.lsl_append_child(self.e, str.encode(name)))\n \n def prepend_child(self, name):\n \"\"\"Prepend a child element with the specified name.\"\"\"\n return XMLElement(lib.lsl_prepend_child(self.e, str.encode(name)))\n \n def append_copy(self, elem):\n \"\"\"Append a copy of the specified element as a child.\"\"\"\n return XMLElement(lib.lsl_append_copy(self.e, elem.e))\n \n def prepend_copy(self, elem):\n \"\"\"Prepend a copy of the specified element as a child.\"\"\"\n return XMLElement(lib.lsl_prepend_copy(self.e, elem.e))\n \n def remove_child(self, rhs):\n \"\"\"Remove a given child element, specified by name or as element.\"\"\"\n if type(rhs) is XMLElement:\n lib.lsl_remove_child(self.e, rhs.e)\n else:\n lib.lsl_remove_child_n(self.e, rhs)\n\n \n# ==========================\n# === ContinuousResolver ===\n# ==========================\n\nclass ContinuousResolver:\n \"\"\"A convenience class resolving streams continuously in the background.\n\n This object can be queried at any time for the set of streams that are\n currently visible on the network.\n\n \"\"\"\n \n def __init__(self, prop=None, value=None, pred=None, forget_after=5.0):\n \"\"\"Construct a new continuous_resolver.\n\n Keyword arguments:\n forget_after -- When a stream is no longer visible on the network \n (e.g., because it was shut down), this is the time in \n seconds after which it is no longer reported by the \n resolver.\n\n \"\"\"\n if pred is not None:\n if prop is not None or value is not None:\n raise ValueError(\"you can only either pass the prop/value \"\n \"argument or the pred argument, but not \"\n \"both.\")\n self.obj = lib.lsl_create_continuous_resolver_bypred(str.encode(pred),\n c_double(forget_after))\n elif prop is not None and value is not None:\n self.obj = lib.lsl_create_continuous_resolver_byprop(str.encode(prop),\n str.encode(value),\n c_double(forget_after))\n elif prop is not None or value is not None:\n raise ValueError(\"if prop is specified, then value must be \"\n \"specified, too, and vice versa.\")\n else:\n self.obj = lib.lsl_create_continuous_resolver(c_double(forget_after))\n self.obj = c_void_p(self.obj)\n if not self.obj:\n raise RuntimeError(\"could not create continuous resolver.\")\n \n def __del__(self):\n \"\"\"Destructor for the continuous resolver.\"\"\"\n # noinspection PyBroadException\n try:\n lib.lsl_destroy_continuous_resolver(self.obj)\n except:\n pass\n \n def results(self):\n \"\"\"Obtain the set of currently present streams on the network.\n\n Returns a list of matching StreamInfo objects (with empty desc\n field), any of which can subsequently be used to open an inlet.\n\n \"\"\"\n # noinspection PyCallingNonCallable\n buffer = (c_void_p*1024)()\n num_found = lib.lsl_resolver_results(self.obj, byref(buffer), 1024)\n return [StreamInfo(handle=buffer[k]) for k in range(num_found)]\n\n\n# =========================\n# === Error Definitions === \n# =========================\n\n# noinspection PyShadowingBuiltins\nclass TimeoutError(RuntimeError):\n # note: although this overrides the name of a built-in exception,\n # this API is retained here for compatiblity with the Python 2.x\n # version of pylsl\n pass\n\n\nclass LostError(RuntimeError):\n pass\n\n\nclass InvalidArgumentError(RuntimeError):\n pass\n\n\nclass InternalError(RuntimeError):\n pass\n\n\ndef handle_error(errcode):\n \"\"\"Error handler function. Translates an error code into an exception.\"\"\"\n if type(errcode) is c_int:\n errcode = errcode.value\n if errcode == 0:\n pass # no error\n elif errcode == -1:\n raise TimeoutError(\"the operation failed due to a timeout.\")\n elif errcode == -2:\n raise LostError(\"the stream has been lost.\")\n elif errcode == -3:\n raise InvalidArgumentError(\"an argument was incorrectly specified.\")\n elif errcode == -4:\n raise InternalError(\"an internal error has occurred.\")\n elif errcode < 0: \n raise RuntimeError(\"an unknown error has occurred.\")\n\n\n# ================================================= \n# === Compatibility Interface for old pylsl API === \n# ================================================= \n\n# set class aliases\nstream_info = StreamInfo\nstream_outlet = StreamOutlet\nstream_inlet = StreamInlet\nxml_element = XMLElement\ntimeout_error = TimeoutError\nlost_error = LostError\nvectorf = vectord = vectorl = vectori = vectors = vectorc = vectorstr = list\n\n\ndef resolve_stream(*args):\n if len(args) == 0:\n return resolve_streams()\n elif type(args[0]) in [int, float]:\n return resolve_streams(args[0])\n elif type(args[0]) is str:\n if len(args) == 1:\n return resolve_bypred(args[0])\n elif type(args[1]) in [int, float]:\n return resolve_bypred(args[0], args[1])\n else:\n if len(args) == 2:\n return resolve_byprop(args[0], args[1])\n else:\n return resolve_byprop(args[0], args[1], args[2])\n \n\n# ==================================\n# === Module Initialization Code ===\n# ==================================\n\n# find and load library\nos_name = platform.system()\nbitness = 8 * struct.calcsize(\"P\")\nif os_name in ['Windows', 'Microsoft']:\n libname = 'liblsl32.dll' if bitness == 32 else 'liblsl64.dll'\nelif os_name == 'Darwin':\n libname = 'liblsl32.dylib' if bitness == 32 else 'liblsl64.dylib'\nelif os_name == 'Linux':\n libname = 'liblsl32.so' if bitness == 32 else 'liblsl64.so'\nelse:\n raise RuntimeError(\"unrecognized operating system:\", os_name)\nlibpath = os.path.join(os.path.dirname(__file__), libname)\nif not os.path.isfile(libpath):\n libpath = util.find_library('lsl' + str(bitness))\nif not libpath:\n raise RuntimeError(\"library \" + libname + \" was not found - make sure \"\n \"that it is on the search path (e.g., in the same \"\n \"folder as pylsl.py).\")\nlib = CDLL(libpath)\n\n\n# set function return types where necessary\nlib.lsl_local_clock.restype = c_double\nlib.lsl_create_streaminfo.restype = c_void_p\nlib.lsl_get_name.restype = c_char_p\nlib.lsl_get_type.restype = c_char_p\nlib.lsl_get_nominal_srate.restype = c_double\nlib.lsl_get_source_id.restype = c_char_p\nlib.lsl_get_created_at.restype = c_double\nlib.lsl_get_uid.restype = c_char_p\nlib.lsl_get_session_id.restype = c_char_p\nlib.lsl_get_hostname.restype = c_char_p\nlib.lsl_get_desc.restype = c_void_p\nlib.lsl_get_xml.restype = c_char_p\nlib.lsl_create_outlet.restype = c_void_p\nlib.lsl_create_inlet.restype = c_void_p \nlib.lsl_get_fullinfo.restype = c_void_p\nlib.lsl_open_stream.restype = c_void_p\nlib.lsl_time_correction.restype = c_double\nlib.lsl_pull_sample_f.restype = c_double\nlib.lsl_pull_sample_d.restype = c_double\nlib.lsl_pull_sample_l.restype = c_double\nlib.lsl_pull_sample_i.restype = c_double\nlib.lsl_pull_sample_s.restype = c_double\nlib.lsl_pull_sample_c.restype = c_double\nlib.lsl_pull_sample_str.restype = c_double\nlib.lsl_pull_sample_buf.restype = c_double\nlib.lsl_first_child.restype = c_void_p\nlib.lsl_first_child.argtypes = [c_void_p, ]\nlib.lsl_last_child.restype = c_void_p\nlib.lsl_last_child.argtypes = [c_void_p, ]\nlib.lsl_next_sibling.restype = c_void_p\nlib.lsl_next_sibling.argtypes = [c_void_p, ]\nlib.lsl_previous_sibling.restype = c_void_p\nlib.lsl_previous_sibling.argtypes = [c_void_p, ]\nlib.lsl_parent.restype = c_void_p\nlib.lsl_parent.argtypes = [c_void_p, ]\nlib.lsl_child.restype = c_void_p\nlib.lsl_child.argtypes = [c_void_p, c_char_p]\nlib.lsl_next_sibling_n.restype = c_void_p\nlib.lsl_next_sibling_n.argtypes = [c_void_p, c_char_p]\nlib.lsl_previous_sibling_n.restype = c_void_p\nlib.lsl_previous_sibling_n.argtypes = [c_void_p, c_char_p]\nlib.lsl_name.restype = c_char_p\nlib.lsl_name.argtypes = [c_void_p, ]\nlib.lsl_value.restype = c_char_p\nlib.lsl_value.argtypes = [c_void_p, ]\nlib.lsl_child_value.restype = c_char_p\nlib.lsl_child_value.argtypes = [c_void_p, ]\nlib.lsl_child_value_n.restype = c_char_p\nlib.lsl_child_value_n.argtypes = [c_void_p, c_char_p]\nlib.lsl_append_child_value.restype = c_void_p\nlib.lsl_append_child_value.argtypes = [c_void_p, c_char_p, c_char_p]\nlib.lsl_prepend_child_value.restype = c_void_p\nlib.lsl_prepend_child_value.argtypes = [c_void_p, c_char_p, c_char_p]\n# Return type for lsl_set_child_value, lsl_set_name, lsl_set_value is int\nlib.lsl_set_child_value.argtypes = [c_void_p, c_char_p, c_char_p]\nlib.lsl_set_name.argtypes = [c_void_p, c_char_p]\nlib.lsl_set_value.argtypes = [c_void_p, c_char_p]\nlib.lsl_append_child.restype = c_void_p\nlib.lsl_append_child.argtypes = [c_void_p, c_char_p]\nlib.lsl_prepend_child.restype = c_void_p\nlib.lsl_prepend_child.argtypes = [c_void_p, c_char_p]\nlib.lsl_append_copy.restype = c_void_p\nlib.lsl_append_copy.argtypes = [c_void_p, c_void_p]\nlib.lsl_prepend_copy.restype = c_void_p\nlib.lsl_prepend_copy.argtypes = [c_void_p, c_void_p]\nlib.lsl_remove_child_n.argtypes = [c_void_p, c_char_p]\nlib.lsl_remove_child.argtypes = [c_void_p, c_void_p]\nlib.lsl_destroy_string.argtypes = [c_void_p]\n# noinspection PyBroadException\ntry:\n lib.lsl_pull_chunk_f.restype = c_long\n lib.lsl_pull_chunk_d.restype = c_long\n lib.lsl_pull_chunk_l.restype = c_long\n lib.lsl_pull_chunk_i.restype = c_long\n lib.lsl_pull_chunk_s.restype = c_long\n lib.lsl_pull_chunk_c.restype = c_long\n lib.lsl_pull_chunk_str.restype = c_long\n lib.lsl_pull_chunk_buf.restype = c_long\nexcept:\n print(\"pylsl: chunk transfer functions not available in your liblsl \"\n \"version.\")\n# noinspection PyBroadException\ntry:\n lib.lsl_create_continuous_resolver.restype = c_void_p\n lib.lsl_create_continuous_resolver_bypred.restype = c_void_p\n lib.lsl_create_continuous_resolver_byprop.restype = c_void_p\nexcept:\n print(\"pylsl: ContinuousResolver not (fully) available in your liblsl \"\n \"version.\")\n \n# set up some type maps\nstring2fmt = {'float32': cf_float32, 'double64': cf_double64,\n 'string': cf_string, 'int32': cf_int32, 'int16': cf_int16,\n 'int8': cf_int8, 'int64': cf_int64}\nfmt2string = ['undefined', 'float32', 'double64', 'string', 'int32', 'int16',\n 'int8', 'int64']\nfmt2type = [[], c_float, c_double, c_char_p, c_int, c_short, c_byte, c_longlong]\nfmt2push_sample = [[], lib.lsl_push_sample_ftp, lib.lsl_push_sample_dtp,\n lib.lsl_push_sample_strtp, lib.lsl_push_sample_itp,\n lib.lsl_push_sample_stp, lib.lsl_push_sample_ctp, []]\nfmt2pull_sample = [[], lib.lsl_pull_sample_f, lib.lsl_pull_sample_d,\n lib.lsl_pull_sample_str, lib.lsl_pull_sample_i,\n lib.lsl_pull_sample_s, lib.lsl_pull_sample_c, []]\n# noinspection PyBroadException\ntry:\n fmt2push_chunk = [[], lib.lsl_push_chunk_ftp, lib.lsl_push_chunk_dtp,\n lib.lsl_push_chunk_strtp, lib.lsl_push_chunk_itp,\n lib.lsl_push_chunk_stp, lib.lsl_push_chunk_ctp, []]\n fmt2pull_chunk = [[], lib.lsl_pull_chunk_f, lib.lsl_pull_chunk_d,\n lib.lsl_pull_chunk_str, lib.lsl_pull_chunk_i,\n lib.lsl_pull_chunk_s, lib.lsl_pull_chunk_c, []]\nexcept:\n # if not available\n fmt2push_chunk = [None, None, None, None, None, None, None, None]\n fmt2pull_chunk = [None, None, None, None, None, None, None, None]\n","repo_name":"sccn/lsl_archived","sub_path":"LSL/liblsl-Python/pylsl/pylsl.py","file_name":"pylsl.py","file_ext":"py","file_size_in_byte":54895,"program_lang":"python","lang":"en","doc_type":"code","stars":243,"dataset":"github-code","pt":"31"}
+{"seq_id":"13676958666","text":"import sys\n\n'''\n 답 리턴 변수 answer\n 입력 받을 변수 str\n 알파벳들이 들어갈 딕셔너리 alphaDic\n'''\nanswer = \"\"\nstr = sys.stdin.readline().rstrip()\nalphaDic = {}\n\n'''\n 문자의 길이만큼 반복하여\n 스펠링을 대문자화 시킨다.\n \n 스펠링이 알파벳 딕셔녀리에 키값으로 존재하지 않으면 해당 키의 1 값을 추가한다.\n 존재하면 값을 1추가한다.\n'''\nfor c in str:\n C = c.upper()\n\n if C not in alphaDic.keys():\n alphaDic[C] = 1\n else:\n alphaDic[C]+=1\n\n'''\n 알파벳 딕셔너리의 값들중 최대값을 찾는다.\n 딕셔너리의 키의 값을 탐색하며 해당 최대값을 가지고 있는 키 값을 리턴 문자열에 추가한다.\n'''\nmaxVal = max(alphaDic.values())\n\nfor key in alphaDic.keys():\n if alphaDic[key] == maxVal:\n answer+=key\n\n'''\n 문자열의 길이가 1보다 크면 ? 를 출력하고 1이면 해당 스펠링만 출력한다.\n'''\nif len(answer) > 1:\n print(\"?\")\nelse:\n print(answer)\n\n'''\n다른 사람의 풀이\n모두 대문자화 하여 입력받는다.\nword = input().upper()\n\nli = [0] * (ord('Z') + 1)\nfor ab in range(ord('A'), ord('Z')+1):\n li[ab] = word.count(chr(ab))\n\nmax_ = max(li[ord('A'):])\nif li[ord('A'):].count(max_) >= 2:\n print('?')\nelse:\n print(chr(li.index(max_)))\n \nord 함수 : 문자의 아스키코드 값을 돌려주는 함수\n'''","repo_name":"junseokseo-KR/pythonAlgorithm","sub_path":"venv/src/codeAlgorithm/baekjoon/문자열/1157_단어공부.py","file_name":"1157_단어공부.py","file_ext":"py","file_size_in_byte":1434,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"}
+{"seq_id":"9125691261","text":"from Bio import SeqIO\nimport os.path\nimport sys\n\ndef get_seq_from_fasta(file, include_reverse = True):\n if os.path.isfile(file):\n try:\n rec_dict = SeqIO.to_dict(SeqIO.parse(file, 'fasta'))\n if len(rec_dict) == 0:\n raise RuntimeError('¿y los reads?')\n return rec_dict\n except IOError as err:\n raise err\n\n else:\n raise RuntimeError('error 404 file not found')\n\ndef include_reverse(rec_dict):\n rev_rec_dict = {}\n for seq_id, seq in rec_dict.items():\n rev_rec_dict[seq_id + '_rev'] = seq.reverse_complement()\n\n rec_dict.update(reversed_record_dict)\n return rec_dict\n\ndef output_assembly(sequences, output_file_name=\"./output.txt\",\n longest_assembly_only=False):\n with open(output_file_name, 'w') as output_handle:\n if longest_assembly_only:\n sequence = max(sequences, key=len)\n output_handle.write(str(sequence) + '\\n')\n else:\n for sequence in sorted(sequences,key=len,reverse=True):\n output_handle.write(str(sequence) + '\\n')\n","repo_name":"biocomp-eafit/simple-assembly","sub_path":"src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"40878792887","text":"# Created by viv at 15.12.18\n\"\"\"\n\n\"\"\"\nimport math\nimport time\nimport sys\nimport numpy as np\n\n# -----------------------------------------------\nfrom lib import pwm\nimport constants as const\nfrom lib.servo_calibration import servo_calib_data as servo_calib\nfrom lib import miscellaneous as misc\nfrom lib.kinematics import ikine as ik\n\n\n# ------------------------------------------------------------------------------\n# \"\"\" FUNCTION: To control Servos with IK algorithm \"\"\"\n# ------------------------------------------------------------------------------\ndef robo_main():\n \"\"\"\n 906\n :return:\n \"\"\"\n pwm_jf1 = pwm.PWM(gpio_path=const.JF1_MIO13_919, servo_cal_info=servo_calib.servo_1)\n pwm_jf4 = pwm.PWM(gpio_path=const.JF4_MIO12_918, servo_cal_info=servo_calib.servo_2)\n pwm_jf7 = pwm.PWM(gpio_path=const.JF7_MIO0_906, servo_cal_info=servo_calib.servo_3)\n pwm_jf8 = pwm.PWM(gpio_path=const.JF8_MIO09_915, servo_cal_info=servo_calib.servo_4)\n pwm_jf9 = pwm.PWM(gpio_path=const.JF9_MIO14_920, servo_cal_info=servo_calib.servo_5)\n\n while True:\n theta1 = float(input(\"theta1: \"))\n theta2 = float(input(\"theta2: \"))\n theta3 = float(input(\"theta3: \"))\n theta4 = float(input(\"theta4: \"))\n theta5 = float(input(\"theta5: \"))\n\n pwm_jf1.pwm_generate(theta1)\n time.sleep(0.5)\n\n pwm_jf4.pwm_generate(theta2)\n time.sleep(0.5)\n\n pwm_jf7.pwm_generate(theta3)\n time.sleep(0.5)\n\n pwm_jf8.pwm_generate(theta4)\n time.sleep(0.5)\n\n pwm_jf9.pwm_generate(theta5)\n time.sleep(0.5)\n\n\n# ------------------------------------------------------------------------------\n# \"\"\" FUNCTION: MAIN \"\"\"\n# ------------------------------------------------------------------------------\ndef main():\n \"\"\"\n\n \"\"\"\n pwm_jf1 = pwm.PWM(gpio_path=const.JF1_MIO13_919, servo_cal_info=servo_calib.servo_1)\n pwm_jf4 = pwm.PWM(gpio_path=const.JF4_MIO12_918, servo_cal_info=servo_calib.servo_2)\n pwm_jf7 = pwm.PWM(gpio_path=const.JF7_MIO0_906, servo_cal_info=servo_calib.servo_3)\n pwm_jf8 = pwm.PWM(gpio_path=const.JF8_MIO09_915, servo_cal_info=servo_calib.servo_4)\n pwm_jf9 = pwm.PWM(gpio_path=const.JF9_MIO14_920, servo_cal_info=servo_calib.servo_5)\n\n end_eff_direction_mat = np.matrix([\n [-1., 0., 0.],\n [0., -1., 0.],\n [0., 0., 1.]\n ])\n\n while True:\n x = float(input(\"x: \"))\n y = float(input(\"y: \"))\n z = float(input(\"z: \"))\n\n thetas = ik.ik_5dof(end_eff_direction_mat, x, y, z)\n\n print(\"theta_1 {}\".format(math.degrees(thetas.theta_1)))\n print(\"theta_2 {}\".format(math.degrees(thetas.theta_2)))\n print(\"theta_3 {}\".format(math.degrees(thetas.theta_3)))\n print(\"theta_4 {}\".format(math.degrees(thetas.theta_4)))\n print(\"theta_5 {}\".format(math.degrees(thetas.theta_5)))\n\n pwm_jf1.pwm_generate(thetas.theta_1)\n time.sleep(0.5)\n\n pwm_jf4.pwm_generate(thetas.theta_2)\n time.sleep(0.5)\n\n pwm_jf7.pwm_generate(thetas.theta_3)\n time.sleep(0.5)\n\n pwm_jf8.pwm_generate(thetas.theta_4)\n time.sleep(0.5)\n\n pwm_jf9.pwm_generate(thetas.theta_5)\n time.sleep(0.5)\n\n\nif __name__ == '__main__':\n tstart = time.time()\n\n # robo_main()\n main()\n\n print(\"Total time {}\".format(time.time() - tstart))\n","repo_name":"vivekpatel99/Kinematics","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"20143968750","text":"import unittest\n\nfrom project.aquarium.freshwater_aquarium import FreshwaterAquarium\nfrom project.decoration.ornament import Ornament\nfrom project.decoration.plant import Plant\nfrom project.fish.freshwater_fish import FreshwaterFish\n\n\nclass TestAquarium(unittest.TestCase):\n def setUp(self) -> None:\n self.test = FreshwaterAquarium('fresh')\n\n def test_add_decoration(self):\n for _ in range(3):\n self.test.add_decoration(Ornament())\n self.assertEqual(3, len(self.test.decorations))\n\n def test_calculate_comfort(self):\n for _ in range(3):\n self.test.add_decoration(Ornament())\n self.assertEqual(3, self.test.calculate_comfort())\n\n def test_add_fish_valid_fish_enough_capacity(self):\n self.test.capacity = 1\n self.assertEqual([], self.test.fish)\n fish = FreshwaterFish('fish', 'freshwater', 10)\n expected = \"Successfully added FreshwaterFish to fresh.\"\n actual = self.test.add_fish(fish)\n self.assertEqual(fish, self.test.fish[0])\n self.assertEqual(expected, actual)\n\n def test_valid_fish_not_enough_capacity(self):\n self.test.capacity = 1\n self.assertEqual([], self.test.fish)\n fish = FreshwaterFish('fish', 'freshwater', 10)\n fish2 = FreshwaterFish('fish', 'freshwater', 10)\n self.test.add_fish(fish)\n expected = \"Not enough capacity.\"\n actual = self.test.add_fish(fish2)\n self.assertEqual(expected, actual)\n\n def test_str_method_with_fish(self):\n fish = FreshwaterFish('fish', 'freshwater', 10)\n fish2 = FreshwaterFish('fish2', 'freshwater', 10)\n self.test.add_decoration(Ornament())\n self.test.add_decoration(Plant())\n self.test.add_decoration(Plant())\n self.test.add_fish(fish)\n self.test.add_fish(fish2)\n expected = \"fresh:\\nFish: fish fish2\\nDecorations: 3\\nComfort: 11\"\n actual = self.test.__str__()\n self.assertEqual(expected, actual)\n\n def test_str_method_no_fish(self):\n self.test.add_decoration(Ornament())\n self.test.add_decoration(Plant())\n self.test.add_decoration(Plant())\n expected = \"fresh:\\nFish: none\\nDecorations: 3\\nComfort: 11\"\n actual = self.test.__str__()\n self.assertEqual(expected, actual)\n","repo_name":"StanDobrev11/Python_OOP","sub_path":"OOP_Exams/03_APR_2021/TASK/project/aquarium/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"1802279073","text":"# Режим\tОбозначение\n# 'r'\tоткрытие на чтение (является значением по умолчанию).\n# 'w'\tоткрытие на запись, содержимое файла удаляется, если файла не существует, создается новый.\n# 'x'\tоткрытие на запись, если файла не существует, иначе исключение.\n# 'a'\tоткрытие на дозапись, информация добавляется в конец файла.\n# 'b'\tоткрытие в двоичном режиме.\n# 't'\tоткрытие в текстовом режиме (является значением по умолчанию).\n# '+'\tоткрытие на чтение и запись\n\n# Вспоминаем работу с файлом. Есть файл, в котором много англоязычных текстовых строк.\n# Считаем частоту встретившихся слов в файле, но через функции и map, без единого цикла!\n\nimport re\nimport sys\n\n\ndef count_words(word, dict_words):\n if word.lower() in dict_words:\n dict_words[word] += 1\n else:\n dict_words[word] = 1\n\n\ndef calc_words(text):\n words_list = list(re.findall(r'\\w+', text))\n dict_total = dict()\n list(map(lambda word: count_words(word, dict_total), words_list))\n return dict_total\n\n\nfilename = sys.argv[0]\n# далее открываем файл на чтение (опция 'r')\nf = open(\"task3.txt\", 'r') # в файле теперь file descriptor\n\nfile_lines = f.readlines()\nfile_text = \"\".join(file_lines)\n\nwords_total = calc_words(file_text)\nprint(words_total)\n\nf.close() # закрытие файла\n","repo_name":"OleksiiKhivrenko/python-course","sub_path":"Lesson 5/practice/lesson5.practice.task3.py","file_name":"lesson5.practice.task3.py","file_ext":"py","file_size_in_byte":1782,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"10819517009","text":"import argparse\nimport os\nimport simbiofilm as sb\nimport numpy as np\n\n# There may be some warnings from libraries we use. Feel free to enable this\nimport warnings\nwarnings.simplefilter(action=\"ignore\", category=FutureWarning)\n\n\nclass InfectAndEndController:\n def __init__(self, height, count, duration=10, biomass=False):\n \"\"\"\n If biomass is given, interpret height as a biomass\n \"\"\"\n self.infection_height = height\n self.infection_count = count\n self.end_time = 10000\n self.infection_length = duration\n self._use_mass = biomass\n\n def infect_point(self, space, time, phage, biomass, infectable):\n self.end_time = time + self.infection_length\n if self.infection_count > 1:\n sb.infect_point(space, time, self.infection_count, phage, infectable)\n else:\n sb.infect_at(space, time, phage, biomass, space.shape[1])\n\n def condition(self, space, time, phage, biomass, infectable):\n mass = sb.to_grid(biomass, \"mass\")\n if self._use_mass:\n return mass.sum() >= self.infection_height\n return (np.max(np.where(mass > 0)[0]) * space.dl) >= self.infection_height\n\n def end_condition(self, space, time):\n return time >= self.end_time\n\n\ndef config():\n return sb.cfg_from_dict(\n {\n \"general\": {\n \"output_frequency\": 1,\n \"nconnections\": 1,\n \"seed\": 1235,\n \"runtime\": 20,\n \"init_count\": 150,\n \"init_f\": 0.95,\n \"line_shove\": False,\n \"max_sim_time\": 100,\n \"3D\": False,\n \"connectivity\": 0.05,\n \"fixed_dt\": 1 / 24 + 0.0000001,\n \"targetone\": True,\n },\n \"space\": {\"dl\": 3e-6, \"shape\": (75, 200), \"well_mixed\": False},\n \"infection\": {'count': 120, 'height': 20e-6, 'duration': 1.5},\n \"substrate\": {\"max\": 6, \"diffusivity\": 2e-5, \"K\": 1.18, \"h\": 15e-6},\n \"erosion\": {\"biomass_rate\": 7.5e8, \"phage_rate\": 2.4e12},\n \"species1\": {\n \"density\": 200e3,\n \"mass\": 1e-12,\n \"division_mass\": 1.333e-12,\n \"impedance\": 6,\n \"mu\": 24.5,\n \"adhesion\": 1,\n \"resistant\": False,\n \"adsorbable\": True,\n \"yield_s\": 0.495,\n },\n \"species2\": {\n \"density\": 200e3,\n \"mass\": 1e-12,\n \"division_mass\": 1.333e-12,\n \"impedance\": 6,\n \"mu\": 24.5,\n \"adhesion\": 1,\n \"resistant\": True,\n \"adsorbable\": False,\n \"yield_s\": 0.495,\n },\n \"infected\": {\n \"density\": 200e3,\n \"mass\": 1e-12,\n \"division_mass\": 1.333e-12,\n \"impedance\": 6,\n \"adsorbable\": False, # not sure if used\n \"adhesion\": 1,\n },\n \"phage\": {\n \"diffusivity\": 3.30e-6,\n \"adsorption_rate\": 70,\n \"burst\": 120,\n \"incubation_period\": 0.02,\n \"adhesion\": 1,\n },\n }\n )\n\n\ndef setup(cfg, outdir=\"tmp\"):\n \"\"\"Do the thing.\"\"\"\n\n space = sb.Space(cfg.space)\n sim = sb.Simulation(space, cfg)\n\n substrate = sb.Solute(\"solute\", space, cfg.substrate)\n\n activeSpecies = [\n sb.Bacteria(\"species1\", space, cfg.species1, extragroups=['Susceptible']),\n sb.Bacteria(\"species2\", space, cfg.species2, extragroups=['Producer']),\n ]\n phage = sb.Phage(\"phage\", space, cfg.phage)\n infected = sb.InfectedBacteria(\"infected\", space, cfg.infected, cfg.phage)\n pairs = {phage: infected}\n\n sim.add_container(substrate, *activeSpecies, infected, phage)\n\n sb.inoculate_at(space, 0, activeSpecies[0], int(cfg.general.init_count * cfg.general.init_f))\n sb.inoculate_at(space, 0, activeSpecies[1], int(cfg.general.init_count * (1 - cfg.general.init_f)))\n\n sb.initialize_bulk_substrate(space, 0, substrate)\n\n # Set up infection & end of simulation\n ic = InfectAndEndController(\n cfg.infection.height,\n int(cfg.infection.count),\n cfg.infection.duration,\n cfg.space.well_mixed,\n )\n sim.add_event(ic.infect_point, ic.condition, [phage, activeSpecies, activeSpecies[0]])\n # change infection duration in InfectAndEndController\n sim.add_end_condition(ic.end_condition, f\"FIN-IC: {10} days after infection start\")\n\n reactions = [sb.MonodRateReaction(substrate, sp) for sp in activeSpecies]\n\n sim.add_behavior(\n sb.DiffusionReaction(substrate, reactions),\n sb.Biomass_growth(reactions),\n sb.Bacterial_division(),\n sb.Lysis(pairs),\n sb.Erode_individuals(cfg.erosion.biomass_rate),\n sb.Phage_randomwalk(cfg.erosion.phage_rate),\n sb.Detach_biomass(),\n sb.Relax_biofilm(),\n sb.Phage_interaction(pairs),\n )\n\n sim.initialize(f\"{outdir}/run1\", [], cfg.general.output_frequency)\n return sim\n\n\ndef main():\n import sys\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-p\", metavar=(\"names\", \"values\"), nargs=2)\n parser.add_argument(\"-o\", metavar=\"output_dir\")\n\n args = parser.parse_args()\n\n cfg = config()\n if args.p:\n cfg = sb.parse_params(args.p[0], args.p[1], cfg)\n name = args.o if args.o else f\"local_runs/{sys.argv[0][:-3]}\"\n sim = setup(cfg, name)\n try:\n sim.iterate(cfg.general.runtime, dt_max=0.02)\n except KeyboardInterrupt as kerr:\n sim.finish()\n raise kerr\n sim.finish()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"dvonderheide/test-project","sub_path":"phage.py","file_name":"phage.py","file_ext":"py","file_size_in_byte":5746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"29177319791","text":"import sys\nfrom PyQt5.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout, QMessageBox\nfrom PyQt5.QtGui import QImage, QPixmap\nfrom PyQt5.QtCore import Qt, QTimer\nimport cv2\nimport dlib\nimport numpy as np\nimport os\nimport mysql.connector\nfrom datetime import datetime\n\n# MySQL 연결 정보\ndb_config = {\n 'host': '34.22.65.53',\n 'user': 'root',\n 'password': 'cms',\n 'database': 'cms'\n}\n\n\n\nclass Attendance(QWidget):\n def __init__(self, user_id):\n super().__init__()\n \n now = datetime.now()\n self.date = now.strftime(\"%Y-%m-%d %H:%M:%S\")\n\n\n # 카메라 객체를 설정합니다\n self.cap = cv2.VideoCapture(0)\n\n # Load models and initialize variables\n self.init_models_and_vars()\n\n # 이미지를 표시할 라벨을 설정합니다\n self.label = QLabel(self)\n vbox = QVBoxLayout()\n vbox.addWidget(self.label)\n\n # 타이머를 설정합니다\n self.timer = QTimer()\n self.timer.timeout.connect(self.viewCam)\n self.timer.start(20)\n\n self.user_id = user_id\n\n self.setLayout(vbox)\n self.setWindowTitle(\"Attendance\")\n \n # 학생들을 모두 결석으로 초기화\n self.initialize_attendance()\n \n \n def initialize_attendance(self):\n # MySQL 데이터베이스에 연결합니다\n conn = mysql.connector.connect(**db_config)\n\n # 커서를 생성합니다\n cursor = conn.cursor()\n\n # 모든 학생의 목록을 가져옵니다\n query = \"SELECT id FROM student where teacher_id = %s\"\n cursor.execute(query, (self.get_teacher_id(),))\n students = students = cursor.fetchall()\n\n # 모든 학생의 출석 상태를 '결석'으로 초기화합니다\n for student in students:\n sql = \"INSERT INTO attendance (attend_type, date, student_id, teacher_id) VALUES (%s, %s, %s, %s)\"\n values = (1, self.date, student[0], self.user_id)\n\n # SQL 쿼리를 실행합니다\n cursor.execute(sql, values)\n\n # 변경 사항을 커밋합니다\n conn.commit()\n\n # 커넥션을 닫습니다\n conn.close()\n\n def init_models_and_vars(self):\n # 얼굴 인식 모델 로드\n self.face_recognition_model = dlib.face_recognition_model_v1(\n \"dlib_face_recognition_resnet_model_v1.dat\"\n )\n # 얼굴 랜드마크 모델 로드\n self.landmark_detector = dlib.shape_predictor(\n \"shape_predictor_68_face_landmarks.dat\"\n )\n\n # 얼굴 인식을 위한 Dlib face detector 생성\n self.face_detector = dlib.get_frontal_face_detector()\n\n self.known_embeddings = []\n self.known_labels = []\n self.attended = []\n self.load_known_faces()\n\n def load_known_faces(self):\n faces_folder = \"faces\"\n npy_files = [os.path.join(faces_folder, file) for file in os.listdir(faces_folder) if file.endswith(\".npy\")]\n for file in npy_files:\n embedding = np.load(file)\n label = os.path.basename(file).replace(\".npy\", \"\")\n self.known_embeddings.append(embedding)\n self.known_labels.append(label)\n self.attended.append(False)\n\n def viewCam(self):\n # OpenCV를 이용하여 카메라로부터 이미지를 캡쳐합니다\n ret, frame = self.cap.read()\n if ret:\n dlib_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n\n # 얼굴 인식 수행\n faces = self.face_detector(dlib_frame)\n\n # 각 얼굴에 대해 얼굴 식별 및 감정 분석 수행\n for face in faces:\n landmarks = self.landmark_detector(dlib_frame, face)\n unknown_embedding = self.face_recognition_model.compute_face_descriptor(dlib_frame, landmarks)\n unknown_embedding = np.array(unknown_embedding)\n\n min_distance = 1.0\n min_distance_index = -1\n for i, known_embedding in enumerate(self.known_embeddings):\n distance = np.linalg.norm(unknown_embedding - known_embedding)\n if distance < min_distance:\n min_distance = distance\n min_distance_index = i\n\n if min_distance < 0.3:\n if not self.attended[min_distance_index]:\n self.attended[min_distance_index] = True\n student_id = self.known_labels[min_distance_index]\n teacher_id = self.get_teacher_id() # 로그인 시 사용한 user_id 가져오기\n attend_type = 0 # 출석 유형 O\n self.check_attendance(student_id, teacher_id, attend_type)\n QMessageBox.information(self, \"알림\", f\"{student_id} 출석체크 되었습니다.\")\n self.attended[min_distance_index] = True\n\n # 얼굴 영역에 라벨 표시\n left, top, right, bottom = (\n face.left(),\n face.top(),\n face.right(),\n face.bottom(),\n )\n cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)\n cv2.putText(\n frame,\n f\"{self.known_labels[min_distance_index]} {min_distance}\",\n (left, top - 10),\n cv2.FONT_HERSHEY_SIMPLEX,\n 0.9,\n (0, 255, 0),\n 2,\n )\n\n # OpenCV 형식의 이미지를 Pixmap으로 변환합니다\n image = QImage(\n frame, frame.shape[1], frame.shape[0], QImage.Format_RGB888\n ).rgbSwapped()\n pixmap = QPixmap.fromImage(image)\n\n # Pixmap을 라벨에 표시합니다\n self.label.setPixmap(pixmap)\n\n def check_attendance(self, student_id, teacher_id, attend_type):\n # 현재 시간을 가져옵니다\n\n # try:\n # # MySQL 데이터베이스에 연결합니다\n # conn = mysql.connector.connect(**db_config)\n\n # # 커서를 생성합니다\n # cursor = conn.cursor()\n\n # # attendance 테이블에 데이터를 삽입하는 SQL 쿼리를 작성합니다\n # sql = \"INSERT INTO attendance (attend_type, self., student_id, teacher_id) VALUES (%s, %s, %s, %s)\"\n # values = (attend_type, self.date, student_id, teacher_id)\n\n # # SQL 쿼리를 실행합니다\n # cursor.execute(sql, values)\n\n # # 변경 사항을 커밋합니다\n # conn.commit()\n\n # # 커넥션을 닫습니다\n # conn.close()\n\n # except mysql.connector.Error as e:\n # print(f\"Error: {e}\")\n \n try:\n # MySQL 데이터베이스에 연결합니다\n conn = mysql.connector.connect(**db_config)\n\n # 커서를 생성합니다\n cursor = conn.cursor()\n\n # 해당 학생의 오늘의 출석 데이터가 이미 있는지 확인합니다.\n query = \"SELECT * FROM attendance WHERE student_id = %s AND teacher_id = %s AND DATE(date) = CURDATE()\"\n cursor.execute(query, (student_id, teacher_id))\n\n result = cursor.fetchone()\n\n if result:\n # 출석 데이터가 이미 있는 경우, attendance 테이블을 업데이트 합니다.\n sql = \"UPDATE attendance SET attend_type = %s, date = %s WHERE student_id = %s AND teacher_id = %s\"\n values = (attend_type, self.date, student_id, teacher_id)\n else:\n # 출석 데이터가 없는 경우, attendance 테이블에 데이터를 삽입합니다.\n sql = \"INSERT INTO attendance (attend_type, date, student_id, teacher_id) VALUES (%s, %s, %s, %s)\"\n values = (attend_type, self.date, student_id, teacher_id)\n\n # SQL 쿼리를 실행합니다\n cursor.execute(sql, values)\n\n # 변경 사항을 커밋합니다\n conn.commit()\n\n # 커넥션을 닫습니다\n conn.close()\n\n except mysql.connector.Error as e:\n print(f\"Error: {e}\")\n\n\n def get_teacher_id(self):\n # 로그인 시 사용한 user_id를 가져오는 함수를 구현하세요\n # 예를 들어, 로그인할 때 저장한 user_id를 반환하도록 합니다\n # 이 예시에서는 임의로 \"teacher123\"을 반환하도록 설정하였습니다\n return self.user_id\n\n def closeEvent(self, event):\n reply = QMessageBox.question(\n self, 'Message', 'Are you sure you want to exit?',\n QMessageBox.Yes | QMessageBox.No, QMessageBox.No\n )\n\n if reply == QMessageBox.Yes:\n # for i in range(len(self.attended)):\n # if not self.attended[i]:\n # check_attendance(self.known_labels[i], 1)\n self.close()\n event.accept()\n self.cap.release()\n else:\n event.ignore()\n\n\n\n# if __name__ == \"__main__\":\n# app = QApplication(sys.argv)\n# ex = MyApp()\n# ex.show()\n# sys.exit(app.exec_())","repo_name":"MJU-ClassmanagementSystem/PyQt","sub_path":"attendance.py","file_name":"attendance.py","file_ext":"py","file_size_in_byte":9341,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"9031699796","text":"\"\"\"\nПрограмма: Frontend часть проекта\nВерсия: 1.0\n\"\"\"\n\nfrom src import charts, evaluation, data, train\n\nimport streamlit as st\nimport yaml\n\nCONFIG_PATH = \"../config/params.yaml\"\n\n\ndef home():\n \"\"\"\n Функция для создания стартовой страницы с описанием проекта.\n \"\"\"\n\n # заголовок страницы\n st.markdown(\"# Описание проекта\")\n st.title(\"MLOps project: Recommender system for suppliers in trading platform\")\n\n # описание проекта\n st.write(\"\"\"Оператор электронных торгов предоставляет торговую площадку для государственных заказчиков,\n госкомпаний и коммерческих предприятий. Им необходима рекомендательная система, которая бы обеспечила \n поставщикам удобную навигацию по сервису, преоритетно показывая релевантные для них торги.\"\"\")\n\n # список признаков датасета\n st.markdown(\n \"\"\"\n ### Описание полей \n \n Поля в датасете purchases: \n \n - purchase – Ун��кальный идентификатор закупки\n - region_code – Регион поставки\n - min_publish_date – Дата публикации закупки \n - purchase_name – Название закупки\n - forsmallbiz – Если да, то большие компании не могут предлагать свое участие в этой закупке\n - price – Цена за закупку, предлагаемая заказчиком\n - customer – Уникальный идентификатор заказчика\n - okpd2_code – Код стандартизации товара в соответствии со справочником ОКПД2, обрезанный до 3 числа\n - okpd2_names – Названия ОКПД2\n - Item_descriptions – Описания товаров\n \n Поля в датасете suppliers: \n \n - purchase – Уникальный идентификатор закупки\n - supplier – Уникальный идентификатор поставщика\n - is_winner – Выиграл ли этот поставщик в этой закупке\n\n \"\"\"\n )\n\n\ndef eda():\n \"\"\"\n Функция для создания страницы разведочного анализа данных с графиками.\n \"\"\"\n # заголовок страницы\n st.title(\"Разведочный анализ данных\")\n\n with open(CONFIG_PATH) as file:\n config = yaml.load(file, Loader=yaml.FullLoader)\n\n # параметры конфигурации предобработки\n preproc = config['preprocessing']\n\n # загрузка данных\n df = data.get_data(preproc['train_data'], 'vectorized')\n st.write(df[:5])\n\n uniq_okpd2 = st.sidebar.checkbox(\"Кол-во уникальных ОКПД2 у поставщиков\")\n season_activity = st.sidebar.checkbox(\"Активность поставщиков в течение года\")\n price_mean_std = st.sidebar.checkbox(\"Средняя цена и разброс цены закупок поставщиков\")\n\n if uniq_okpd2:\n st.pyplot(\n charts.chart_unique_okpd2(df, 'n_unique_okpd2',\n title=\"Плотность распределения кол-ва уникальных ОКПД2 у поставщиков\")\n )\n\n if season_activity:\n ax = charts.chart_season_activity(df, 'month', 'supplier',\n title=\"Кол-во участий поставщиков в разрезе месяца\")\n\n fig = ax.get_figure()\n\n st.pyplot(fig)\n\n if price_mean_std:\n ax = charts.chart_price(df, 'supplier', 'price',\n title='Средняя цена - Разброс цены закупки у поставщиков')\n\n fig = ax.get_figure()\n\n st.pyplot(fig)\n\n\ndef train_recommender():\n \"\"\"\n Функция для создания страницы тренировки рекомендательной модели.\n \"\"\"\n # заголовок страницы\n st.title(\"Тренировка рекомендательной модели\")\n\n with open(CONFIG_PATH) as file:\n config = yaml.load(file, Loader=yaml.FullLoader)\n\n # ввод id поставщика\n supplier_id = st.text_input(\"Введите id поставщика\")\n\n if supplier_id:\n endpoint = config['endpoints']['train_recommender'] + str(supplier_id)\n\n # кнопка для запуска тренировки модели\n if st.button(\"Запустить тренировку\"):\n # тренировка модели\n train.training_recommender(endpoint)\n\n\ndef train_win_predictor():\n \"\"\"\n Функция для создания страницы тренировки прогнозирующей модели.\n \"\"\"\n # заголовок страницы\n st.title(\"Тренировка прогнозирующей модели\")\n\n with open(CONFIG_PATH) as file:\n config = yaml.load(file, Loader=yaml.FullLoader)\n\n endpoint = config['endpoints']['train_win_predictor']\n\n # кнопка для запуска тренировки модели\n if st.button(\"Запустить тренировку\"):\n # тренировка модели\n train.training_win_predictor(endpoint)\n\n\ndef get_recommends():\n \"\"\"\n Получение предсказаний рекомендательной модели\n \"\"\"\n # заголовок страницы\n st.title(\"Получение предсказаний рекомендательной модели\")\n\n with open(CONFIG_PATH) as file:\n config = yaml.load(file, Loader=yaml.FullLoader)\n\n # ввод id поставщика\n supplier_id = st.text_input(\"Введите id поставщика\")\n\n if supplier_id:\n endpoint = config[\"endpoints\"][\"evaluate_recommender\"] + str(supplier_id)\n\n if st.button(\"Запустить подбор рекомендаций\"):\n evaluation.evaluate_recommender(endpoint)\n\n\ndef get_predicts():\n \"\"\"\n Получение предсказаний прогнозирующей модели\n \"\"\"\n # заголовок страницы\n st.title(\"Получение предсказаний прогнозирующей модели\")\n\n with open(CONFIG_PATH) as file:\n config = yaml.load(file, Loader=yaml.FullLoader)\n\n endpoint = config[\"endpoints\"][\"evaluate_win_predictor\"]\n\n if st.button(\"Запустить подбор рекомендаций\"):\n evaluation.evaluate_win_predictor(endpoint)\n\n\ndef get_metrics():\n \"\"\"\n Вывод метрик качества\n \"\"\"\n # заголовок страницы\n st.title(\"Метрики качества\")\n\n with open(CONFIG_PATH) as file:\n config = yaml.load(file, Loader=yaml.FullLoader)\n\n with open(config['train']['recommender']['metrics']) as file:\n recommender_metrics = yaml.load(file, Loader=yaml.FullLoader)\n\n with open(config['train']['win_predictor']['metrics']) as file:\n win_predictor_metrics = yaml.load(file, Loader=yaml.FullLoader)\n\n dict_metrics = {\n \"Базовые метрики модели рекомендаций\": recommender_metrics['basic_metrics'],\n \"Лучшие метрики модели рекомендаций\": recommender_metrics['best_metrics'],\n \"Базовые метрики модели прогнозирования\": win_predictor_metrics['basic_metrics']['catboost'],\n \"Лучшие метрики модели прогнозирования\": win_predictor_metrics['best_metrics']['catboost']\n }\n\n type_metric = st.sidebar.selectbox(\"Метрики качества\", dict_metrics.keys())\n\n roc_auc, precision, recall, f1_metric, logloss = st.columns(5)\n roc_auc.metric(\n \"ROC-AUC\",\n dict_metrics[type_metric][\"ROC_AUC\"],\n )\n precision.metric(\n \"Precision\",\n dict_metrics[type_metric][\"Precision\"]\n )\n recall.metric(\n \"Recall\",\n dict_metrics[type_metric][\"Recall\"],\n )\n f1_metric.metric(\n \"F1 score\",\n dict_metrics[type_metric][\"f1\"]\n )\n logloss.metric(\n \"Logloss\",\n dict_metrics[type_metric][\"Logloss\"]\n )\n\n\ndef main():\n \"\"\"\n Сборка пайплайна в одном блоке\n \"\"\"\n pages_to_funcs = {\n \"Описание проекта\": home,\n \"Разведочный анализ данных\": eda,\n \"Тренировка рекомендательной модели\": train_recommender,\n \"Тренировка прогнозирующей модели\": train_win_predictor,\n \"Получение рекомендаций\": get_recommends,\n \"Получение прогнозов победителя\": get_predicts,\n \"Метрики качества моделей\": get_metrics\n }\n page = st.sidebar.selectbox(\"Выберите пункт\", pages_to_funcs.keys())\n pages_to_funcs[page]()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Lsdbot/mlops-fastapi","sub_path":"frontend/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9771,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"70983736087","text":"from pyspark import SparkContext, SparkConf\n\nconf = SparkConf().setAppName(\"MaxMin\").setMaster(\"local[2]\")\n\nsc = SparkContext(conf=conf)\n\nrdd = sc.textFile(\"average_quiz_sample.csv\")\n\nrdd = rdd.map(lambda x: x.split(\",\")).map(lambda x: (x[1], float(x[2])))\n\nprint(rdd.reduceByKey(lambda x, y: x if x > y else y).collect())\nprint(rdd.reduceByKey(lambda x, y: x if x < y else y).collect())\n","repo_name":"Zalasyu/PySpark-AWS","sub_path":"SparkRDDs/MaxMin/quiz_maxmin.py","file_name":"quiz_maxmin.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"19527065755","text":"import datetime\nimport json\nfrom urllib.parse import parse_qs\n\nimport bottle\nfrom jinja2 import Template, UndefinedError, TemplateError\nfrom simple_mailer import exceptions\nfrom simple_mailer.captcha import CaptchaClient\nfrom simple_mailer.config import settings\nfrom simple_mailer.mailer import Mailer\nfrom simple_mailer.utils import get_logger\n\nlog = get_logger(__name__)\n\n\nclass Dispatcher:\n \"\"\"A controller that processes incoming HTTP requests and sends mail.\"\"\"\n\n data: dict\n metadata: dict\n captcha_client: CaptchaClient\n\n def __init__(self, data=None, metadata=None):\n self.data = {} if data is None else data\n self.metadata = {} if metadata is None else metadata\n self.captcha_client = CaptchaClient.from_environment()\n\n def process_data(self) -> \"Dispatcher\":\n \"\"\"Process the data, applying filters and manipulations appropriately\n \"\"\"\n data = self.data\n\n log.debug(f\"Received payload: {data}\")\n\n fields_to_include = set(settings.FIELDS_INCLUDED)\n if fields_to_include:\n if self.captcha_client.key:\n fields_to_include.add(self.captcha_client.key)\n data = {k: v for k, v in data.items() if k in fields_to_include}\n fields_to_exclude = settings.FIELDS_EXCLUDED\n if fields_to_exclude:\n data = {\n k: v for k, v in data.items() if k not in fields_to_exclude\n }\n\n log.debug(f\"After filters were applied, the payload was: {data}\")\n\n if not data:\n raise exceptions.SubmittedDataInvalid(\"Need at least one field\")\n self.data = data\n return self\n\n def parse_request(self, request: bottle.Request) -> \"Dispatcher\":\n \"\"\"Extract and store the payload of a given HTTP request.\"\"\"\n env = request.environ\n content_type = env[\"CONTENT_TYPE\"]\n client_ip = env.get(\"HTTP_X_FORWARDED_FOR\", env.get(\"REMOTE_ADDR\", \"\"))\n log.info(\n f\"Processing HTTP request from client with IP {client_ip} ...\"\n )\n self.metadata = {\n \"mailer_url\": request.url,\n \"origin\": request.remote_addr or \"\",\n \"client_ip\": client_ip,\n }\n body = request.body.read().decode(request.POST.input_encoding)\n if content_type == \"application/x-www-form-urlencoded\":\n data = {k: (\", \").join(v) for k, v in parse_qs(body).items()}\n elif content_type == \"application/json\":\n try:\n data = json.loads(body)\n except json.JSONDecodeError:\n err = log.error(\"Received invalid JSON\")\n log.debug(f\"Invalid JSON: {body}\")\n raise exceptions.SubmittedDataInvalid(err)\n else:\n log.debug(f\"Submitted payload: {data}\")\n else:\n err = (\n f\"Client sent request unsupported content type: {content_type}\"\n )\n log.warning(err)\n raise exceptions.ContentTypeUnsupported(err)\n self.data = data\n self.process_data()\n return self\n\n def _get_templated_body(self) -> str:\n \"\"\"Assemble and return the body of the message using the template.\n\n Any captcha data is automatically removed, if present.\n \"\"\"\n tmpl_path = settings.MAIL_TEMPLATE_PATH\n data = self.data.copy()\n if self.captcha_client.key:\n data.pop(self.captcha_client.key)\n if tmpl_path:\n try:\n with open(tmpl_path) as fd:\n tmpl = Template(fd.read())\n try:\n return tmpl.render(data=data, metadata=self.metadata)\n except UndefinedError as exc:\n raise TemplateError(\n f\"The template did not define the required fields:\"\n f\" {exc.message}\"\n )\n except IOError:\n err = (\n f\"Cannot open template file. \"\n f\"Check if it exists and is readable.\"\n )\n log.error(err)\n raise exceptions.ConfigError(err)\n else:\n return json.dumps(self.data)\n\n def get_server(self) -> Mailer:\n \"\"\"Get an instance of the mailer server.\"\"\"\n return Mailer(\n host=settings.SMTP_HOST,\n port=settings.SMTP_PORT,\n use_tls=settings.USE_TLS,\n )\n\n def dispatch(self) -> None:\n \"\"\"Dispatch a given HTTP request.\n\n Returns true or false depending on the outcome.\n \"\"\"\n self.captcha_client.validate_data(self.data)\n\n self.metadata.update(\n timestamp_utc=datetime.datetime.utcnow().isoformat()\n )\n\n cfg = {\n \"from_\": settings.FROM_ADDRESS,\n \"to\": settings.TO_ADDRESS,\n \"reply_to\": self.get_reply_to() or settings.FROM_ADDRESS,\n \"subject\": self.get_subject(),\n \"body\": self._get_templated_body(),\n }\n self.get_server().connect().send_message(**cfg).disconnect()\n log.info(\n f\"Sent email to server {settings.SMTP_HOST}:{settings.SMTP_PORT}\"\n )\n\n def get_reply_to(self) -> str:\n \"\"\"Get the reply-to address if it has been defined.\n\n If it hasn't been defined, just use the From: address.\"\"\"\n reply_to_field = settings.REPLY_TO_FIELD\n if reply_to_field:\n try:\n address = self.data[reply_to_field]\n except KeyError:\n pass\n else:\n log.debug(f\"Setting Reply-to field to: {address}\")\n return address\n\n return \"\"\n\n def get_subject(self) -> str:\n \"\"\"Get the subject for the current email.\"\"\"\n subject = settings.MAIL_SUBJECT\n if subject:\n tmpl = Template(subject)\n return tmpl.render(data=self.data, metadata=self.metadata)\n else:\n return subject\n","repo_name":"zedr/simple-mailer","sub_path":"src/simple_mailer/dispatcher.py","file_name":"dispatcher.py","file_ext":"py","file_size_in_byte":6019,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"}
+{"seq_id":"5960010402","text":"import re\nimport urllib\n\nfrom st_assistant.data.stock_price import StockPrice\n\n\nclass StockPriceLoader(object):\n \n def __init__(self):\n pass\n\n def load(self, stock_ids: list):\n pass\n\n\nclass SinaStockPriceLoader(StockPriceLoader):\n\n PRICE_FILE = '/Users/yanpan/Documents/stock_price_data.txt'\n SERVICE_URL = 'https://hq.sinajs.cn/list='\n RESP_REG = r'var (.*)=\"(.*)\";'\n HK_EX_CNY_RATE = 0.82\n\n def load(self, stock_ids: list):\n url = '%s%s' % (self.SERVICE_URL, ','.join(stock_ids))\n with urllib.request.urlopen(url) as f:\n response = f.read().decode('gbk')\n print(response)\n return self.loadFromData(response)\n\n def loadToFile(self, stock_ids: list):\n url = '%s%s' % (self.SERVICE_URL, ','.join(stock_ids))\n with urllib.request.urlopen(url) as f:\n response = f.read().decode('gbk')\n with open(self.PRICE_FILE, 'r+') as f:\n print(response)\n f.write(response)\n\n def loadFromDataFile(self):\n with open(self.PRICE_FILE, encoding='utf-8') as f:\n return self.loadFromData(f.read())\n\n def loadFromData(self, stock_price_data):\n loaded_prices = []\n foundMatches = re.findall(self.RESP_REG, stock_price_data)\n for match in foundMatches:\n stockId = match[0].split('_')[2]\n prices = match[1].split(',')\n if stockId.startswith('sh') or stockId.startswith('sz'):\n price = self.parseSHSZPrice(stockId, prices)\n elif stockId.startswith('hk'):\n price = self.parseHKPrice(stockId, prices)\n loaded_prices.append(price)\n return loaded_prices\n\n def parseSHSZPrice(self, stockId, prices):\n return StockPrice(\n stock_id=stockId,\n name=prices[0],\n start=float(prices[1]),\n last_end=float(prices[2]),\n current=float(prices[3]),\n high=float(prices[4]),\n low=float(prices[5]))\n\n def parseHKPrice(self, stockId, prices):\n return StockPrice(\n stock_id=stockId,\n name=prices[1],\n start=float(prices[2]) * self.HK_EX_CNY_RATE,\n last_end=float(prices[3]) * self.HK_EX_CNY_RATE,\n current=float(prices[4]) * self.HK_EX_CNY_RATE,\n high=float(prices[5]) * self.HK_EX_CNY_RATE,\n low=float(prices[6]) * self.HK_EX_CNY_RATE)","repo_name":"yan0621/ta","sub_path":"st_assistant/data/stock_price_loader.py","file_name":"stock_price_loader.py","file_ext":"py","file_size_in_byte":2191,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"5809443034","text":"#/usr/bin/python\n'''\nRepresenting a chess set in Python\nPart 2\nBrendan Scott\n27 April 2013\n\nDark square on a1\nRequires there to be a directory called\nchess_data in the current directory, and for that\ndata directory to have a copy of all the images\n\n'''\n\n# import Tkinter as tk\n# from Tkinter import PhotoImage\nfrom tkinter import *\nimport os.path\nimport os\n\n#column_reference = \"1 2 3 4 5 6 7 8\".split(\" \")\ncolumn_reference = \"a b c d e f g h\".split(\" \")\nEMPTY_SQUARE = \" \"\n\nTILE_WIDTH = 60\n'''We have used a tile width of 60 because the images we are used are 60x60 pixels\nThe original svg files were obtained from\nhttp://commons.wikimedia.org/wiki/Category:SVG_chess_pieces/Standard_transparent\nafter downloading they were batch converted to png, then gif files. Bash one liners\nto do this:\nfor i in $(ls *.svg); do inkscape -e ${i%.svg}.png -w 60 -h 60 $i ; done\nfor i in $(ls *.png); do convert $i ${i%.png}.gif ; done\nwhite and black tiles were created in inkscape\n'''\n\nBOARD_WIDTH = 8*TILE_WIDTH\nBOARD_HEIGHT = BOARD_WIDTH\nDATA_DIR = \"chess_data\"\nTILES = {\n \"black_tile\":\"black_tile.gif\",\n \"Bishop.White\":\"chess_b451.gif\",\n \"Bishop.Black\":\"chess_b45.gif\",\n \"King.White\":\"chess_k451.gif\",\n \"King.Black\":\"chess_k45.gif\",\n \"Knight.White\":\"chess_n451.gif\",\n \"Knight.Black\":\"chess_n45.gif\",\n \"Pawn.White\":\"chess_p451.gif\",\n \"Pawn.Black\":\"chess_p45.gif\",\n \"Queen.White\":\"chess_q451.gif\",\n \"Queen.Black\":\"chess_q45.gif\",\n \"Rook.White\":\"chess_r451.gif\",\n \"Rook.Black\":\"chess_r45.gif\",\n \"white_tile\":\"white_tile.gif\"\n }\n\n\nfrom enum import Enum\nclass Color(Enum):\n UNDEFINED = -1\n BLACK = 0\n WHITE = 1\n\nclass Location:\n def __init__(self, x = None, y = None):\n self.y = x\n self.x = y\n\n def __str__(self):\n return \"(\" + str(self.x) + \", \" + str(self.y) + \")\"\n\n __repr__ = __str__\n\nclass Piece:\n def __init__(self, color, x, y):\n self.m_color = color\n self.m_location = Location(x, y)\n\n @property\n def color(self):\n return self.m_color\n\n @color.setter\n def color(self, c):\n self.m_color = c\n\n @property\n def location(self):\n return self.m_location\n\n @location.setter\n def location(self, x, y):\n self.m_location = Location(x, y)\n\n def get_tile(self, piece_str):\n color = str(self.m_color).split(\".\")[1]\n color = color[0] + color[1:].lower()\n return piece_str + \".\" + str(color)\n\n def render(self):\n raise Exception(\"Render not implemented\")\n\n def valid_move(self, dst_x, dst_y):\n raise Exception(\"moves not implemented\")\n\nclass Pawn(Piece):\n # Everything will be represented in bits\n def __init__(self, board, color, x, y):\n Piece.__init__(self, color, x, y)\n\n @property\n def tile(self):\n piece_str = \"Pawn\"\n return self.get_tile(piece_str)\n\n def valid_move(self, dst_x, dst_y):\n loc = self.m_location\n if self.m_color == Color.WHITE:\n if abs(dst_x - loc.x) == 1 and loc.y - dst_y == 1 and self.m_board[dst_y][dst_x].color == Color.BLACK:\n return True\n\n elif abs(dst_x - loc.x) == 0 and loc.y - dst_y >= 1 and loc.y - dst_y <= 2 and self.m_board[dst_y][dst_x] == EMPTY_SQUARE:\n return True\n\n elif self.m_color == Color.BLACK:\n if abs(dst_x - loc.x) == 1 and loc.y - dst_y == -1 and self.m_board[dst_y][dst_x].color == Color.WHITE:\n return True\n\n elif abs(dst_x - loc.x) == 0 and loc.y - dst_y >= 1 and loc.y - dst_y <= 2 and self.m_board[dst_y][dst_x] == EMPTY_SQUARE:\n return True\n\n\nclass Queen(Piece):\n def __init__(self, board, color, x, y):\n Piece.__init__(self, color, x, y)\n\n @property\n def tile(self):\n piece_str = \"Queen\"\n return self.get_tile(piece_str)\n\nclass King(Piece):\n def __init__(self, board, color, x, y):\n Piece.__init__(self, color, x, y)\n\n @property\n def tile(self):\n piece_str = \"King\"\n return self.get_tile(piece_str)\n\nclass Rook(Piece):\n def __init__(self, board, color, x, y):\n Piece.__init__(self, color, x, y)\n\n @property\n def tile(self):\n piece_str = \"Rook\"\n return self.get_tile(piece_str)\n\nclass Bishop(Piece):\n def __init__(self, board, color, x, y):\n Piece.__init__(self, color, x, y)\n\n @property\n def tile(self):\n piece_str = \"Bishop\"\n return self.get_tile(piece_str)\n\nclass Knight(Piece):\n def __init__(self, board, color, x, y):\n Piece.__init__(self, color, x, y)\n\n @property\n def tile(self):\n piece_str = \"Knight\"\n return self.get_tile(piece_str)\n\n\nclass Model(object):\n def __init__(self):\n '''create a chess board with pieces positioned for a new game\n row ordering is reversed from normal chess representations\n but corresponds to a top left screen coordinate\n '''\n self.board = []\n\n white_pieces = [Rook(self.board, Color.WHITE, 0, 0),\n Knight(self.board, Color.WHITE, 1, 0),\n Bishop(self.board, Color.WHITE, 2, 0),\n Queen(self.board, Color.WHITE, 3, 0),\n King(self.board, Color.WHITE, 4, 0),\n Bishop(self.board, Color.WHITE, 5, 0),\n Knight(self.board, Color.WHITE, 6, 0),\n Rook(self.board, Color.WHITE, 7, 0)]\n\n white_pawns = [Pawn(self.board, Color.WHITE, i, 0) for i in range(0, 8)]\n\n black_pieces = [Rook(self.board, Color.BLACK, 0, 0),\n Knight(self.board, Color.BLACK, 1, 0),\n Bishop(self.board, Color.BLACK, 2, 0),\n Queen(self.board, Color.BLACK, 3, 0),\n King(self.board, Color.BLACK, 4, 0),\n Bishop(self.board, Color.BLACK, 5, 0),\n Knight(self.board, Color.BLACK, 6, 0),\n Rook(self.board, Color.BLACK, 7, 0)]\n\n black_pawns = [Pawn(self.board, Color.BLACK, i, 0) for i in range(0, 8)]\n\n self.board.append(black_pieces)\n self.board.append(black_pawns)\n\n for i in range(4):\n self.board.append([EMPTY_SQUARE]*8)\n\n self.board.append(white_pawns)\n self.board.append(white_pieces)\n\n def validate_move(self, start, destination):\n start.i = int(start.i)\n start.j = int(start.j)\n destination.i = int(destination.i)\n destination.j = int(destination.j)\n\n if self.board[start.i][start.j] == EMPTY_SQUARE:\n return\n\n piece = self.board[start.i][start.j]\n\n\n def move(self, start, destination):\n ''' move a piece located at the start location to destination\n (each an instance of BoardLocation)\n Does not check whether the move is valid for the piece\n '''\n start.i = int(start.i)\n start.j = int(start.j)\n destination.i = int(destination.i)\n destination.j = int(destination.j)\n # error checking\n for c in [start, destination]: # check coordinates are valid\n if c.i > 7 or c.j > 7 or c.i <0 or c.j <0:\n return\n if start.i == destination.i and start.j == destination.j: # don't move to same location\n return\n\n if self.board[start.i][start.j] == EMPTY_SQUARE: #nothing to move\n return\n\n f = self.board[start.i][start.j]\n self.board[destination.i][destination.j] = f\n self.board[start.i][start.j] = EMPTY_SQUARE\n\n\nclass BoardLocation(object):\n def __init__(self, i, j):\n self.i = i\n self.j = j\n\nclass View(Frame):\n def __init__(self, parent = None):\n Frame.__init__(self, parent)\n self.canvas = Canvas(self, width=BOARD_WIDTH, height=BOARD_HEIGHT)\n self.canvas.pack()\n self.images = {}\n for image_file_name in TILES:\n f = os.path.join(DATA_DIR, TILES[image_file_name])\n if not os.path.exists(f):\n print((\"Error: Cannot find image file: %s at %s - aborting\"%(TILES[image_file_name], f)))\n exit(-1)\n self.images[image_file_name]= PhotoImage(file=f)\n '''This opens each of the image files, converts the data into a form that Tkinter\n can use, then stores that converted form in the attribute self.images\n self.images is a dictionary, keyed by the letters we used in our model to\n represent the pieces - ie PRNBKQ for white and prnbkq for black\n eg self.images['N'] is a PhotoImage of a white knight\n this means we can directly translate a board entry from the model into a picture\n '''\n self.pack()\n\n\n def clear_canvas(self):\n ''' delete everything from the canvas'''\n items = self.canvas.find_all()\n for i in items:\n self.canvas.delete(i)\n\n def draw_row(self, y, first_tile_white=True, debug_board = False):\n ''' draw a single row of alternating black and white tiles,\n the colour of the first tile is determined by first_tile_white\n if debug_board is set show the coordinates of each of the tile corners\n '''\n\n if first_tile_white:\n remainder = 1\n else:\n remainder = 0\n\n for i in range(8):\n x = i*TILE_WIDTH\n if i % 2 == remainder:\n # i %2 is the remainder after dividing i by 2\n # so i%2 will always be either 0 (no remainder- even numbers) or\n # 1 (remainder 1 - odd numbers)\n # this tests whether the number i is even or odd\n tile = self.images['black_tile']\n else:\n tile = self.images['white_tile']\n self.canvas.create_image(x, y, anchor = NW, image=tile)\n # NW is a constant in the Tkinter module. It stands for \"north west\"\n # that is, the top left corner of the picture is to be located at x,y\n # if we used another anchor, the grid would not line up properly with\n # the canvas size\n if debug_board: # implicitly this means if debug_board == True.\n ''' If we are drawing a debug board, draw an arrow showing top left\n and its coordinates. '''\n text_pos = (x+TILE_WIDTH/2, y+TILE_WIDTH/2)\n line_end = (x+TILE_WIDTH/4, y +TILE_WIDTH/4)\n self.canvas.create_line((x, y), line_end, arrow = FIRST)\n text_content = \"(%s,%s)\"%(x, y)\n self.canvas.create_text(text_pos, text=text_content)\n\n\n def draw_empty_board(self, debug_board = False):\n ''' draw an empty board on the canvas\n if debug_board is set show the coordinates of each of the tile corners'''\n y = 0\n for i in range(8): # draw 8 rows\n y = i*TILE_WIDTH\n # each time, advance the y value at which the row is drawn\n # by the length of the tile\n first_tile_white = not (i%2)\n self.draw_row(y, first_tile_white, debug_board )\n\n def draw_pieces(self, board):\n for i, row in enumerate(board):\n # using enumerate we get an integer index\n # for each row which we can use to calculate y\n # because rows run down the screen, they correspond to the y axis\n # and the columns correspond to the x axis\n for j, piece in enumerate(row):\n if piece == EMPTY_SQUARE:\n continue # skip empty tiles\n tile = self.images[piece.tile]\n x = j*TILE_WIDTH\n y = i*TILE_WIDTH\n self.canvas.create_image(x, y, anchor=NW, image = tile)\n\n def display(self, board, debug_board= False):\n ''' draw an empty board then draw each of the\n pieces in the board over the top'''\n\n self.clear_canvas()\n self.draw_empty_board(debug_board=debug_board)\n if not debug_board:\n self.draw_pieces(board)\n\n # first draw the empty board\n # then draw the pieces\n # if the order was reversed, the board would be drawn over the pieces\n # so we couldn't see them\n\n def display_debug_board(self):\n self.clear_canvas()\n self.draw_empty_board()\n\n\nclass Controller(object):\n def __init__(self, parent = None, model = None):\n if model is None:\n self.m = Model()\n else:\n self.m = model\n self.v = View(parent)\n ''' we have created both a model and a view within the controller\n the controller doesn't inherit from either model or view\n '''\n self.v.canvas.bind(\"\", self.handle_click)\n # this binds the handle_click method to the view's canvas for left button down\n\n self.clickList = []\n # I have kept clickList here, and not in the model, because it is a record of what is happening\n # in the view (ie click events) rather than something that the model deals with (eg moves).\n\n def run(self, debug_mode = False):\n self.update_display(debug_board=debug_mode)\n mainloop()\n\n def handle_click(self, event):\n ''' Handle a click received. The x,y location of the click on the canvas is at\n (event.x, event.y)\n First, we need to translate the event coordinates (ie the x,y of where the click occurred)\n into a position on the chess board\n add this to a list of clicked positions\n every first click is treated as a \"from\" and every second click as a\"to\"\n so, whenever there are an even number of clicks, use the most recent to two to perform a move\n then update the display\n '''\n j = event.x // TILE_WIDTH\n # the / operator is called integer division\n # it returns the number of times TILE_WIDTH goes into event.x ignoring any remainder\n # eg: 2/2 = 1, 3/2 = 1, 11/5 = 2 and so on\n # so, it should return a number between 0 (if x < TILE_WIDTH) though to 7\n i = event.y // TILE_WIDTH\n\n self.clickList.append(BoardLocation(i, j))\n # just maintain a list of all of the moves\n # this list shouldn't be used to replay a series of moves because that is something\n # which should be stored in the model - but it wouldn't be much trouble to\n # keep a record of moves in the model.\n if len(self.clickList) % 2 ==0:\n # move complete, execute the move\n self.m.move(self.clickList[-2], self.clickList[-1])\n # use the second last entry in the clickList and the last entry in the clickList\n self.update_display()\n\n def update_display(self, debug_board= False):\n self.v.display(self.m.board, debug_board = debug_board)\n\n\n def parse_move(self, move):\n ''' Very basic move parsing\n given a move in the form ab-cd where a and c are in [a,b,c,d,e,f,g,h]\n and b and d are numbers from 1 to 8 convert into BoardLocation instances\n for start (ab) and destination (cd)\n Does not deal with castling (ie 0-0 or 0-0-0) or bare pawn moves (e4)\n or capture d4xe5 etc\n No error checking! very fragile\n '''\n\n s, d = move.split(\"-\")\n\n i = 8- int(s[-1]) # board is \"upside down\" with reference to the representation\n j = column_reference.index(s[0])\n start = BoardLocation(i, j)\n\n i = 8- int(d[-1])\n j= column_reference.index(d[0])\n destination = BoardLocation(i, j)\n\n return start, destination\n\nif __name__==\"__main__\":\n if not os.path.exists(DATA_DIR):\n ''' basic check - if there are files missing from the data directory, the\n program will still fail '''\n dl = eval(input(\"Cannot find chess images directory. Download from website? (Y/n)\"))\n if dl.lower() == \"n\":\n print(\"No image files found, quitting.\")\n exit(0)\n print((\"Creating directory: %s\"%os.path.join(os.getcwd(), DATA_DIR)))\n import urllib.request, urllib.parse, urllib.error\n\n os.mkdir(DATA_DIR)\n url_format= \"http://python4kids.files.wordpress.com/2013/04/%s\"\n for k, v in list(TILES.items()):\n url = url_format%v\n target_filename = os.path.join(DATA_DIR, v)\n print((\"Downloading file: %s\"%v))\n urllib.request.urlretrieve(url, target_filename)\n\n parent = Tk()\n c = Controller(parent)\n c.run(debug_mode= False)\n","repo_name":"ssarangi/chess","sub_path":"chess.py","file_name":"chess.py","file_ext":"py","file_size_in_byte":16576,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"10882675522","text":"\"\"\" Default urlconf for webapp \"\"\"\n\nfrom django.conf import settings\nfrom django.conf.urls import include, patterns, url\nfrom django.conf.urls.static import static\nfrom django.contrib import admin\nadmin.autodiscover()\n\n\ndef bad(request):\n \"\"\" Simulates a server error \"\"\"\n 1 / 0\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'webapp.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n url(r'^o/', include('oauth2_provider.urls',\n namespace='oauth2_provider')),\n url(r'^admin/', include(admin.site.urls)),\n url(r'^swimapp/', include('swimapp.urls')),\n url(r'^api/', include('api.urls')),\n url(r'^bad/$', bad),\n url(r'', include('base.urls')),\n)\n\nurlpatterns += static(settings.STATIC_URL,\n document_root=settings.STATIC_ROOT)\n\nif settings.DEBUG:\n import debug_toolbar\n urlpatterns += patterns('',\n url(r'^__debug__/', include(debug_toolbar.urls)),\n )\n","repo_name":"mbasanta/swimtimerwebapp","sub_path":"webapp/webapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"}
+{"seq_id":"28150821002","text":"from time import time\nimport os\nimport argparse\nimport ast\nimport numpy as np\nimport cv2\nimport mindspore\nimport mindspore.common.dtype as mstype\nfrom mindspore import nn\nfrom mindspore.train.serialization import load_param_into_net, load_checkpoint\nfrom mindspore.ops import operations as ops\nfrom mindspore import Tensor, context\nfrom mindspore.common import set_seed\nfrom mindspore.context import ParallelMode\nfrom mindspore.communication.management import init, get_rank, get_group_size\nfrom mindspore.train.callback import (\n CheckpointConfig,\n ModelCheckpoint,\n _InternalCallbackParam,\n RunContext,\n)\nfrom mindspore.ops import composite as C\n\nfrom src.model.RRDB_Net import RRDBNet\nfrom src.model.discriminator_net import VGGStyleDiscriminator128\nfrom src.model.cell import GeneratorLossCell, DiscriminatorLossCell, TrainOneStepCellDis, TrainOneStepCellGen\nfrom src.config.config import ESRGAN_config\nfrom src.dataset.dataset_DIV2K import get_dataset_DIV2K\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(\"ESRGAN\")\n parser.add_argument('--device_target', type=str,\n default=\"Ascend\", help='Platform')\n parser.add_argument('--device_id', type=int,\n default=7, help='device_id')\n parser.add_argument(\n \"--aug\", type=bool, default=True, help=\"Use augement for dataset\"\n )\n parser.add_argument(\"--loss_scale\", type=float,\n default=1024.0, help=\"loss scale\")\n parser.add_argument('--data_dir', type=str,\n default=None, help='Dataset path')\n parser.add_argument(\"--batch_size\", type=int, default=16, help=\"batch_size\")\n parser.add_argument(\"--epoch_size\", type=int,\n default=20, help=\"epoch_size\")\n parser.add_argument('--Giters', type=int, default=2, help='number of G iters per each D iter')\n parser.add_argument(\"--rank\", type=int, default=1,\n help=\"local rank of distributed\")\n parser.add_argument(\n \"--group_size\", type=int, default=0, help=\"world size of distributed\"\n )\n parser.add_argument(\n \"--keep_checkpoint_max\", type=int, default=40, help=\"max checkpoint for saving\"\n )\n parser.add_argument(\n \"--model_save_step\", type=int, default=5000, help=\"step num for saving\"\n )\n parser.add_argument('--Gpretrained_path', type=str, default=\"psnr.ckpt\")\n parser.add_argument('--experiment', default=\"./images\", help='Where to store samples and models')\n parser.add_argument(\"--run_distribute\", type=ast.literal_eval,\n default=False, help=\"Run distribute, default: false.\")\n # Modelarts\n args, _ = parser.parse_known_args()\n return args\n\n\n# save image\ndef save_img(img, img_name,save_dir):\n save_img = C.clip_by_value(img.squeeze(), 0, 1).asnumpy().transpose(1, 2, 0)\n # save img\n save_fn = save_dir + '/' + img_name\n cv2.imwrite(save_fn, cv2.cvtColor(save_img * 255, cv2.COLOR_BGR2RGB), [cv2.IMWRITE_PNG_COMPRESSION, 0])\n\ndef train():\n args_opt = parse_args()\n config = ESRGAN_config\n context.set_context(mode=context.GRAPH_MODE,device_target=\"Ascend\", device_id=args_opt.device_id, save_graphs=False)\n # Device Environment\n if args_opt.run_distribute:\n if args_opt.device_target == \"Ascend\":\n rank = args_opt.device_id\n # device_num = device_num\n context.set_auto_parallel_context(device_num=device_num, parallel_mode=ParallelMode.DATA_PARALLEL,\n gradients_mean=True)\n init()\n else:\n init(\"nccl\")\n context.reset_auto_parallel_context()\n rank = get_rank()\n device_num = get_group_size()\n context.set_auto_parallel_context(device_num=device_num, parallel_mode=ParallelMode.DATA_PARALLEL,\n gradients_mean=True)\n else:\n rank = 0\n device_num = 1\n dataset, dataset_len = get_dataset_DIV2K(\n base_dir=\"./data/lw\", downsample_factor=config[\"down_factor\"], mode=\"train\", aug=args_opt.aug, repeat=10, batch_size=args_opt.batch_size,shard_id=args_opt.group_size,shard_num=args_opt.rank,num_readers=4)\n dataset_iter = dataset.create_dict_iterator()\n generator = RRDBNet(\n in_nc=config[\"ch_size\"],\n out_nc=config[\"ch_size\"],\n nf=config[\"G_nf\"],\n nb=config[\"G_nb\"],\n )\n discriminator = VGGStyleDiscriminator128(\n num_in_ch=config[\"ch_size\"], num_feat=config[\"D_nf\"])\n param_dict = load_checkpoint(args_opt.Gpretrained_path)\n load_param_into_net(generator, param_dict)\n # Define network with loss\n G_loss_cell = GeneratorLossCell(generator, discriminator,config[\"vgg_pretrain_path\"])\n D_loss_cell = DiscriminatorLossCell(discriminator)\n lr_G = nn.piecewise_constant_lr(\n milestone=config[\"lr_steps\"], learning_rates=config[\"lr_G\"]\n )\n lr_D = nn.piecewise_constant_lr(\n milestone=config[\"lr_steps\"], learning_rates=config[\"lr_D\"]\n )\n optimizerD = nn.Adam(discriminator.trainable_params(\n ), learning_rate=lr_D, beta1=0.5, beta2=0.999,loss_scale=args_opt.loss_scale)\n optimizerG = nn.Adam(generator.trainable_params(\n ), learning_rate=lr_G, beta1=0.5, beta2=0.999,loss_scale=args_opt.loss_scale)\n\n # Define One step train\n G_trainOneStep = TrainOneStepCellGen(G_loss_cell, optimizerG)\n D_trainOneStep = TrainOneStepCellDis(D_loss_cell, optimizerD)\n\n # Train\n G_trainOneStep.set_train()\n D_trainOneStep.set_train()\n\n print('Start Training')\n\n ckpt_config = CheckpointConfig(\n save_checkpoint_steps=args_opt.model_save_step,keep_checkpoint_max=args_opt.keep_checkpoint_max)\n ckpt_cb_g = ModelCheckpoint(\n config=ckpt_config, directory=\"./checkpoints\", prefix='Generator')\n ckpt_cb_d = ModelCheckpoint(\n config=ckpt_config, directory=\"./checkpoints\", prefix='Discriminator')\n\n cb_params_g = _InternalCallbackParam()\n cb_params_g.train_network = generator\n cb_params_g.cur_step_num = 0\n cb_params_g.batch_num = args_opt.batch_size\n cb_params_g.cur_epoch_num = 0\n cb_params_d = _InternalCallbackParam()\n cb_params_d.train_network = discriminator\n cb_params_d.cur_step_num = 0\n cb_params_d.batch_num = args_opt.batch_size\n cb_params_d.cur_epoch_num = 0\n run_context_g = RunContext(cb_params_g)\n run_context_d = RunContext(cb_params_d)\n ckpt_cb_g.begin(run_context_g)\n ckpt_cb_d.begin(run_context_d)\n start = time()\n minibatch = args_opt.batch_size\n ones = ops.Ones()\n zeros = ops.Zeros()\n real_labels = ones((minibatch, 1), mindspore.float32) \n fake_labels = zeros((minibatch, 1), mindspore.float32)+Tensor(np.random.random(size=(minibatch,1)),dtype=mindspore.float32)*0.05\n num_iters = config[\"niter\"]\n for iterator in range(num_iters):\n data = next(dataset_iter)\n inputs = data[\"inputs\"]\n real_hr = data[\"target\"]\n generator_loss_all = G_trainOneStep(inputs, real_hr, fake_labels, real_labels)\n fake_hr = generator_loss_all[0]\n generator_loss = generator_loss_all[1]\n if (iterator + 1) % args_opt.Giters == 0:\n discriminator_loss = D_trainOneStep(fake_hr,real_hr)\n if (iterator + 1) % 500 == 0:\n print('%d:[%d/%d]Loss_D: %10f Loss_G: %10f'\n % ((iterator+1)//dataset_len,iterator,num_iters,\n np.sum(discriminator_loss.asnumpy()), generator_loss.asnumpy()))\n save_img(real_hr[0], 'real_samples_{0}.png'.format(iterator + 1),args_opt.experiment)\n save_img(fake_hr[0], 'fake_samples_{0}.png'.format(iterator + 1),args_opt.experiment)\n \nif __name__ == \"__main__\":\n train()","repo_name":"Mind23-2/MindCode-40","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":7750,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"37838562784","text":"#q9\r\nclass Parentheses:\r\n def __init__(self, string):\r\n self.string = string\r\n \r\n def is_valid(self):\r\n stack = []\r\n for char in self.string:\r\n if char in [\"(\", \"{\", \"[\"]:\r\n stack.append(char)\r\n elif char in [\")\", \"}\", \"]\"]:\r\n if not stack:\r\n return False\r\n current_char = stack.pop()\r\n if char == \")\" and current_char != \"(\":\r\n return False\r\n elif char == \"}\" and current_char != \"{\":\r\n return False\r\n elif char == \"]\" and current_char != \"[\":\r\n return False\r\n return not stack\r\n\r\n# Test the class\r\nstring1 = \"()\"\r\nstring2 = \"()[]{}\"\r\nstring3 = \"[)\"\r\nstring4 = \"({[)]\"\r\nstring5 = \"{{{\"\r\n\r\np1 = Parentheses(string1)\r\np2 = Parentheses(string2)\r\np3 = Parentheses(string3)\r\np4 = Parentheses(string4)\r\np5 = Parentheses(string5)\r\n\r\nprint(p1.is_valid())\r\nprint(p2.is_valid())\r\nprint(p3.is_valid())\r\nprint(p4.is_valid())\r\nprint(p5.is_valid())","repo_name":"Rohan-trivedi-13/itc","sub_path":"as 6/as6q9.py","file_name":"as6q9.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"7110431940","text":"import logging\n\nfrom flask.views import MethodView\nfrom flask_jwt_extended import get_current_user, jwt_required\nfrom flask_smorest import Blueprint\n\nfrom ..helpers import get_sn_config, Table\n\nlogger = logging.getLogger(__name__)\n\nblp = Blueprint('ui_data', __name__, url_prefix='/ui-data')\n\n\n@blp.route('/incidents')\nclass IncidentUIData(MethodView):\n\n @jwt_required\n def get(self):\n current_user = get_current_user()\n # claims = get_request_claims()\n sn_config = get_sn_config(current_user)\n\n sys_choice = Table('sys_choice', sn_config=sn_config)\n query = (\n sys_choice.inactive.eq('false')\n & sys_choice.name.eq('incident')\n | sys_choice.name.eq('task')\n )\n\n resp = sys_choice.get_all(\n query=query,\n fields=[\n 'element',\n 'value',\n 'label',\n 'language',\n 'dependent_value'\n ],\n limit=1000\n )\n\n raw_items = resp.json().get('result')\n\n return {\n 'items': raw_items,\n 'num_items': len(raw_items),\n }\n","repo_name":"WonderCode22/servicenow_component","sub_path":"service_now_service/routes/ui_data.py","file_name":"ui_data.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"}
+{"seq_id":"30331518006","text":"import json\nimport time\nfrom riotwatcher import RiotWatcher\n\nfrom static import Static\nfrom history import MatchHistory\nfrom match import *\nfrom util import do_slowly\n\n# https://mushroom.teemo.gg/\n\nclass Spectator:\n\n def __init__(self, api_key, region, summoner):\n\n self.API_KEY = api_key\n self.region = region\n self.summoner = summoner\n self.data = {}\n self.processing = {}\n\n self.watcher = RiotWatcher(self.API_KEY)\n\n self.me = self.watcher.summoner.by_name(self.region, self.summoner)\n\n #tim = self.watcher.summoner.by_name(self.region, 'Timmaable')\n\n #res = self.watcher.spectator.by_summoner(self.region, tim['id'])\n #print(res)\n\n self.static = Static(region, self.watcher)\n\n def load(self):\n self.history = MatchHistory()\n self.history.build_history(self.region, self.me['accountId'], self.watcher)\n self.history.save()\n\n def f(self):\n h = MatchHistory(self.me['accountId'])\n h.load()\n count = 0\n\n print(len(h))\n\n other_players = {}\n\n candidates = []\n for match in h.items:\n if match not in candidates:\n candidates.append(match)\n\n print(len(candidates))\n\n for match in candidates:\n count += 1\n print(count)\n do_slowly('riot_api', initial_count=1)\n players = self.watcher.match.by_id(self.region, match['gameId']['participantIdentities'])\n for player in players:\n if player['player']['accountId'] != self.me['accountId']:\n if player['player']['summonerName'] in other_players:\n n, ref = other_players[player['player']['summonerName']]\n ref.append(match)\n other_players[player['player']['summonerName']] = n + 1, ref\n else:\n other_players[player['player']['summonerName']] = 1, [match]\n print([(player, other_players[player][0]) for player in other_players if other_players[player][0] > 1])\n\nspec = Spectator('RGAPI-0197ae7d-bca8-4bf1-8490-88480a80d571', 'euw1', 'Anzeige ist raus')\nspec.load()\n#for i in range(10000):\n# print(spec.do_slowly(max, range(i+1)))\n\n#print(spec.static.get_champs())\n","repo_name":"TheodorStraube/spectator","sub_path":"matches.py","file_name":"matches.py","file_ext":"py","file_size_in_byte":2309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"5454384465","text":"# x es divisible entre y? es decir de forma exacta (da 0)\n\n\ndef leap(y):\n\n if y % 4 == 0: # % para que me de 0, si me cumple esta se va a abajo\n\n if y % 100 == 0: #Aqui es divisible entre 100 y por lo tanto no es biciesto\n\n if y % 400 == 0:\n return True\n\n else:\n return False\n \n else:\n return True\n else:\n return False #La primera letra en mayuscula, no es biciesto\n\ndef num_dias_mes(m, y):\n if m in (1, 3, 5, 7, 8, 10, 12):\n return 31\n elif m == 2:\n if leap(y):\n return 29\n else:\n return 28\n else:\n return 30\n \ndef next_day(y, m, d):\n if m == 12 and d == num_dias_mes(m, y):\n return y + 1, 1, 1 # se regresa al primero de enero del año siguiente\n elif d == num_dias_mes(m, y):\n return y, m + 1, 1\n else: \n return y, m, d + 1\n \ndef main():\n print(leap(2015))\n print(leap(2016))\n print(leap(2000))\n print(leap(2100))\n print(next_day(2015, 2, 13))\n print(next_day(2015, 2, 28))\n print(next_day(2016, 2, 28))\n print(next_day(2016, 12, 31))\n\n \nmain() \n \n# Los caminos deben de llegar a un resultado cada if tiene que venir con un else\n ","repo_name":"CertifiedErickBaps/Python36","sub_path":"Condiconal If/leap year.py","file_name":"leap year.py","file_ext":"py","file_size_in_byte":1287,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"12581243567","text":"import math\n\ndef solution(fees, records):\n answer = []\n dic = {}\n fee_dic = {}\n numbers = []\n\n OUT_TIME = 23 * 60 + 59\n\n for record in records: # 0 = time, 1 = num , 2 = i/o\n\n keys = record.split()\n time = keys[0].split(\":\")\n time_m = int(time[0]) * 60 + int(time[1])\n if keys[1] in dic:\n dic[keys[1]].append(time_m)\n else :\n dic[keys[1]] = [time_m]\n fee_dic[keys[1]] = 0\n numbers.append(keys[1])\n [300, 350, 360 , out_time]\n\n\n for key in dic:\n sum_time = 0\n if len(dic[key]) % 2 == 1:\n dic[key].append(OUT_TIME)\n\n for i in range(1,len(dic[key]),2):\n sum_time += dic[key][i] - dic[key][i-1]\n if sum_time < fees[0]:\n fee_dic[key] = fees[1]\n else : \n fee_dic[key] = fees[1] + math.ceil((sum_time - fees[0]) / fees[2]) * fees[3] \n\n \n numbers.sort()\n for key in numbers:\n answer.append(int(fee_dic[key]))\n \n return answer\n","repo_name":"rieull0225/algorithm","sub_path":"kakao3.py","file_name":"kakao3.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"9622655221","text":"import gradio as gr\nimport torch\nimport torch.nn.functional as F\nfrom torchvision import datasets, transforms, models\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nmodel=torch.load('shufflenetmodel.pth')\nmodel.eval()\n\nimport dataloader as dtl\ndata_dir = \"data/train\"\ntrainloader, testloader = dtl.load_split_train_test(data_dir, .2)\n\ndef inference(input_image):\n preprocess = transforms.Compose([\n transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),\n ])\n input_tensor = preprocess(input_image)\n # create a mini-batch as expected by the model\n input_batch = input_tensor.unsqueeze(0)\n # move the input and model to GPU for speed if available\n if torch.cuda.is_available():\n input_batch = input_batch.to('cuda')\n model.to('cuda')\n with torch.no_grad():\n output = model(input_batch)\n # The output has unnormalized scores. To get probabilities, we will run a softmax on it.\n probabilities = torch.nn.functional.softmax(output[0], dim=0)\n # Show top categories per image\n categories = trainloader.dataset.classes\n top3_prob, top3_catid = torch.topk(probabilities, 3)\n result = {}\n for i in range(top3_prob.size(0)):\n result[categories[top3_catid[i]]] = top3_prob[i].item()\n return result\n\n# Variables for gradio interface\ninputs = gr.inputs.Image(type='pil')\noutputs = gr.outputs.Label(type=\"confidences\",num_top_classes=3)\ntitle = \"SHUFFLENET\"\ndescription = \"Please upload your headphones, coffee or reiven image.\"\n","repo_name":"rutkaite/dl-assignments","sub_path":"inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":1643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"3135575048","text":"import math\r\n\r\nprint(\"Program Menghitung Luas dan Volume Limas Segitiga\")\r\n\r\n#Programmer : Nur Iskandar S\r\n#NIM : 220511009\r\n#Pertemuan : 1\r\n#Tanggal : 22 Oktober 2023\r\n\r\n#input nilai\r\nalas = float(input(\"Masukkan panjang sisi alas limas segitiga: \"))\r\ntinggi = float(input(\"Masukkan tinggi limas segitiga: \"))\r\nsisi_tegak = float(input(\"Masukkan panjang sisi tegak limas segitiga: \"))\r\n\r\n#rumus\r\nluas_alas = 0.5 * alas * tinggi\r\nluas_tegak = 3 * (alas * sisi_tegak) / 2\r\nluas = luas_alas + luas_tegak\r\nvolume = (luas_alas * tinggi) / 3\r\n\r\n#output\r\nprint(f\"Luas: {luas}\")\r\nprint(f\"Volume: {volume}\")\r\n","repo_name":"nuriskandarsyah/Tugas-Python","sub_path":"python/5. limas segitiga.py","file_name":"5. limas segitiga.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"39147274769","text":"'''\nQuestion :\nYou have been given a dictionary of movie(key) and cat(value)\ncollection = {\"The Last samurai\":\"Tom Cruise, Ken\", \"Justice League\":\"Cavil, Gadot\", \"MI\":\"Tom Cruise\"}\nPrint a list of movies, where cruise is not a part of cast.\nOutput:\n['Justice League']\n'''\ncollection = {\"The Last samurai\":\"Tom Cruise, Ken\", \"Justice League\":\"Cavil, Gadot\", \"MI\":\"Tom Cruise\"}\n\nres = [movie for movie in collection.keys() if('Cruise' not in collection[movie])]\nprint(res)\n","repo_name":"rajatmishra3108/Daily-Flash-PYTHON","sub_path":"20 aug 2020/prog5.py","file_name":"prog5.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"}
+{"seq_id":"20885488772","text":"## Thermal FPS Test\n\nimport cv2\nimport sys\nimport time\nimport numpy\nimport math\nfrom PIL import Image, ImageOps\nfrom tinkerforge.ip_connection import IPConnection\nfrom tinkerforge.bricklet_thermal_imaging import BrickletThermalImaging\n\n\n#Tinkerforge Config\nHOST = \"localhost\"\nPORT = 4223\nUID = \"LcN\"\n\n\nprint(\"start Connection\")\nipcon = IPConnection() # Create IP connection\nti = BrickletThermalImaging(UID, ipcon) # Create device object\nipcon.connect(HOST, PORT) # Connect to brickd\nwhile ipcon.get_connection_state() == 2 :\n print(\".\")\nprint(ipcon.get_connection_state())\n\ndef get_thermal_image_color_palette():\n palette = []\n\n for x in range(256):\n x /= 255.0\n palette.append(int(round(255*math.sqrt(x)))) # RED\n palette.append(int(round(255*pow(x, 3)))) # GREEN\n if math.sin(2 * math.pi * x) >= 0:\n palette.append(int(round(255*math.sin(2 * math.pi * x)))) # BLUE\n else:\n palette.append(0)\n\n return palette\n\n\nfps = 0\ncount = 0\n\n\nti.set_image_transfer_config(ti.IMAGE_TRANSFER_MANUAL_HIGH_CONTRAST_IMAGE)\ntime.sleep(0.5)\n\n\nstart = time.time()\nwhile True:\n\n #request termalimage\n image_data = ti.get_high_contrast_image()\n \n # Display Thermal Image\n image = Image.new('P', (80, 60))\n image.putdata(image_data)\n image.putpalette(get_thermal_image_color_palette())\n #print(numpy.array(image))\n image = image.resize((80*8, 60*8), Image.ANTIALIAS)\n image = ImageOps.flip(image)\n img = numpy.array(image.convert('RGB'))\n img = img[:, :, ::-1].copy()\n \n \n ### FPS\n end = time.time()\n if (end - start > 2):\n fps = int(count / 2)\n start = time.time()\n count = 0\n print(fps)\n else:\n count += 1\n cv2.putText(img, f'FPS: {int(fps)}', (10, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0))\n \n #Show Image\n cv2.imshow('ThermalVideo', img)\n \n \n if cv2.waitKey(10) & 0xFF == ord('q'):\n break\n\ncv2.destroyAllWindows()\nipcon.disconnect()\n","repo_name":"OliverGorges/Federated-learning-on-edge-devices","sub_path":"ThermalFPSTest.py","file_name":"ThermalFPSTest.py","file_ext":"py","file_size_in_byte":2044,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"}
+{"seq_id":"41118549898","text":"from renamer import ReNamer\n\n#\n# DEMO\n#\n# Let ReNamer know which directory to alter\n# If no path is provided, will assume current directory\n#\n# Use show_dir() to preview filenames\n#\n# ReNamer will display proposed changes and ask for confirmation\n# before altering any files, for safety.\n#\n# TO DO\n# - Methods should return reference to self to allow chaining alterations\n# e.g. my_folder.replace(\"this\", \"that\").add_prefix(\"pre\")\n# - Add remove() method for easy removing occurences of a string (replace with \"\")\n# e.g. my_folder.remove(\"delete\") > my_folder.replace(\"delete\", \"\")\n# - Reversal method for undoing previous change(s)\n\nif __name__ == \"__main__\":\n path = \"./renamer_test_images/\"\n my_folder = ReNamer(path)\n\n my_folder.show_dir()\n\n my_folder.replace(\"grab\", \"shot\")\n #my_folder.replace(\"shot\", \"grab\")\n #my_folder.add_prefix(\"screen_\")\n #my_folder.add_suffix(\"-test\")\n\n my_folder.show_dir()\n","repo_name":"TurbulentRice/file_renamer","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"23679406159","text":"#task4\ninp_file = open(\"/content/drive/MyDrive/cse221/lab1/input4.txt\", mode = \"r\")\ndata = inp_file.readlines()\noutFile = open(\"/content/drive/MyDrive/cse221/lab1/output4.txt\", mode = \"w\")\nid = data[1].split()\nmarks = data[2].split()\nfor i in range(int(data[0])):\n high = i\n for j in range(i+1,len(marks)):\n if marks[high] < marks[j]:\n high = j\n elif marks[high] == marks[j]:\n if id[j] < id[i]:\n high = j\n marks[i],marks[high] = marks[high],marks[i]\n id[i],id[high]=id[high],id[i]\n print('ID:',id[i],'Mark:',marks[i], file = outFile)\ninp_file.close()\noutFile.close()","repo_name":"sigh8/CSE-221","sub_path":"lab1/task4.py","file_name":"task4.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"71427362007","text":"from django.contrib import admin\nfrom .models import Msgbox, SaveMsgbox, Alarm_Addcommentlike\n\n\nclass Alarm_AddcommentlikeAdmin(admin.ModelAdmin):\n list_display = ('id', 'likefrom', 'comment_user', 'act_type', 'content_id', 'comment_id', 'comment_table', 'checkitout','is_published', 'upload_date')\n list_display_links = ('id', 'likefrom', 'comment_user', 'comment_table', 'content_id', 'checkitout')\n list_editable = ('is_published',)\n list_per_page = 20\n\nclass MsgboxAdmin(admin.ModelAdmin):\n list_display = ('id', 'chat_id', 'send_user', 'from_user', 'is_checked', 'is_active', 'upload_date')\n list_display_links = ('id', 'chat_id')\n search_fields = ('id','chat_id','send_user__username','from_user__username')\n list_editable = ('is_active',)\n list_per_page = 20\n\nclass SaveMsgboxAdmin(admin.ModelAdmin):\n list_display = ('id', 'user', 'msgbox', 'is_published', 'upload_date')\n list_display_links = ('id', 'user', 'msgbox')\n search_fields = ('id','user__username', 'msgbox__send_user__username')\n list_editable = ('is_published',)\n list_per_page = 20\n\nadmin.site.register(Alarm_Addcommentlike, Alarm_AddcommentlikeAdmin)\nadmin.site.register(Msgbox, MsgboxAdmin)\nadmin.site.register(SaveMsgbox, SaveMsgboxAdmin)\n","repo_name":"ehdrn3020/edit_80_template","sub_path":"04_wego/wego/msgboxs/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1256,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"36684854241","text":"# Find the Power of a Number.\r\nimport math\r\n\r\nnum, power = map(int,input().split(\" \"))\r\n\r\n# using math library functions\r\nprint(int(math.pow(num, power)))\r\n\r\n# using loop\r\nans = 1\r\nfor i in range(1, power + 1):\r\n ans *= num\r\nprint(ans)","repo_name":"Gopal7476/Python-Programming","sub_path":"Getting Started/17.FindThePowerOfANumber.py","file_name":"17.FindThePowerOfANumber.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"35036930476","text":"import pygame\n\nfrom collisions import *\n\nfrom ball import Ball\nfrom cue import Cue\nfrom image_loader import BALL_IMAGE, BALL_RED_IMAGE, BALL_YELLOW_IMAGE\nfrom table import Table\n\nfrom constants import HEIGHT, WIDTH, FPS, RED_BALL_PLACEMENT, YELLOW_BALL_PLACEMENT\n\nclass Game:\n\n def __init__(self) -> None:\n pygame.init()\n pygame.mixer.init()\n\n\n self.debug = False\n\n self.screen = pygame.display.set_mode((WIDTH, HEIGHT))\n\n pygame.display.set_caption(\"Pool\")\n\n self.clock = pygame.time.Clock()\n\n self.table = Table()\n\n self.sprites = pygame.sprite.Group()\n\n self.player_ball = Ball(BALL_IMAGE)\n \n self.balls = [\n self.player_ball,\n ]\n\n \n self.sprites.add(self.table)\n self.sprites.add(self.player_ball)\n\n\n for b in RED_BALL_PLACEMENT:\n ball = Ball(BALL_RED_IMAGE)\n\n ball.set_position(b[0], b[1])\n\n self.balls.append(ball)\n self.sprites.add(ball)\n \n for b in YELLOW_BALL_PLACEMENT:\n ball = Ball(BALL_YELLOW_IMAGE)\n\n ball.set_position(b[0], b[1])\n\n self.balls.append(ball)\n self.sprites.add(ball)\n \n\n self.cue = Cue(self.player_ball)\n\n self.player_ball.set_position(WIDTH // 4, HEIGHT // 2)\n\n\n self.running = False\n\n\n def run(self):\n running = True\n\n while running:\n delta_time = self.clock.tick(FPS)\n\n for event in pygame.event.get():\n\n if event.type == pygame.QUIT:\n running = False\n\n elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:\n #self.cue.trigger_mouse(Vec2.to_vec2(event.pos))\n self.cue.start_mouse_hold()\n\n elif event.type == pygame.MOUSEBUTTONUP and event.button == 1:\n self.cue.stop_mouse_hold()\n\n\n for ball in self.balls:\n if ball.potted:\n if ball == self.player_ball:\n ball.set_position(WIDTH // 4, HEIGHT // 2)\n ball.potted = False\n ball.velocity.set(0, 0)\n continue\n self.balls.remove(ball)\n self.sprites.remove(ball)\n\n self.sprites.update()\n\n\n ##############\n check_ball_collisions(self.balls)\n check_table_collisions(self.balls)\n check_holes_collision(self.balls)\n ##############\n\n\n\n\n self.sprites.draw(self.screen)\n\n if not any(map(lambda x:x.moving, self.balls)):\n self.cue.update()\n self.screen.blit(self.cue.image, self.cue.rect)\n\n\n if self.debug:\n holes = [\n Vec2(TABLE_OFFSET + 10, TABLE_OFFSET + 10),\n Vec2(TABLE_OFFSET + 10, HEIGHT - TABLE_OFFSET - 10),\n Vec2(WIDTH - TABLE_OFFSET - 10, TABLE_OFFSET + 10),\n Vec2(WIDTH - TABLE_OFFSET - 10, HEIGHT - TABLE_OFFSET - 10),\n Vec2(WIDTH // 2, TABLE_OFFSET - 10),\n Vec2(WIDTH // 2, HEIGHT - TABLE_OFFSET + 10),\n ]\n for hole in holes:\n pygame.draw.circle(self.screen, (0, 255, 0), hole.values(), 30)\n \n\n pygame.display.flip()\n\n \n pygame.quit()","repo_name":"Badis-Bfifteen/python-pool-game","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":3462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"28461435471","text":"\"\"\"dummy_test - Dummy test package for testing purposes\n\nThis package is super small and light used for pip testing purposes\n\n\"\"\"\n\nclassifiers = \"\"\"\\\nDevelopment Status :: 5 - Production/Stable\nEnvironment :: Console\nIntended Audience :: Developers\nLicense :: OSI Approved :: MIT License\nOperating System :: OS Independent\nProgramming Language :: Python :: 2\nTopic :: Software Development :: Quality Assurance\nTopic :: Software Development :: Testing\n\"\"\".splitlines()\n\nfrom setuptools import setup\n\ndoc = __doc__.splitlines()\n\nsetup(\n name=\"dummy_test\",\n version=\"0.1.3\",\n packages=['dummy_test'],\n zip_safe=False,\n author='Kien Pham',\n author_email='kien@sendgrid.com',\n url=\"https://github.com/kienpham2000/dummy_test\",\n license='MIT',\n description=doc[0],\n long_description='\\n'.join(doc[2:]),\n keywords='dummy test',\n classifiers=classifiers\n)","repo_name":"kpx-dev/dummy_test","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"38787707936","text":"import os\nimport subprocess\nfrom prompt_toolkit.styles import Style\nfrom pathlib import Path\nfrom socket import gethostname\nimport getpass\nimport shutil\nfrom datetime import datetime\n\nstyle = Style.from_dict({\n 'parantheses1': '#FFFFFF bold',\n 'username': '#FF0000 bold',\n 'parantheses2': '#FFFFFF bold',\n 'parantheses3': '#FFFFFF bold',\n 'hostname': '#00FF00 bold',\n 'pipe': '#FFFFFF bold',\n 'date-time': '#0FFFFF bold',\n 'parantheses4': '#FFFFFF bold',\n 'parantheses5': '#FFFFFF bold',\n 'git-branch': '#0000FF bold',\n 'star' : '#FFFF00 bold',\n 'parantheses6': '#FFFFFF bold',\n 'end': \"#FFFF00 bold\"\n})\n\nHOME_DIR = str(Path.home())\nhostname = str(gethostname())\nhistory = Path(HOME_DIR + \"/.yash_history\")\n\nx = subprocess.getoutput(\"git rev-parse --is-inside-work-tree\")\n\nrightNow = datetime.now()\nnow = rightNow.strftime(\"%d/%m/%Y %H:%M:%S\")\n\npart1=\"\"\npart2=\"\"\npart3=\"\"\npart4=\"\"\npart5=\"\"\npart6=\"\"\npart7=\"\"\npart8=\"\"\npart9=\"\"\npart10=\"\"\npart11=\"\"\npart12=\"\"\npart13=\"\"\n\nif str(x) == \"true\":\n changed_files = subprocess.getoutput(\"git ls-files -m\")\n added_files = subprocess.getoutput(\"git diff --name-only --cached\")\n current_branch = subprocess.getoutput(\"git branch --show-current\")\n noOfColumns = shutil.get_terminal_size()[0]\n if len(changed_files) != 0 or len(added_files) != 0:\n part1 = \"(\" \n part2 = str(getpass.getuser()) + \"@\" + str(os.path.basename(os.getcwd()))\n part3 = \")\"\n part5 = hostname\n part6 =\" | \"\n part7 = now\n part8 = \")\" + \"\\n\"\n new_str = part1 + part2 + part3 + part5 + part6 + part7 + part8\n width = noOfColumns - len(new_str) -1\n part4 = \"(\".rjust(width, \"-\")\n part9 = \"(\"\n part10 = current_branch + \" \"\n part11 = \"*\"\n part12 = \")\"\n part13 = \"$ \"\n else: \n part1 = \"(\" \n part2 = str(getpass.getuser()) + \"@\" + str(os.path.basename(os.getcwd()))\n part3 = \")\"\n part5 = hostname\n part6 =\" | \"\n part7 = now\n part8 = \")\" + \"\\n\"\n new_str = part1 + part2 + part3 + part5 + part6 + part7 + part8\n width = noOfColumns - len(new_str) -1\n part4 = \"(\".rjust(width, \"-\")\n part9 = \"(\"\n part10 = current_branch + \" \"\n part11 = \"✔\"\n part12 = \")\"\n part13 = \"$ \" \nelse: \n noOfColumns = shutil.get_terminal_size()[0]\n part1 = \"(\" \n part2 = str(getpass.getuser()) + \"@\" + str(os.path.basename(os.getcwd()))\n part3 = \")\"\n part5 = hostname\n part6 =\" | \"\n part7 = now\n part8 = \")\" + \"\\n\"\n new_str = part1 + part2 + part3 + part5 + part6 + part7 + part8\n width = noOfColumns - len(new_str) -1\n part4 = \"(\".rjust(width, \"-\")\n part13 = \"$ \"\n\ninput_required = [\n ('class:parantheses1', part1),\n ('class:username', part2),\n ('class:parantheses2', part3),\n ('class:parantheses3', part4),\n ('class:hostname', part5),\n ('class:pipe', part6),\n ('class:date-time', part7),\n ('class:parantheses4', part8),\n ('class:parantheses5', part9),\n ('class:git-branch', part10),\n ('class:star', part11),\n ('class:parantheses6', part12),\n ('class:end', part13)\n]\n\n","repo_name":"NeoDrags/neosh","sub_path":"neosh/themes/neoTheme.py","file_name":"neoTheme.py","file_ext":"py","file_size_in_byte":3211,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"31"}
+{"seq_id":"35672577564","text":"import cv2 \nimport time, sys, os\nfrom ros import rosbag\nimport roslib\nimport rospy\nroslib.load_manifest('sensor_msgs')\nfrom sensor_msgs.msg import Image,Imu\nfrom geometry_msgs.msg import Vector3\nfrom cv_bridge import CvBridge\nfrom numpy import asarray\n\n# import ImageFile\nfrom PIL import ImageFile\nfrom PIL import Image as ImagePIL\n\ndef CompSortFileNamesNr(f):\n g = os.path.splitext(os.path.split(f)[1])[0] #get the file of the\n numbertext = ''.join(c for c in g if c.isdigit())\n return int(numbertext)\n\ndef ReadIMU(IMUFile):\n '''return IMU data and timestamp of IMU'''\n IMUfp = open(IMUFile,'r')\n IMULines = IMUfp.readlines()\n #all = IMUDatas.readlines()\n IMUDatas = {}\n for l in IMULines:\n if l[0] == \"#\":\n continue;\n items = l.rstrip('\\n').split(' ')\n IMUDatas[items[0]] = items[1:]\n \n IMUfp.close()\n return IMUDatas \n\ndef ReadImages(assocoations):\n assofp = open(assocoations, 'r')\n asso = assofp.readlines()\n RGBImages = {}\n depthImages = {}\n for l in asso:\n if l[0] == \"#\":\n continue;\n items = l.rstrip('\\n').split(' ')\n RGBImages[items[0]] = items[1]\n depthImages[items[2]] = items[3]\n\n assofp.close()\n return RGBImages, depthImages\n\ndef CreateBag(args):#assocoations, imu, output_bag_name\n '''read assocoations.txt'''\n RGBImages,depthImages = ReadImages(args[1])\n\n IMUDatas = ReadIMU(args[2]) #the url of IMU data\n\n '''Creates a bag file with camera images'''\n if not os.path.exists(args[3]):\n os.system(r'touch %s' % args[3])\n else:\n os.system(r'rm %s' % args[3])\n os.system(r'touch %s' % args[3])\n\n bagName = rosbag.Bag(args[3], 'w')\n\n try:\n for it, iData in IMUDatas.items():\n imu = Imu()\n imuStamp = rospy.rostime.Time.from_sec(float(it))\n #angular_v = Vector3()\n linear_a = Vector3()\n #angular_v.x = float(iData[0])\n #angular_v.y = float(iData[1])\n #angular_v.z = float(iData[2])\n linear_a.x = float(iData[0])\n linear_a.y = float(iData[1])\n linear_a.z = float(iData[2])\n imu.header.stamp = imuStamp\n #imu.angular_velocity = angular_v\n imu.linear_acceleration = linear_a\n\n bagName.write(\"/imu\",imu,imuStamp)\n\n br = CvBridge()\n\n for imt, img in RGBImages.items():\n #img = args[2] + img; \n print(\"Adding %s\" % img)\n\n cv_image = cv2.imread(img)\n\n Stamp = rospy.rostime.Time.from_sec(float(imt))\n\n '''set image information '''\n Img = br.cv2_to_imgmsg(cv_image)\n Img.header.stamp = Stamp\n Img.header.frame_id = \"camera\"\n\n '''for mono8'''\n Img.encoding = \"rgb8\"\n bagName.write('/camera/rgb/image_color', Img, Stamp)\n\n for dt, dimg in depthImages.items():\n #dimg = args[2] + dimg; \n print(\"Adding %s\" % dimg)\n\n cv_image = cv2.imread(dimg, cv2.IMREAD_ANYDEPTH)\n\n '''set image information '''\n Stamp = rospy.rostime.Time.from_sec(float(dt))\n\n '''set image information '''\n dImg = br.cv2_to_imgmsg(cv_image)\n dImg.header.stamp = Stamp\n dImg.header.frame_id = \"camera\"\n\n #dImg.encoding = \"32FC1\"\n\n bagName.write('/camera/depth/image', dImg, Stamp)\n\n finally:\n bagName.close()\n\nif __name__ == \"__main__\":\n print(sys.argv)\n\n if len(sys.argv) < 4:\n print(\"Usage:\\n\\t python generate_bags.py /path/assocoations.txt /path/accelerometer.txt output.bag\")\n exit(1)\n\n CreateBag(sys.argv)\n\n","repo_name":"haohaoalt/hao_datasets","sub_path":"tum2bag/generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":3696,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"}
+{"seq_id":"71230042329","text":"from tkinter import *\nimport tkinter.ttk as ttk\nfrom tkinter.constants import *\nfrom tkinter import messagebox\nalphabetRUS=set('АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя')\nalphabetENG=set('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz')\ndef match(text,alphabet):\n for c in text:\n if c in alphabet:\n return True\n return False\ndef keyF(key):\n for char in key: # copies and iterates passing a value to char everytime\n key = key[1:] # deletes the first character in the string x\n if char in key: # checks if there is char in x string\n return False\n return True\ndef playfair():\n\n def polybiusE():\n openSTR = openText.get(1.0, END)\n openSTR = openSTR[:-1]\n key = keyPolybius.get()\n language = TCombobox1.get()\n if language == \"Русский\":\n if match(openSTR,alphabetENG):\n messagebox.showerror('Ошибка', 'Неверный алфавит.')\n else:\n if not key.isalpha() or match(key,alphabetENG) or not keyF(key):\n messagebox.showerror('Ошибка', 'Неверный ключ.')\n else:\n if not 1:\n messagebox.showerror('Ошибка', 'Неверный сдвиг.')\n else:\n rusB = \"АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯÈÉÊ\" # Алфавит\n key = key.upper() # Кодовое слово\n rusBtemp = rusB\n for i in range(len(key)):\n rusBtemp = rusBtemp.replace(key[i], '')\n sq = key + rusBtemp\n sqP = [[0 for i in range(6)] for j in range(6)]\n for i in range(6):\n for j in range(6):\n sqP[i][j] = sq[6 * i + j]\n print(sqP)\n openText1 = openSTR # Открытый текст\n cipherSTR = \"\"\n simvol = [[], []]\n slow = []\n\n for k in range(len(openText1)):\n if not openText1[k].isalpha():\n simvol[0].append(openText1[k])\n simvol[1].append(k)\n\n for k in openText1:\n if not k.isalpha():\n openText1 = openText1.replace(k, '')\n for k in range(len(openText1)):\n if openText1[k].islower():\n slow.append(k)\n openText2 = openText1.upper()\n\n for i in range(0, len(openText2), 2):\n if i == len(openText2) - 1:\n break\n if openText2[i] == openText2[i + 1]:\n if openText2[i] == \"Х\":\n openText2 = openText2[:i + 1] + \"Ф\" + openText2[i + 1:]\n else:\n openText2 = openText2[:i + 1] + \"Х\" + openText2[i + 1:]\n\n for u in range(len(simvol[1])):\n if i + 1 < simvol[1][u]:\n simvol[1][u] += 1\n\n for u in range(len(slow)):\n if i + 1 <= slow[u]:\n slow[u] += 1\n\n if len(openText2) % 2 != 0:\n openText2 = openText2 + \"Х\"\n print(openText2)\n for k in range(0, len(openText2)-1, 2):\n l = [0, 0, 0, 0]\n for i in range(6):\n for j in range(6):\n if openText2[k] == sqP[i][j]:\n l[0] = i\n l[1] = j\n if openText2[k + 1] == sqP[i][j]:\n l[2] = i\n l[3] = j\n if l[1] == l[3]:\n cipherSTR = cipherSTR + sqP[(l[0] + 1) % 6][l[1]] + sqP[(l[2] + 1) % 6][l[3]]\n print(cipherSTR)\n elif l[0] == l[2]:\n cipherSTR = cipherSTR + sqP[l[0]][(l[1] + 1) % 6] + sqP[l[2]][(l[3] + 1) % 6]\n print(cipherSTR)\n else:\n cipherSTR = cipherSTR + sqP[l[0]][l[3]] + sqP[l[2]][l[1]]\n print(cipherSTR)\n\n for i in slow:\n cipherSTR = cipherSTR[:i] + cipherSTR[i].lower() + cipherSTR[i + 1:]\n print(cipherSTR)\n for i in range(len(simvol[0])):\n cipherSTR = cipherSTR[:int(simvol[1][i])] + simvol[0][i] + cipherSTR[int(simvol[1][i]):]\n\n cipherText.delete(1.0, END)\n cipherText.insert(1.0, cipherSTR)\n if language == \"Английский\":\n if match(openSTR, alphabetRUS):\n messagebox.showerror('Ошибка', 'Неверный алфавит.')\n else:\n if not key.isalpha() or match(key, alphabetRUS) or not keyF(key):\n messagebox.showerror('Ошибка', 'Неверный ключ.')\n else:\n if not 1:\n messagebox.showerror('Ошибка', 'Неверный сдвиг.')\n else:\n engB = \"ABCDEFGHIKLMNOPQRSTUVWXYZ\" # Алфавит\n # Кодовое слово\n key = key.upper()\n engBtemp = engB\n for i in range(len(key)):\n engBtemp = engBtemp.replace(key[i], '')\n sq = key + engBtemp\n sqP = [[0 for i in range(5)] for j in range(5)]\n for i in range(5):\n for j in range(5):\n sqP[i][j] = sq[5 * i + j]\n\n # Зашифрование\n openText1 = openSTR # Открытый текст\n cipherSTR = \"\"\n iStr = \"\"\n jStr = \"\"\n simvol = [[], []]\n slow = []\n\n for k in range(len(openText1)):\n if not openText1[k].isalpha():\n simvol[0].append(openText1[k])\n simvol[1].append(k)\n\n for k in openText1:\n if not k.isalpha():\n openText1 = openText1.replace(k, '')\n for k in range(len(openText1)):\n if openText1[k].islower():\n slow.append(k)\n openText2 = openText1.upper()\n openText2 = openText2.replace('J', 'I')\n\n for i in range(0, len(openText2), 2):\n if i == len(openText2) - 1:\n break\n if openText2[i] == openText2[i + 1]:\n if openText2[i] == \"X\":\n openText2 = openText2[:i + 1] + \"Q\" + openText2[i + 1:]\n else:\n openText2 = openText2[:i + 1] + \"X\" + openText2[i + 1:]\n\n for u in range(len(simvol[1])):\n if i + 1 < simvol[1][u]:\n simvol[1][u] += 1\n\n for u in range(len(slow)):\n if i + 1 <= slow[u]:\n slow[u] += 1\n\n if len(openText2) % 2 != 0:\n openText2 = openText2 + \"X\"\n\n for k in range(0, len(openText2), 2):\n l = [0, 0, 0, 0]\n for i in range(5):\n for j in range(5):\n if openText2[k] == sqP[i][j]:\n l[0] = i\n l[1] = j\n if openText2[k + 1] == sqP[i][j]:\n l[2] = i\n l[3] = j\n if l[1] == l[3]:\n cipherSTR = cipherSTR + sqP[(l[0] + 1) % 5][l[1]] + sqP[(l[2] + 1) % 5][l[3]]\n if l[0] == l[2]:\n cipherSTR = cipherSTR + sqP[l[0]][(l[1] + 1) % 5] + sqP[l[2]][(l[3] + 1) % 5]\n else:\n cipherSTR = cipherSTR + sqP[l[0]][l[3]] + sqP[l[2]][l[1]]\n\n for i in slow:\n cipherSTR = cipherSTR[:i] + cipherSTR[i].lower() + cipherSTR[i + 1:]\n for i in range(len(simvol[0])):\n cipherSTR = cipherSTR[:int(simvol[1][i])] + simvol[0][i] + cipherSTR[int(simvol[1][i]):]\n\n\n cipherText.delete(1.0, END)\n cipherText.insert(1.0, cipherSTR)\n\n\n def polybiusD():\n cipherT = cipherText.get(1.0, END)\n cipherT = cipherT[:-1]\n key = keyPolybius.get()\n language = TCombobox1.get()\n if language == \"Русский\":\n if match(cipherT, alphabetENG):\n messagebox.showerror('Ошибка', 'Неверный алфавит.')\n else:\n if not key.isalpha() or match(key, alphabetENG) or not keyF(key):\n messagebox.showerror('Ошибка', 'Неверный ключ.')\n else:\n if not 1:\n messagebox.showerror('Ошибка', 'Неверный сдвиг.')\n else:\n rusB = \"АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯÈÉÊ\" # Алфавит\n key = key.upper() # Кодовое слово\n rusBtemp = rusB\n for i in range(len(key)):\n rusBtemp = rusBtemp.replace(key[i], '')\n sq = key + rusBtemp\n sqP = [[0 for i in range(6)] for j in range(6)]\n for i in range(6):\n for j in range(6):\n sqP[i][j] = sq[6 * i + j]\n\n openText1 = cipherT # Открытый текст\n cipherSTR = \"\"\n simvol = [[], []]\n slow = []\n\n for k in range(len(openText1)):\n if not openText1[k].isalpha():\n simvol[0].append(openText1[k])\n simvol[1].append(k)\n\n for k in openText1:\n if not k.isalpha():\n openText1 = openText1.replace(k, '')\n for k in range(len(openText1)):\n if openText1[k].islower():\n slow.append(k)\n openText2 = openText1.upper()\n\n for k in range(0, len(openText2)-1, 2):\n l = [0, 0, 0, 0]\n for i in range(6):\n for j in range(6):\n if openText2[k] == sqP[i][j]:\n l[0] = i\n l[1] = j\n if openText2[k + 1] == sqP[i][j]:\n l[2] = i\n l[3] = j\n if l[1] == l[3]:\n cipherSTR = cipherSTR + sqP[(l[0] - 1) % 6][l[1]] + sqP[(l[2] - 1) % 6][l[3]]\n elif l[0] == l[2]:\n cipherSTR = cipherSTR + sqP[l[0]][(l[1] - 1) % 6] + sqP[l[2]][(l[3] - 1) % 6]\n else:\n cipherSTR = cipherSTR + sqP[l[0]][l[3]] + sqP[l[2]][l[1]]\n\n for i in slow:\n cipherSTR = cipherSTR[:i] + cipherSTR[i].lower() + cipherSTR[i + 1:]\n for i in range(len(simvol[0])):\n cipherSTR = cipherSTR[:int(simvol[1][i])] + simvol[0][i] + cipherSTR[int(simvol[1][i]):]\n\n print(cipherSTR)\n cipherSTR = cipherSTR.replace(\"Х\", '')\n print(cipherSTR)\n openText.delete(1.0, END)\n openText.insert(1.0, cipherSTR)\n if language == \"Английский\":\n if match(cipherT, alphabetRUS):\n messagebox.showerror('Ошибка', 'Неверный алфавит.')\n else:\n if not key.isalpha() or match(key, alphabetRUS) or not keyF(key):\n messagebox.showerror('Ошибка', 'Неверный ключ.')\n else:\n if not 1:\n messagebox.showerror('Ошибка', 'Неверный сдвиг.')\n else:\n engB = \"ABCDEFGHIKLMNOPQRSTUVWXYZ\" # Алфавит\n # Кодовое слово\n key = key.upper()\n engBtemp = engB\n for i in range(len(key)):\n engBtemp = engBtemp.replace(key[i], '')\n sq = key + engBtemp\n sqP = [[0 for i in range(5)] for j in range(5)]\n for i in range(5):\n for j in range(5):\n sqP[i][j] = sq[5 * i + j]\n\n # Расшифрование\n\n openText1 = cipherT # Открытый текст\n cipherSTR = \"\"\n simvol = [[], []]\n slow = []\n\n for k in range(len(openText1)):\n if not openText1[k].isalpha():\n simvol[0].append(openText1[k])\n simvol[1].append(k)\n\n for k in openText1:\n if not k.isalpha():\n openText1 = openText1.replace(k, '')\n for k in range(len(openText1)):\n if openText1[k].islower():\n slow.append(k)\n openText2 = openText1.upper()\n\n for k in range(0, len(openText2), 2):\n l = [0, 0, 0, 0]\n for i in range(5):\n for j in range(5):\n if openText2[k] == sqP[i][j]:\n l[0] = i\n l[1] = j\n if openText2[k + 1] == sqP[i][j]:\n l[2] = i\n l[3] = j\n if l[1] == l[3]:\n cipherSTR = cipherSTR + sqP[(l[0] - 1) % 5][l[1]] + sqP[(l[2] - 1) % 5][l[3]]\n if l[0] == l[2]:\n cipherSTR = cipherSTR + sqP[l[0]][(l[1] - 1) % 5] + sqP[l[2]][(l[3] - 1) % 5]\n else:\n cipherSTR = cipherSTR + sqP[l[0]][l[3]] + sqP[l[2]][l[1]]\n\n for i in slow:\n cipherSTR = cipherSTR[:i] + cipherSTR[i].lower() + cipherSTR[i + 1:]\n for i in range(len(simvol[0])):\n cipherSTR = cipherSTR[:int(simvol[1][i])] + simvol[0][i] + cipherSTR[int(simvol[1][i]):]\n\n print(cipherSTR)\n cipherSTR = cipherSTR.replace(\"X\", '')\n print(cipherSTR)\n openText.delete(1.0, END)\n openText.insert(1.0, cipherSTR)\n\n\n def polybiusI():\n messagebox.showinfo('Об Квадрате Полибия', 'В криптографии квадрат Полибия (англ. Polybius square), '\n 'также известный как шахматная доска Полибия — оригинальный '\n 'код простой замены, одна из древнейших систем кодирования, '\n 'предложенная Полибием')\n\n polybiusW = Tk()\n polybiusW.geometry(\"716x263+322+179\")\n polybiusW.title(\"Шифр Плейфера\")\n polybiusW.configure(background=\"#ffcece\")\n\n openText = Text(polybiusW)\n openText.place(relx=0.029, rely=0.3, relheight=0.612, relwidth=0.37)\n openText.configure(background=\"white\")\n openText.configure(borderwidth=\"2\")\n openText.configure(font=\"-family {@Malgun Gothic} -size 13\")\n openText.configure(foreground=\"black\")\n\n cipherText = Text(polybiusW)\n cipherText.place(relx=0.601, rely=0.3, relheight=0.612, relwidth=0.37)\n cipherText.configure(background=\"white\")\n cipherText.configure(borderwidth=\"2\")\n cipherText.configure(font=\"-family {@Malgun Gothic} -size 13\")\n cipherText.configure(foreground=\"black\")\n\n encryptPolybius = Button(polybiusW, command=polybiusE)\n encryptPolybius.place(relx=0.419, rely=0.305, height=34, width=115)\n encryptPolybius.configure(background=\"#ffffff\")\n encryptPolybius.configure(borderwidth=\"3\")\n encryptPolybius.configure(cursor=\"hand2\")\n encryptPolybius.configure(font=\"-family {@Malgun Gothic} -size 10\")\n encryptPolybius.configure(foreground=\"#000000\")\n encryptPolybius.configure(text='''Зашифровать ->''')\n\n decipherPolybius = Button(polybiusW, command=polybiusD)\n decipherPolybius.place(relx=0.419, rely=0.455, height=34, width=114)\n decipherPolybius.configure(background=\"#ffffff\")\n decipherPolybius.configure(borderwidth=\"3\")\n decipherPolybius.configure(cursor=\"hand2\")\n decipherPolybius.configure(font=\"-family {@Malgun Gothic} -size 10\")\n decipherPolybius.configure(foreground=\"#000000\")\n decipherPolybius.configure(text='''<-Расшифровать''')\n\n headPolybius = Label(polybiusW)\n headPolybius.place(relx=0.279, rely=0.075, height=52, width=341)\n headPolybius.configure(background=\"#ffcece\")\n headPolybius.configure(font=\"-family {Open Sans Light} -size 20 -weight bold\")\n headPolybius.configure(foreground=\"#000000\")\n headPolybius.configure(text='''Шифр Плейфера''')\n\n information = Button(polybiusW, command=polybiusI)\n information.place(relx=0.95, rely=0.038, height=24, width=27)\n information.configure(background=\"#ffffff\")\n information.configure(borderwidth=\"3\")\n information.configure(compound='left')\n information.configure(cursor=\"question_arrow\")\n information.configure(font=\"-family {Segoe UI} -size 11\")\n information.configure(foreground=\"#000000\")\n information.configure(text='''?''')\n\n keyPolybius = Entry(polybiusW)\n keyPolybius.place(relx=0.419, rely=0.602, height=30, relwidth=0.159)\n keyPolybius.configure(background=\"white\")\n keyPolybius.configure(borderwidth=\"2\")\n keyPolybius.configure(font=\"-family {@Malgun Gothic} -size 14\")\n keyPolybius.configure(foreground=\"#000000\")\n\n headKey = Label(polybiusW)\n headKey.place(relx=0.425, rely=0.714, height=11, width=103)\n headKey.configure(background=\"#ffcece\")\n headKey.configure(font=\"-family {@Malgun Gothic} -size 8\")\n headKey.configure(foreground=\"#000000\")\n headKey.configure(text='''Ключевое слово''')\n\n\n\n TCombobox1 = ttk.Combobox(polybiusW)\n TCombobox1.place(relx=0.768, rely=0.038, relheight=0.079\n , relwidth=0.158)\n TCombobox1['values'] = (\"Русский\", \"Английский\")\n TCombobox1.current(0) # установите вариант по умолчанию\n\n polybiusW.mainloop()","repo_name":"yablockoJiMori/cripte_symmetric","sub_path":"playfair.py","file_name":"playfair.py","file_ext":"py","file_size_in_byte":21484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"14727661814","text":"import os\nimport logging\nimport uuid\nfrom logging import Handler, FileHandler, StreamHandler\n\n\nclass PathFileHandler(FileHandler):\n def __init__(self, path, filename, mode='test_before', encoding=None, delay=False):\n\n filename = os.fspath(filename)\n if not os.path.exists(path):\n os.mkdir(path)\n self.baseFilename = os.path.join(path, filename)\n self.mode = mode\n self.encoding = encoding\n self.delay = delay\n if delay:\n Handler.__init__(self)\n self.stream = None\n else:\n StreamHandler.__init__(self, self._open())\n\n\nclass Loggers(object):\n # 日志级别关系映射\n level_relations = {\n 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING,\n 'error': logging.ERROR, 'critical': logging.CRITICAL\n }\n\n def __init__(self, filename='{uid}.log'.format(uid=uuid.uuid4()), level='info', log_dir='log',\n fmt='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s'):\n self.logger = logging.getLogger(filename)\n abspath = os.path.dirname(os.path.abspath(__file__))\n self.directory = os.path.join(abspath, log_dir)\n format_str = logging.Formatter(fmt) # 设置日志格式\n self.logger.setLevel(self.level_relations.get(level)) # 设置日志级别\n stream_handler = logging.StreamHandler() # 往屏幕上输出\n stream_handler.setFormatter(format_str)\n file_handler = PathFileHandler(path=self.directory, filename=filename, mode='test_before')\n file_handler.setFormatter(format_str)\n self.logger.addHandler(stream_handler)\n self.logger.addHandler(file_handler)\n\n\nif __name__ == \"__main__\":\n txt = \"关注公众号【进击的 Coder】,回复『日志代码』可以领取文章中完整的代码以及流程图\"\n log = Loggers(level='debug')\n log.logger.info(4)\n log.logger.info(5)\n log.logger.info(txt)\n","repo_name":"hsyy673150343/PythonLearning","sub_path":"模块/logging模块/coder.py","file_name":"coder.py","file_ext":"py","file_size_in_byte":1978,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"}
+{"seq_id":"13201412395","text":"N, M = map(int, input().split())\n\nmat = list()\nans = list()\n\nfor i in range(N):\n temp = input()\n row = list()\n for t in temp:\n row.append(int(t))\n mat.append(row)\n\nfor i in range(N):\n temp = input()\n row = list()\n for t in temp:\n row.append(int(t))\n ans.append(row)\n\n\nrow = 0\ncol = 0\n\nif N < 3 or M < 3:\n for col in range(N):\n for row in range(M):\n if mat[col][row] != ans[col][row]:\n print(-1)\n quit()\n print(0)\n quit()\n\ncount = 0\n\nwhile True:\n if col > N-1 or row > M-1:\n print(-1)\n quit()\n if mat[col][row] != ans[col][row]:\n if col+3 > N or row+3 > M:\n print(-1)\n quit()\n else:\n count += 1\n for c in range(3):\n for e in range(3):\n if mat[col+c][row+e] == 0:\n mat[col+c][row+e] = 1\n else:\n mat[col+c][row+e] = 0\n\n\n if row+3 > M:\n col += 1\n row = 0\n elif col+3 > N:\n for i in range(N):\n for l in range(M):\n if mat[i][l] != ans[i][l]:\n print(-1)\n quit()\n print(count)\n quit()\n else:\n row += 1","repo_name":"mushroom1324/Algorithm","sub_path":"BOJ_1080.py","file_name":"BOJ_1080.py","file_ext":"py","file_size_in_byte":1280,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"}
+{"seq_id":"7561203402","text":"import matplotlib.pyplot as plt\r\nfrom sklearn.model_selection import train_test_split, cross_val_score\r\nfrom sklearn.metrics import accuracy_score\r\nimport pandas as pd\r\nimport seaborn as sns\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\n\r\n# Importing the dataset\r\ndataset = pd.read_csv('bcdata.csv')\r\n\r\n# looking at the first 5 values of the dataset\r\ndataset.head()\r\n\r\n# Splitting the dataset in independent and dependent variables\r\nX = dataset.iloc[:, 1:10].values\r\nY = dataset['Class'].values\r\n\r\n# Splitting the dataset into the Training set and Test set\r\nX_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.20)\r\n\r\n# Fitting KNN Classifier to the Training set with linear kernel\r\nknnclassifier = KNeighborsClassifier(n_neighbors=10)\r\nknnclassifier.fit(X_train, y_train)\r\n\r\n# Making the prediction on test data\r\ny_pred = knnclassifier.predict(X_test)\r\n\r\n# Calculating Model Accuracy\r\naccuracy = accuracy_score(y_test,y_pred)*100\r\n\r\n# Printing the accuracy score of prediction and train test data\r\nprint('\\nAccuracy of KNN classifier on Training Set: {:.2f}'\r\n .format(knnclassifier.score(X_train, y_train)))\r\nprint('\\nAccuracy of KNN classifier on Test Set: {:.2f}'\r\n .format(knnclassifier.score(X_test, y_test)))\r\nprint('\\nAccuracy of Prediction :', str(round(accuracy, 2)) + ' %.')\r\n\r\n# Now lets understand the Accuracy of KNN on various value of neighbor by creating list of K for KNN\r\nk_list = list(range(1, 50, 1))\r\n\r\n# creating list of cv scores\r\ncv_scores = []\r\n\r\n# perform 10-fold cross validation\r\nfor k in k_list:\r\n knn = KNeighborsClassifier(n_neighbors=k)\r\n scores = cross_val_score(knn, X_train, y_train, cv=10, scoring='accuracy')\r\n cv_scores.append(scores.mean())\r\n\r\n# printing klist and cv_score\r\nprint(k_list)\r\nprint(cv_scores)\r\n\r\n# changing to misclassification error\r\nMSE = [1 - x for x in cv_scores]\r\n\r\n# Calculating best value of K\r\nbest_k = k_list[MSE.index(min(MSE))]\r\nprint(\"The optimal number of neighbors is %d.\" % best_k)\r\n\r\nplt.figure(figsize=(15, 10))\r\nplt.title('The optimal number of neighbors', fontsize=20, fontweight='bold')\r\nplt.xlabel('Number of Neighbors K', fontsize=15)\r\nplt.ylabel('Misclassification Error', fontsize=15)\r\nsns.set_style(\"whitegrid\")\r\nplt.plot(k_list, MSE)\r\nplt.show()","repo_name":"SnehaMishra28/Python-DeepLearning_Fall2018","sub_path":"Mod1_Lab2/Source/mod1_lab2/KNN.py","file_name":"KNN.py","file_ext":"py","file_size_in_byte":2267,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"31100806979","text":"import cv2\r\nimport numpy as np \r\nfrom matplotlib import pyplot as plt\r\n\r\ndef maior(blue, green, red):\r\n if(blue > green):\r\n if(blue > red):\r\n return \"a imagem é mais azul\"\r\n else:\r\n return \"a imagem é mais vermelha\"\r\n elif(green > red):\r\n return \"a imagem é mais verde\"\r\n else:\r\n return \"a imagem é mais vermelha\"\r\n\r\ndog = cv2.imread(\"trabalho2/cachorro.jpg\")\r\ndog = cv2.cvtColor(dog, cv2.COLOR_BGR2RGB)\r\naltura, largura, _ = dog.shape\r\n\r\nr, g, b = cv2.split(dog)\r\n\r\nplt.subplot(1, 3, 1), plt.imshow(b, cmap=\"gray\"), plt.title(\"BLUE\"), plt.xticks([]), plt.yticks([])\r\nplt.subplot(1, 3, 2), plt.imshow(g, cmap=\"gray\"), plt.title(\"GREEN\"), plt.xticks([]), plt.yticks([])\r\nplt.subplot(1, 3, 3), plt.imshow(r, cmap=\"gray\"), plt.title(\"RED\"), plt.xticks([]), plt.yticks([])\r\n\r\nblue = 0\r\ngreen = 0\r\nred = 0\r\n\r\nfor y in range(altura):\r\n for x in range(largura):\r\n blue += dog.item(y, x, 2)\r\n green += dog.item(y, x, 1)\r\n red += dog.item(y, x, 0)\r\n\r\nblue = blue/(altura*largura)\r\ngreen = green/(altura*largura)\r\nred = red/(altura*largura)\r\n\r\nprint(maior(blue, green, red))\r\n\r\nplt.show()","repo_name":"g4briel-rp/trabalho_PDI","sub_path":"parte2.py","file_name":"parte2.py","file_ext":"py","file_size_in_byte":1174,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"28827495877","text":"#%%\nfrom sklearn.svm import SVC\nfrom sklearn import datasets\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\n\n\nX, y = datasets.make_circles(n_samples=500,\n factor=0.3,\n noise=0.1)\nax = plt.subplot(111)\nax.set_facecolor((0.85, 0.85, 0.85))\nax.scatter(X[:,0], X[:,1], c=y, edgecolors='k', alpha=0.5)\nax.set_aspect('equal')\nplt.show()\n\nfig = plt.figure()\nax = fig.add_subplot(111, projection = \"3d\")\nax.scatter(X[:,0], X[:,1], np.sqrt(X[:, 0]**2 + X[:,1]**2),\n c = y, s =10)\nax.view_init(20, 35)\nplt.show()\n# %%\nmodel = SVC(kernel='poly', degree=2, coef0=1, C=10)\nmodel.fit(X, y)\n\nx_min = X[:, 0].min() - 0.5\nx_max = X[:, 0].max() + 0.5\ny_min = X[:, 1].min() - 0.5\ny_max = X[:, 1].max() + 0.5\n\nxx, yy = np.meshgrid(\n np.linspace(x_min, x_max, 500),\n np.linspace(y_min, y_max, 500)\n)\nxy_list = np.c_[xx.ravel(), yy.ravel()]\nax = plt.subplot(111)\n\nZ = model.predict(xy_list)\nZ = Z.reshape(xx.shape)\nax.contourf(xx, yy, Z, cmap='plasma', alpha=0.25)\n\nZ = model.decision_function(xy_list)\nZ = Z.reshape(xx.shape)\nax.contour(xx, yy, Z, colors='k', levels=[-1,0,1],\n linestyles=['--','-','--'], linewidths=1,\n alpha=0.5)\n\nax.scatter(X[:,0],X[:,1], c=y, edgecolors='k',alpha=0.5)\nax.set_aspect('equal')\n\nplt.scatter(\n model.support_vectors_[:,0],\n model.support_vectors_[:,1],\n s=150, facecolors='none', edgecolors='gray',\n linewidths=0.5\n)\n# %%\n","repo_name":"1994ericlee/assignment","sub_path":"Advanced AI/SVM.py","file_name":"SVM.py","file_ext":"py","file_size_in_byte":1461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"24662386128","text":"# XOR Operation in an Array\n# You are given an integer n and an integer start.\n# Define an array nums where nums[i] = start + 2 * i (0-indexed) and n == nums.length.\n# Return the bitwise XOR of all elements of nums.\n\ndef xorOperation (n, start) :\n sum = start\n counter = 1\n while (counter < n) :\n sum ^= (start + 2 * counter)\n counter += 1\n return sum\nprint(xorOperation(n = 5, start = 0))","repo_name":"vibhatsu08/leetcode-python","sub_path":"XORoperationInAnArray.py","file_name":"XORoperationInAnArray.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"31992111406","text":"from DB.DML import DML\nfrom crawling.crawlingmlbimg import CrawlingMlbImg\n\nif __name__ == \"__main__\":\n dml_instance = DML()\n\n table_name = \"baseball_players\"\n # select_list = [\"uid\", \"full_name\"]\n select_list = [\"name_slug\"]\n # players = dml_instance.get_select_from_where(column_names=select_list, table_name=table_name)\n condition = \"img_url is null\"\n players = dml_instance.get_select_from_where(column_names=select_list, table_name=table_name,condition=condition, print_sql=True)\n print(f'남은 크롤링할 선수 사진 수: {len(players)}')\n row_num1 = len(players) // 5\n row_num2 = len(players) // 5 * 2\n row_num3 = len(players) // 5 * 3\n row_num4 = len(players) // 5 * 4\n row_num5 = len(players)\n\n field_name = \"img_url\"\n # CrawlingMlbImg.save_db(table_name=table_name, player_names=players[now_num:row_num1], field_name=field_name)\n CrawlingMlbImg.save_db_by_name_slug(table_name=table_name, name_slugs=players[row_num4:], field_name=field_name)\n\n # 찬호\n # CrawlingGoogleImg.main(players[row_num1:row_num2])\n # 예림\n # CrawlingGoogleImg.main(players[row_num2:row_num3])\n","repo_name":"ehddn5252/ssafy_pjt2_data_processing","sub_path":"crwaler_main/picture_crwaler.py","file_name":"picture_crwaler.py","file_ext":"py","file_size_in_byte":1146,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"25782867970","text":"from datetime import date\nimport os\nimport extras.functions as ef\nfrom prefect import flow\n\n\n@flow(log_prints=True, retries=3, retry_delay_seconds=10, persist_result=False)\ndef extract_load(site_url: str, to_folder: str, file_type: str, start_year: int, end_year: int) -> None:\n\n YEARS_TO_DOWNLOAD = range(start_year, end_year + 1)\n\n # downloads\n print(\"Started to download files.\")\n for year in YEARS_TO_DOWNLOAD:\n work_dir = to_folder\n print(f\"Downloading {year}.zip\")\n downloaded_file = ef.downloader(url=f\"{site_url}{year}{file_type}\",\n folder=work_dir, filename=f\"{year}{file_type}\")\n\n # unzip\n zip_ext_dir = ef.unziper(\n zip_file=downloaded_file, folder=work_dir, year=year)\n\n # csvs to df\n print(f\"CSVs {year}.zip to DataFrame\")\n all_dfs_list = ef.csv_to_pd(foldername=zip_ext_dir)\n\n # remove sub-folder container for year, if so\n sub_folder = work_dir + str(year)\n if os.path.exists(sub_folder):\n os.rmdir(sub_folder)\n\n # df to parquet\n print(f\"DataFrame {year} to Parquet\")\n pq_file = ef.generate_parquet(all_dfs=all_dfs_list,\n folder=\"pqs/\", filename=str(year))\n\n # parquet to GCS\n print(f\"Upload {year}.Parquet to GCS\")\n ef.upload_parquet(filename=pq_file)\n\n # remove working folder\n if os.path.exists(to_folder):\n os.rmdir(to_folder)\n\n\n@flow(log_prints=True, retries=3, retry_delay_seconds=10, persist_result=False)\ndef main_flow(dict_param: dict) -> None:\n\n # Flow for Extract and Load\n extract_load(site_url=dict_param[\"BASE_URL\"],\n to_folder=dict_param[\"DEST_DIR\"],\n file_type=dict_param[\"FILE_EXT\"],\n start_year=dict_param[\"START_YEAR\"],\n end_year=dict_param[\"END_YEAR\"],\n )\n \n #create BG table\n ef.create_bg_ext_table(\"raw_zone\")\n\n # Flow for dbt Transform\n \n\nif __name__ == \"__main__\":\n flow_param = dict(\n BASE_URL=\"https://portal.inmet.gov.br/uploads/dadoshistoricos/\",\n DEST_DIR=\"./dump_zips/\",\n FILE_EXT=\".zip\",\n START_YEAR=date.today().year - 10,\n END_YEAR=date.today().year,\n )\n\n main_flow(dict_param=flow_param)\n","repo_name":"romiof/brazil-weather","sub_path":"prefect/elt_flow.py","file_name":"elt_flow.py","file_ext":"py","file_size_in_byte":2324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"32322459719","text":"class Solution:\n \"\"\"\n @param nums: a list of integers.\n @param k: length of window.\n @return: the sum of the element inside the window at each moving.\n \"\"\"\n def winSum(self, nums, k):\n # write your code here\n ret = []\n if nums:\n ret.append(0)\n for i in range(k):\n ret[0] += nums[i]\n for i in range(1, len(nums) - k + 1):\n ret.append(ret[i - 1] - nums[i - 1] + nums[i + k - 1])\n return ret;\n\n# easy: https://www.lintcode.com/problem/window-sum/\n","repo_name":"yingl/LintCodeInPython","sub_path":"window-sum.py","file_name":"window-sum.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","stars":123,"dataset":"github-code","pt":"31"}
+{"seq_id":"11595094947","text":"from django.shortcuts import render, HttpResponse\nfrom . models import Pelicula, PeliculaID, Director, Genero\n\n# Create your views here.\n\ndef index(request):\n num_peliculas = Pelicula.objects.all().count()\n num_ids = PeliculaID.objects.all().count()\n \n disponibles = PeliculaID.objects.filter(status__exact='d').count()\n num_director = Director.objects.all().count()\n num_genero = Genero.objects.all().count()\n \n return render(\n request, \n 'index.html',\n context={\n 'num_peliculas': num_peliculas,\n 'num_director': num_director,\n 'disponibles': disponibles,\n 'num_ids': num_ids,\n 'num_genero': num_genero,\n }\n ) \n \ndef peliculas(request):\n nombre = Pelicula.titulo\n return render(\n request,\n 'peliculas.html'\n )\n \ndef directores(request):\n nombre = Director.nombre\n apellido = Director.apellido\n return render(\n request,\n 'directores.html'\n ) ","repo_name":"vicbassdeveloper/EjerciciosOpenBootCamp","sub_path":"cursopython/Tema12.0/catalog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"43508275791","text":"import numpy as np\n\ndef RRR_elbow(l1,l2,l3,d,theta_1,theta_2,theta_3):\n\n theta_1=theta_1*np.pi/180\n theta_2=theta_2*np.pi/180\n theta_3=theta_3*np.pi/180\n \n H_01=np.array([[np.cos(theta_1),-np.sin(theta_1),0,0],\n [np.sin(theta_1),np.cos(theta_1),0,0],\n [0,0,1,0],\n [0,0,0,1]])\n\n\n H_12=np.array([[np.cos(theta_2),-np.sin(theta_2),0,l1],\n [np.sin(theta_2),np.cos(theta_2),0,0],\n [0,0,1,0],\n [0,0,0,1]])\n \n H_23=np.array([[np.cos(theta_3),-np.sin(theta_3),0,l2],\n [np.sin(theta_3),np.cos(theta_3),0,0],\n [0,0,1,0],\n [0,0,0,1]])\n\n p_1=np.array([[l1],[0],[0],[1]])\n p_2=np.array([[l2],[0],[0],[1]])\n p_3=np.array([[l3],[0],[0],[1]])\n \n O0=np.array([[0],[0],[0]])\n O1=(H_01@p_1)[:-1]\n O2=(H_01@H_12@p_2)[:-1]\n O3=(H_01@H_12@H_23@p_3)[:-1]\n\n z0=np.array([[0],[0],[1]])\n z1=np.array([[0],[0],[1]])\n z2=np.array([[0],[0],[1]])\n\n\n jacobian=np.concatenate((np.concatenate((np.cross(z0.T,(O3-O0).T).T,np.cross(z1.T,(O3-O1).T).T,np.cross(z2.T,(O3-O2).T).T),axis=1),\n np.concatenate((z0,z1,z2),axis=1)),axis=0)\n\n \n\n return print(jacobian.real)\n\n#Enter the arguments below \ntheta_1=80 # angle in degree\ntheta_2=50 # angle isn degree\ntheta_3=40\n\nl1=4 # length of arm 1\nl2=5 # length of arm 2\nl3=5\nd=2 # instantaneous distance from prismatic joint\n\nRRR_elbow(l1,l2,l3,d,theta_1,theta_2,theta_3)","repo_name":"Tejendra00/ME639-Robotics","sub_path":"Assignement_2/Que10.py","file_name":"Que10.py","file_ext":"py","file_size_in_byte":1568,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"42961342385","text":"# Т16.17 Описати генератор-функцію, що повертає всі доданки нескінченної\n# суми дійсних чисел, заданої співвідношенням, та обчислити суму всіх\n# доданків при заданому значенні x, що за абсолютною величиною не\n# перевищують заданого ε > 0:\ndef generator(x, eps):\n power = 1\n try:\n while True:\n power += 1\n addend = sign(power) * x**power/power\n if addend > eps:\n raise StopIteration\n yield addend\n except StopIteration:\n pass\n\ndef sign(power):\n if power % 2 == 0:\n return -1\n return 1\n\nx, eps = float(input('input x: ')), float(input('input eps: '))\n\nprint('y = ln(1+x) Addends:')\ncounter = 0\nprint(counter, x)\nfor x in generator(x, eps):\n counter += 1\n print(counter, x)\n","repo_name":"cyberskeleton/sandbox","sub_path":"2020-03-07hw3.py","file_name":"2020-03-07hw3.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"uk","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"18568161536","text":"import sys\nfrom heapq import heappush, heappop\ninput = sys.stdin.readline\n\n\ndef prim():\n Q = [(0, 1)]\n visit = [False] * (V + 1)\n cnt = 0\n\n ans = maxV = 0\n while cnt < V:\n cost, curV = heappop(Q)\n if visit[curV]: continue\n visit[curV] = True\n cnt += 1\n ans += cost\n if maxV < cost:\n maxV = cost\n\n for neiCost, neiV in adj[curV]:\n if not visit[neiV]:\n heappush(Q, (neiCost, neiV))\n\n return ans - maxV\n\n\nV, E = map(int, input().split())\nadj = [[] for _ in range(V + 1)]\nfor _ in range(E):\n A, B, C = map(int, input().split())\n adj[A].append((C, B))\n adj[B].append((C, A))\n\nprint(prim())","repo_name":"seunghee73/may-algo-study","sub_path":"0530/1647_hyry.py","file_name":"1647_hyry.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"34167094940","text":"\nimport io,json\nimport commands\nbasic={\n\t\t\"Hostname\" : \"hostname -b\",\n\t\t\"Distro Name\":\"uname -s\",\n\t\t\"Kernel Version\":\"uname -v\",\n\t\t\"Date\":\"date\",\n\t\t\"Machine\":\"uname -m\",\n\t\t\"Voltage\":\"vcgencmd measure_volts core\",\n\t\t\"Temperature\":\"vcgencmd measure_temp\"\n\n}\nnetwork={\n \n\t\t\tx:{\n\t\t\t\t\"IP address\" : \"/sbin/ifconfig \"+x+\" | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'\",\n\t\t\t\t\"IP loopback\": \"hostname -i\",\n\t\t\t\t\"Broadcast\" : \"/sbin/ifconfig \"+x+\" | grep 'inet addr:' | cut -d: -f3 | awk '{ print $1}'\",\n\t\t\t\t\"Subnetmask\" : \"/sbin/ifconfig \"+x+\" | grep 'inet addr:' | cut -d: -f4 | awk '{ print $1}'\",\n\t\t\t\t\"MAC\"\t\t :\"/sbin/ifconfig \"+x+\" | grep 'HWaddr' | tr -s ' ' |cut -d' ' -f5\",\n\t\t\t\t\"RX packet\" :\"/sbin/ifconfig \"+x+\" | grep 'RX packet' | cut -d: -f2 | awk '{ print $1}'\",\n\t\t\t\t\"TX packet\" :\"/sbin/ifconfig \"+x+\" | grep 'TX packet' | cut -d: -f2 | awk '{ print $1}'\",\n\t\t\t\t\"RX bytes\" :\"/sbin/ifconfig \"+x+\" | grep 'RX bytes' | cut -d: -f2 | awk '{ print $1$2$3}'\",\n\t\t\t\t\"TX bytes\"\t :\"/sbin/ifconfig \"+x+\" | grep 'TX bytes' | cut -d: -f2 | awk '{ print $1$2$3}'\"\n\t\t\t\t} for x in (\"eth0\",\"lo\")\n\t\t\t# \"\":\"\",\n}\n#print(commands.getoutput(basic[\"Date\"]))\nfor key, value in basic.items():\n\tbasic[key]=commands.getoutput(basic[key])\n#print(basic)\n\nfor key, value in network[\"eth0\"].items():\n\tnetwork[\"eth0\"][key]=commands.getoutput(network[\"eth0\"][key])\n\nstatus=[basic,network]\nwith open('sta/j.json', 'w') as file:\n\tjson.dump(basic, file)\n#with io.open('data.txt', 'w', encoding='utf-8') as f:\n#\tf.write(unicode(json.dump(data, ensure_ascii=False)))\n#\tfile.write(string(basic))\n#print(commands.getoutput(basic[\"Date\"]))\n#for key, value in basic.items():\n# \tbasic[key]=commands.getoutput(basic[key])\n#print(basic)\n\n#for key, value in network[\"eth0\"].items():\n# network[\"eth0\"][key]=commands.getoutput(network[\"eth0\"][key])\n#print(network[\"eth0\"])\n\n","repo_name":"grit0/project","sub_path":"json.py","file_name":"json.py","file_ext":"py","file_size_in_byte":2014,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"24009353658","text":"#!/usr/bin/env python\n\nfrom QUBEKit.decorators import timer_logger, for_all_methods\n\nfrom simtk.openmm import app\nimport simtk.openmm as mm\nfrom simtk import unit\nfrom numpy import array, zeros, sqrt, sum, exp, round, append\nfrom scipy.optimize import minimize\n\nfrom subprocess import run as sub_run\nfrom collections import OrderedDict\nfrom copy import deepcopy\nfrom os import chdir, mkdir, system, getcwd\nfrom shutil import rmtree\n\nimport matplotlib.pyplot as plt\n\n\n@for_all_methods(timer_logger)\nclass TorsionScan:\n \"\"\"\n This class will take a QUBEKit molecule object and perform a torsiondrive QM energy scan\n for each selected dihedral.\n\n inputs\n ---------------\n molecule A QUBEKit Ligand instance\n qm_engine A QUBEKit QM engine instance that will be used for calculations\n native_opt Should we use the QM engines internal optimizer or torsiondrive/geometric\n\n attributes\n ---------------\n grid_space The distance between the scan points on the surface\n \"\"\"\n\n def __init__(self, molecule, qm_engine, native_opt=False, verbose=False):\n\n # engine info\n self.qm_engine = qm_engine\n self.grid_space = self.qm_engine.fitting['increment']\n self.native_opt = native_opt\n self.verbose = verbose\n\n # molecule\n self.scan_mol = molecule\n self.constraints = None\n\n # working dir\n self.home = getcwd()\n\n # setup methods\n self.cmd = {}\n self.find_scan_order()\n self.torsion_cmd()\n\n def find_scan_order(self):\n \"\"\"\n Function takes the molecule and displays the rotatable central bonds,\n the user then enters the number of the torsions to be scanned in the order to be scanned.\n The molecule can also be supplied with a scan order already, if coming from csv\n or chosen in the input string.\n \"\"\"\n\n if self.scan_mol.scan_order:\n return self.scan_mol\n\n elif len(self.scan_mol.rotatable) == 1:\n print('One rotatable torsion found')\n self.scan_mol.scan_order = self.scan_mol.rotatable\n\n elif len(self.scan_mol.rotatable) == 0:\n print('No rotatable torsions found in the molecule')\n self.scan_mol.scan_order = []\n\n else:\n # Get the rotatable dihedrals from the molecule\n rotatable = list(self.scan_mol.rotatable)\n print('Please select the central bonds round which you wish to scan in the order to be scanned')\n print('Torsion number Central-Bond Representative Dihedral')\n for i, bond in enumerate(rotatable):\n print(f' {i + 1} {bond[0]}-{bond[1]} '\n f'{self.scan_mol.atom_names[self.scan_mol.dihedrals[bond][0][0] - 1]}-'\n f'{self.scan_mol.atom_names[self.scan_mol.dihedrals[bond][0][1] - 1]}-'\n f'{self.scan_mol.atom_names[self.scan_mol.dihedrals[bond][0][2] - 1]}-'\n f'{self.scan_mol.atom_names[self.scan_mol.dihedrals[bond][0][3] - 1]}')\n\n scans = list(input('>')) # Enter as a space separated list\n scans[:] = [scan for scan in scans if scan != ' '] # remove all spaces from the scan list\n\n scan_order = []\n # Add the rotatable dihedral keys to an array\n for scan in scans:\n scan_order.append(rotatable[int(scan) - 1])\n self.scan_mol.scan_order = scan_order\n\n def qm_scan_input(self, scan):\n \"\"\"Function takes the rotatable dihedrals requested and writes a scan input file for torsiondrive.\"\"\"\n\n with open('dihedrals.txt', 'w+') as out:\n\n out.write('# dihedral definition by atom indices starting from 0\\n# i j k l\\n')\n scan_di = self.scan_mol.dihedrals[scan][0]\n out.write(f' {scan_di[0]} {scan_di[1]} {scan_di[2]} {scan_di[3]}\\n')\n\n # TODO need to add PSI4 redundant mode selector\n\n if self.native_opt:\n self.qm_engine.generate_input(optimise=True)\n\n else:\n self.qm_engine.geo_gradient(run=False)\n\n def torsion_cmd(self):\n \"\"\"Generates a command string to run torsiondrive based on the input commands for QM and MM.\"\"\"\n\n # add the first basic command elements for QM\n cmd_qm = f'torsiondrive-launch {self.scan_mol.name}.psi4in dihedrals.txt '\n\n if self.grid_space:\n cmd_qm += f'-g {self.grid_space} '\n\n if self.qm_engine:\n cmd_qm += '-e psi4 '\n\n if self.native_opt:\n cmd_qm += '--native_opt '\n\n if self.verbose:\n cmd_qm += '-v '\n\n self.cmd = cmd_qm\n\n def get_energy(self, scan):\n \"\"\"\n Extracts an array of energies from the scan results then stores it back\n into the molecule (in a dictionary) using the scan orders as the keys.\n \"\"\"\n\n with open('scan.xyz', 'r') as scan_file:\n scan_energy = []\n for line in scan_file:\n if 'Energy ' in line:\n scan_energy.append(float(line.split()[3]))\n\n self.scan_mol.qm_scan_energy[scan] = array(scan_energy)\n\n def start_scan(self):\n \"\"\"Makes a folder and writes a new a dihedral input file for each scan and runs the scan.\"\"\"\n\n # TODO QCArchive/Fractal search don't do a calc that has been done!\n\n # TODO\n # if the molecule has multiple scans to do they should all start at the same time as this is slow\n # We must also make sure that we don't exceed the core limit when we do this!\n # e.g. user gives 6 cores for QM and we run two drives that takes 12 cores!\n\n for scan in self.scan_mol.scan_order:\n mkdir(f'SCAN_{scan[0]}_{scan[1]}')\n chdir(f'SCAN_{scan[0]}_{scan[1]}')\n mkdir('QM_torsiondrive')\n chdir('QM_torsiondrive')\n\n # now make the scan input files\n self.qm_scan_input(scan)\n sub_run(self.cmd, shell=True)\n self.get_energy(scan)\n chdir(self.home)\n\n\n@for_all_methods(timer_logger)\nclass TorsionOptimiser:\n \"\"\"\n Torsion optimiser class used to optimise dihedral parameters with a range of methods\n\n inputs\n ---------\n weight_mm: Weight the low energy parts of the surface (not sure if it works)\n combination: Which combination rules are to be used\n use_force: Match the forces as well as the energies (not avaiable yet)\n step_size: The scipy displacement step size\n minimum error_tol: The scipy error tol\n x_tol: ?\n opt_method: The main scipy optimization method (NM: Nelder-Mead, BFGS)\n refinement_method: The stage two refinement methods\n {SP: single point energy matching, Steep: steepest decent optimizer, None: no extra refinement.}\n vn_bounds: The absolute upper limit on Vn parameters (moving past this has a heavy penalty)\n \"\"\"\n\n def __init__(self, molecule, qm_engine, config_dict, weight_mm=True, combination='opls', use_force=False, step_size=0.02,\n error_tol=1e-5, x_tol=1e-5, opt_method='BFGS', refinement_method='Steep', vn_bounds=20):\n\n # configurations\n self.qm, self.fitting, self.descriptions = config_dict[1:]\n self.l_pen = self.fitting['l_pen']\n self.t_weight = self.fitting['t_weight']\n self.combination = combination\n self.weight_mm = weight_mm\n self.step_size = step_size\n self.methods = {'NM': 'Nelder-Mead', 'BFGS': 'BFGS', None: None}\n self.method = self.methods[opt_method]\n self.error_tol = error_tol\n self.x_tol = x_tol\n self.use_Force = use_force\n self.abs_bounds = vn_bounds\n self.refinement = refinement_method\n\n # QUBEKit objects\n self.molecule = molecule\n self.qm_engine = qm_engine\n\n # TorsionOptimiser starting parameters\n # QM scan energies {(scan): [array of qm energies]}\n self.energy_dict = molecule.qm_scan_energy\n # numpy array of the current mm energies\n self.mm_energy = None\n # numpy array of the fitting iteration initial parameter energies\n self.initial_energy = None\n # numpy array of the starting parameter energies\n self.starting_energy = None\n # list of the scan keys in the order to be fit\n self.scan_order = molecule.scan_order\n # list of molecule geometries in OpenMM format list[tuple] [(x, y, z)]\n self.scan_coords = []\n # list of the dihedral starting parameters\n self.starting_params = []\n # list of all of the qm energies collected in the same order as the scan coords\n self.energy_store_qm = []\n # list of all of the coordinates sampled in the fitting\n self.coords_store = []\n # the qm optimised geometrys\n self.initial_coords = []\n self.atm_no = len(molecule.atom_names)\n # important! stores the torsion indexs in the OpenMM system and groups torsions\n self.tor_types = OrderedDict()\n # list of the qm optimised energies\n self.target_energy = None\n # the current qm energy numpy array\n self.qm_energy = None\n # the current scan key that is being fit\n self.scan = None\n # numpy array of the parameters being fit, this is a flat array even with multipule torsions\n self.param_vector = None\n # this dictionary is a copy of the molecules periodic torsion force dict\n self.torsion_store = None\n # used to work out the index of the torsions in the OpenMM system\n self.index_dict = {}\n # the loaction of the QM torsiondrive\n self.qm_local = None\n\n # OpenMM system info\n self.system = None\n self.simulation = None\n\n # constants\n self.k_b = 0.001987\n self.phases = [0, 3.141592653589793, 0, 3.141592653589793]\n self.home = getcwd()\n\n # start the OpenMM system\n self.molecule.write_pdb()\n self.rest_torsions()\n self.openmm_system()\n\n def mm_energies(self):\n \"\"\"Evaluate the MM energies of the QM structures.\"\"\"\n\n mm_energy = []\n for position in self.scan_coords:\n mm_energy.append(self.get_energy(position))\n\n return array(mm_energy)\n # get forces from the system\n # open_grad = state.getForces()\n\n @staticmethod\n def get_coords(engine):\n \"\"\"\n Read the torsion drive output file to get all of the coords in a format that can be passed to openmm\n so we can update positions in context without reloading the molecule.\n \"\"\"\n\n scan_coords = []\n if engine == 'torsiondrive':\n # open the torsion drive data file read all the scan coordinates\n with open('qdata.txt', 'r') as data:\n for line in data.readlines():\n if 'COORDS' in line:\n # get the coords into a single array\n coords = [float(x) / 10 for x in line.split()[1:]]\n # convert to a list of tuples for OpenMM format\n tups = []\n for i in range(0, len(coords), 3):\n tups.append((coords[i], coords[i + 1], coords[i + 2]))\n scan_coords.append(tups)\n\n # get the coords from a geometric output\n elif engine == 'geometric':\n with open('scan-final.xyz', 'r') as data:\n lines = data.readlines()\n # get the amount of atoms\n atoms = int(lines[0])\n for i, line in enumerate(lines):\n if 'Iteration' in line:\n # this is the start of the cordinates\n tups = []\n for coords in lines[i + 1:i + atoms + 1]:\n coord = tuple(float(x) / 10 for x in coords.split()[1:])\n # convert to a list of tuples for OpenMM format\n # store tuples\n tups.append(coord)\n # now store that structure back to the coords list\n scan_coords.append(tups)\n return scan_coords\n\n def openmm_system(self):\n \"\"\"Initialise the OpenMM system we will use to evaluate the energies.\"\"\"\n\n # Load the initial coords into the system and initialise\n self.molecule.write_pdb(input_type='input', name=self.molecule.name)\n pdb = app.PDBFile(f'{self.molecule.name}.pdb')\n forcefield = app.ForceField(f'{self.molecule.name}.xml')\n modeller = app.Modeller(pdb.topology, pdb.positions) # set the initial positions from the pdb\n self.system = forcefield.createSystem(modeller.topology, nonbondedMethod=app.NoCutoff, constraints=None)\n\n if self.combination == 'opls':\n self.opls_lj()\n\n temperature = 298.15 * unit.kelvin\n integrator = mm.LangevinIntegrator(temperature, 5 / unit.picoseconds, 0.001 * unit.picoseconds)\n\n self.simulation = app.Simulation(modeller.topology, self.system, integrator)\n self.simulation.context.setPositions(modeller.positions)\n\n def initial_energies(self):\n \"\"\"Calculate the initial energies using the input xml.\"\"\"\n\n # first we need to work out the index order the torsions are in while inside the OpenMM system\n # this order is different from the xml order\n forces = {self.simulation.system.getForce(index).__class__.__name__: self.simulation.system.getForce(index) for\n index in range(self.simulation.system.getNumForces())}\n torsion_force = forces['PeriodicTorsionForce']\n for i in range(torsion_force.getNumTorsions()):\n p1, p2, p3, p4, periodicity, phase, k = torsion_force.getTorsionParameters(i)\n torsion = (p1, p2, p3, p4)\n if torsion not in self.index_dict:\n self.index_dict[torsion] = i\n\n # Now, reset all periodic torsion terms back to their initial values\n for pos, key in enumerate(self.torsion_store):\n try:\n self.tor_types[pos] = [[key], [float(self.torsion_store[key][i][1]) for i in range(4)],\n [self.index_dict[key]]]\n except KeyError:\n try:\n self.tor_types[pos] = [[tuple(reversed(key))], [float(self.torsion_store[key][i][1]) for i in range(4)],\n [self.index_dict[tuple(reversed(key))]]]\n except KeyError:\n # after trying to match the forward and backwards strings must be improper\n self.tor_types[pos] = [[(key[1], key[2], key[0], key[3])], [float(self.torsion_store[key][i][1]) for i in range(4)],\n [self.index_dict[(key[1], key[2], key[0], key[3])]]]\n\n self.update_torsions()\n # initial is a referenceto the energy surface at the start of the fit\n self.initial_energy = deepcopy(self.mm_energies())\n # starting energy is the surface made by the original unfit parameters\n self.starting_energy = deepcopy(self.initial_energy)\n\n # Reset the dihedral values\n self.tor_types = OrderedDict()\n\n def update_tor_vec(self, x):\n \"\"\"Update the tor_types dict with the parameter vector.\"\"\"\n\n x = round(x, decimals=4)\n\n # Update the param vector for the right torsions by slicing the vector every 4 places\n for key, val in self.tor_types.items():\n val[1] = x[key * 4:key * 4 + 4]\n\n def get_energy(self, position):\n \"\"\"Return the MM calculated energy of the structure.\"\"\"\n\n # update the positions of the system\n self.simulation.context.setPositions(position)\n\n # Get the energy from the new state\n state = self.simulation.context.getState(getEnergy=True, getForces=self.use_Force)\n\n energy = float(str(state.getPotentialEnergy())[:-6])\n\n # Convert from kJ to kcal\n return energy / 4.184\n\n def objective(self, x):\n \"\"\"Return the output of the objective function.\"\"\"\n\n # Update the parameter vector into tor_types\n self.update_tor_vec(x)\n\n # Update the torsions in the Openmm system\n self.update_torsions()\n\n # Get the mm corresponding energy\n self.mm_energy = deepcopy(self.mm_energies())\n\n # Make sure the energies match\n assert len(self.qm_energy) == len(self.mm_energy)\n\n # calculate the objective\n\n # Adjust the mm energy to make it relative to the minimum structure\n mm_energy = self.mm_energy - min(self.mm_energy)\n error = (mm_energy - self.qm_energy) ** 2\n\n # if using a weighting, add that here\n if self.t_weight != 'infinity':\n error *= exp(-self.qm_energy / (self.k_b * self.t_weight))\n\n # Find the total error\n total_error = sqrt(sum(error) / len(self.scan_coords))\n\n # Calculate the penalties\n # 1 the movement away from the starting values\n move_pen = self.l_pen * sum((x - self.starting_params) ** 2)\n\n # 2 the penalty incurred by going past the bounds\n bounds_pen = sum(1 for vn in x if abs(vn) >= self.abs_bounds)\n\n total_error += move_pen + bounds_pen\n return total_error\n\n def steep_objective(self, x):\n \"\"\"Return the output of the objective function when using the steep refinment method.\"\"\"\n\n # Update the parameter vector into tor_types\n self.update_tor_vec(x)\n\n # Update the torsions\n self.update_torsions()\n\n # first drive the torsion using geometric\n self.scan_coords = self.drive_mm(engine='geometric')\n\n # Get the mm corresponding energy\n self.mm_energy = self.mm_energies()\n\n # Make sure the energies match\n assert len(self.qm_energy) == len(self.mm_energy)\n\n # calculate the objective\n\n # Adjust the mm energy to make it relative to the lowest in the scan\n self.mm_energy -= min(self.mm_energy)\n error = (self.mm_energy - self.qm_energy) ** 2\n\n # if using a weighting, add that here\n if self.t_weight != 'infinity':\n error *= exp(-self.qm_energy / (self.k_b * self.t_weight))\n\n # Find the total error\n total_error = sqrt(sum(error) / len(self.scan_coords))\n\n # Calculate the penalty\n pen = self.l_pen * sum((x - self.starting_params) ** 2)\n total_error += pen\n\n return total_error\n\n def single_point_matching(self, fitting_error, opt_parameters):\n \"\"\"A function the call the single point matching method of parameter refinement.\n\n method (fit only new generation)\n -------------------\n 1) take parameters from the initial scipy fitting.\n 2) Do a MM torsion scan with the parameters and get the rmsd error\n 3) Calculate the QM single point energies from the structures and get the energy error\n 4) Calculate the total error if not converged fit using scipy to all structures and move to step 2)\n \"\"\"\n\n converged = False\n\n # put in the objective dict\n objective = {'fitting error': [],\n 'energy error': [],\n 'rmsd': [],\n 'total': [],\n 'parameters': []}\n\n iteration = 1\n # start the main optimizer loop by calculating new single point energies\n while not converged:\n # move into the first iteration folder\n try:\n mkdir(f'Iteration_{iteration}')\n except FileExistsError:\n pass\n chdir(f'Iteration_{iteration}')\n\n # step 2 MM torsion scan\n # with wavefront propagation, returns the new set of coords these become the new scan coords\n self.scan_coords = self.drive_mm(engine='torsiondrive')\n\n # also save these coords to the coords store\n self.coords_store = deepcopy(self.coords_store + self.scan_coords)\n\n # step 3 calculate the rmsd for these structures compared to QM\n rmsd = self.rmsd(f'{self.qm_local}/scan.xyz', 'torsiondrive_scan/scan.xyz')\n\n # step 4 calculate the single point energies\n self.qm_energy = self.single_point()\n\n # Keep a copy of the energy before adjusting in case another loop is needed\n self.energy_store_qm = deepcopy(append(self.energy_store_qm, self.qm_energy))\n\n # Normalise the qm energy again using the qm reference energy\n self.qm_normalise()\n\n # calculate the energy error in step 4 (just for this scan) and get a measure of the new reference energies\n energy_error = self.objective(opt_parameters)\n # this now acts as the intial energy for the next fit\n self.initial_energy = deepcopy(self.mm_energy)\n\n # add the results to the dictionary\n objective['fitting error'].append(fitting_error)\n objective['energy error'].append(energy_error)\n objective['rmsd'].append(rmsd)\n objective['total'].append(energy_error + rmsd)\n objective['parameters'].append(opt_parameters)\n\n # now check to see if the error has converged?\n if iteration < 3:\n # if (energy_error + rmsd - objective['total'][-1]) < 0 and\\\n # abs(energy_error + rmsd - objective['total'][-1]) > 0.01:\n\n # now we don't want to move to far away from the last set of optimized parameters\n self.starting_params = opt_parameters\n # turn on the penalty\n self.l_pen = 0.01\n\n # optimise using the scipy method for the new structures with a penatly to remain close to the old\n fitting_error, opt_parameters = self.scipy_optimiser()\n\n # update the parameters in the fitting vector and the molecule for the MM scans\n self.update_tor_vec(opt_parameters)\n self.update_mol()\n\n # use the parameters to get the current energies\n self.mm_energy = deepcopy(self.mm_energies())\n\n # plot the fitting graph this iteration\n self.plot_results(name=f'SP_iter_{iteration}')\n\n # now reset the energy's\n self.qm_normalise()\n\n # move out of the folder\n chdir('../')\n\n # add 1 to the iteration\n iteration += 1\n else:\n # use the parameters to get the current energies\n self.mm_energy = deepcopy(self.mm_energies())\n # print the final iteration energy prediction\n self.plot_results(name=f'SP_iter_{iteration}')\n chdir('../')\n break\n\n # find the minimum total error index in list\n min_error = min(objective['total'])\n min_index = objective['total'].index(min_error)\n\n # gather the parameters with the lowest error, not always the last parameter set\n final_parameters = deepcopy(objective['parameters'][min_index])\n final_error = objective['total'][min_index]\n\n # now we want to see how well we have captured the initial QM energy surface\n # reset the scan coords to the initial values\n self.scan_coords = self.initial_coords\n\n # get the energy surface for these final parameters\n # this will also update the parameters in the molecule class so we can write a new xml\n # first get back the original qm energies as well\n self.qm_energy = self.energy_store_qm[:24]\n self.qm_normalise()\n # energy_error = self.objective(final_parameters)\n\n # get the starting energies back to the initial values before fitting\n self.initial_energy = self.starting_energy\n # plot the results this is a graph of the starting QM surface and how well we can remake it\n self.plot_results(name='Stage2_Single_point_fit')\n\n self.convergence_plot('final_converge', objective)\n\n return final_error, final_parameters\n\n def plot_correlation(self, name):\n \"\"\"Plot the single point energy correlation.\"\"\"\n\n # Make sure we have the same number of energy terms in the QM and MM lists\n assert len(self.qm_energy) == len(self.mm_energy)\n\n # adjust the mm_energy but do not alter\n mm_energy = self.mm_energy - min(self.mm_energy)\n\n # now we are just plotting them against each other they are already in the right order\n plt.scatter(mm_energy, self.qm_energy)\n\n plt.xlabel('Relative energy (kcal/mol) MM energy')\n plt.ylabel('Relative energy (kcal/mol) QM energy')\n plt.savefig(f'{name}.pdf')\n plt.clf()\n\n def qm_normalise(self):\n \"\"\"Normalize the qm energy to the reference energy.\"\"\"\n\n self.qm_energy -= min(self.qm_energy) # make relative to lowest energy\n self.qm_energy *= 627.509 # convert to kcal/mol\n\n def opt_test(self):\n \"\"\"\n Take optimized xml file and test the agreement with QM by doing a torsion drive and checking the single\n point energies.\n \"\"\"\n\n # move into testing folder\n mkdir('testing_opt')\n chdir('testing_opt')\n\n self.scan = self.scan_order[0]\n\n # now run the torsiondrive\n # step 2 MM torsion scan\n # with wavefront propagation, returns the new set of coords these become the new scan coords\n self.scan_coords = self.drive_mm(engine='torsiondrive')\n\n # step 4 calculate the single point energies\n self.qm_energy = self.single_point()\n\n # Normalise the qm energy again using the qm reference energy\n self.qm_normalise()\n\n # calculate the mm energy\n # use the parameters to get the current energies\n self.mm_energy = deepcopy(self.mm_energies())\n\n # for the graph\n self.initial_energy = self.mm_energy\n # now graph the energy\n self.plot_results(name='testing_opt')\n\n def run(self):\n \"\"\"\n Optimise the parameters for the chosen torsions in the molecule scan_order,\n also set up a work queue to do the single point calculations if they are needed.\n \"\"\"\n\n # Set up the first fitting\n for self.scan in self.scan_order:\n # move into the QM scan folder to get the scan coords\n chdir(f'SCAN_{self.scan[0]}_{self.scan[1]}/QM_torsiondrive')\n # keep track of the QM_torsiondrive location needed for rmsd error\n self.qm_local = getcwd()\n\n # Get the MM coords from the QM torsion drive\n self.scan_coords = self.get_coords(engine='torsiondrive')\n\n # now move to our working folder\n # make a lot of folders not nice\n # sort out errors how will this work with restarts and re-runs?\n chdir('../')\n try:\n mkdir('Optimisation')\n except FileExistsError:\n pass\n chdir('Optimisation')\n try:\n mkdir('First_fit')\n mkdir('Refinement')\n except FileExistsError:\n pass\n chdir('First_fit')\n\n # Set the target energies first\n self.target_energy = self.energy_dict[self.scan]\n\n # Adjust the QM energies\n # and store all QM raw energies\n self.energy_store_qm = deepcopy(self.target_energy)\n self.qm_energy = deepcopy(self.target_energy)\n # store the optimized qm energy and make all other energies relative to this one\n\n self.qm_normalise()\n\n # Keep the initial coords\n self.coords_store = deepcopy(self.scan_coords)\n self.initial_coords = deepcopy(self.scan_coords)\n\n # Get the initial energies\n self.initial_energies()\n\n # Get the torsions that will be fit and make the param vector\n self.get_torsion_params()\n\n # Start the main optimiser loop and get the final error and parameters back\n error, opt_parameters = self.scipy_optimiser()\n self.param_vector = opt_parameters\n\n # Push the new parameters back to the molecule parameter dictionary\n self.update_mol()\n\n # Plot the results of the first fit\n self.plot_results(name='Stage1_scipy')\n\n # move to the refinment section\n chdir('../Refinement')\n\n if self.refinement == 'SP':\n error, opt_parameters = self.single_point_matching(error, opt_parameters)\n self.param_vector = opt_parameters\n\n elif self.refinement == 'Steep':\n error, opt_parameters = self.steepest_decent_refinement(self.param_vector)\n\n # now push the parameters back to the molecule\n self.update_tor_vec(opt_parameters)\n self.update_mol()\n\n # now move back to the starting directory\n chdir(self.home)\n\n def steepest_decent_refinement(self, x):\n \"\"\"\n A steepest decent optimiser as implemented in QUBEKit-V1, which will optimise the torsion terms\n using full relaxed surface scans. SLOW!\n \"\"\"\n\n print('Starting optimisation...')\n\n # search steep sizes\n step_size = [0.1, 0.01, 0.001]\n step_index = 0\n\n # set convergence\n converged = False\n final_error = None\n final_parameters = None\n\n # start main optimizer loop\n while not converged:\n\n # when to change the step size\n un_changed = 0\n\n # for each Vn parameter in the parameter vector\n for i in range(len(x)):\n\n # error dict\n error = {}\n\n # First we need to get the initial error with a full relaxed scan\n self.scan_coords = self.drive_mm(engine='geometric')\n\n # get the starting energies and errors from the current parameter set\n normal = self.objective(x)\n\n error[normal] = x\n # make a copy of the parameter vector\n y_plus = deepcopy(x)\n\n # now make a variation on the parameter set\n y_plus[i] += step_size[step_index]\n print(f'y plus {y_plus}')\n # now find the new error\n self.scan_coords = self.drive_mm(engine='geometric')\n\n error_plus = self.objective(y_plus)\n error[error_plus] = y_plus\n\n # now make a differnt variation\n y_minus = deepcopy(x)\n y_minus[i] -= step_size[step_index]\n print(f'y minus {y_minus}')\n\n # now find the other error\n self.scan_coords = self.drive_mm(engine='geometric')\n error_minus = self.objective(y_minus)\n error[error_minus] = y_minus\n\n # now work out which has the lowest error\n min_error = min(normal, error_plus, error_minus)\n print(f'minimum error {min_error}')\n\n # now the parameter vector becomes who had the lowest error\n x = deepcopy(error[min_error])\n print(f'The new parameter vector {x}')\n\n # if the error is not changed count how many times this happens\n if min_error == normal:\n # add one to unchanged\n un_changed += 1\n\n # if all Vn have no effect then change the step size\n if un_changed == len(x) - 1:\n step_index += 1\n\n # now check to see if we have ran out steps\n if step_index >= len(step_size):\n final_parameters = deepcopy(x)\n final_error = deepcopy(min_error)\n converged = True\n\n return final_error, final_parameters\n\n def rest_torsions(self):\n \"\"\"\n Set all the torsion k values to one for every torsion in the system.\n\n Once an OpenMM system is created we cannot add new torsions without making a new PeriodicTorsion\n force every time.\n\n To get round this we have to load every k parameter into the system first; so we set every k term in the fitting\n dihedrals to 1 then reset all values to the gaff terms and update in context.\n \"\"\"\n\n # save the molecule torsions to a dict\n self.torsion_store = deepcopy(self.molecule.PeriodicTorsionForce)\n\n # Set all the torsion to 1 to get them into the system\n for key in self.molecule.PeriodicTorsionForce:\n if self.molecule.PeriodicTorsionForce[key][-1] == 'Improper':\n self.molecule.PeriodicTorsionForce[key] = [['1', '1', '0'], ['2', '1', '3.141592653589793'],\n ['3', '1', '0'], ['4', '1', '3.141592653589793'], 'Improper']\n else:\n self.molecule.PeriodicTorsionForce[key] = [['1', '1', '0'], ['2', '1', '3.141592653589793'],\n ['3', '1', '0'], ['4', '1', '3.141592653589793']]\n\n # Write out the new xml file which is read into the OpenMM system\n self.molecule.write_parameters()\n\n # Put the torsions back into the molecule\n self.molecule.PeriodicTorsionForce = deepcopy(self.torsion_store)\n\n def get_torsion_params(self):\n \"\"\"\n Get the torsions and their parameters that will scanned, work out how many different torsion types needed,\n make a vector corresponding to this size.\n \"\"\"\n\n # Get a list of which dihedrals parameters are to be varied\n # Convert to be indexed from 0\n to_fit = [(tor[0] - 1, tor[1] - 1, tor[2] - 1, tor[3] - 1) for tor in list(self.molecule.dihedrals[self.scan])]\n\n # Check which ones have the same parameters and how many torsion vectors we need\n self.tor_types = OrderedDict()\n\n i = 0\n while to_fit:\n # Get the current torsion\n torsion = to_fit.pop(0)\n\n # Get the torsions param vector used to compare to others\n # The master vector could be backwards so try one way and if keyerror try the other\n try:\n master_vector = [float(self.torsion_store[torsion][i][1]) for i in range(4)]\n except KeyError:\n torsion = torsion[::-1]\n master_vector = [float(self.torsion_store[torsion][i][1]) for i in range(4)]\n\n # Add this type to the torsion type dictionary with the right key index\n try:\n self.tor_types[i] = [[torsion], master_vector, [self.index_dict[torsion]]]\n except KeyError:\n self.tor_types[i] = [[torsion], master_vector, [self.index_dict[tuple(reversed(torsion))]]]\n\n to_remove = []\n # Iterate over what is left of the list to see what other torsions are the same as the master\n for dihedral in to_fit:\n # Again, try both directions\n try:\n vector = [float(self.torsion_store[dihedral][i][1]) for i in range(4)]\n except KeyError:\n dihedral = dihedral[::-1]\n vector = [float(self.torsion_store[dihedral][i][1]) for i in range(4)]\n\n # See if that vector is the same as the master vector\n if vector == master_vector:\n try:\n self.tor_types[i][2].append(self.index_dict[dihedral])\n self.tor_types[i][0].append(dihedral)\n except KeyError:\n self.tor_types[i][2].append(self.index_dict[tuple(reversed(dihedral))])\n self.tor_types[i][0].append(tuple(reversed(dihedral)))\n to_remove.append(dihedral)\n\n # Remove all of the dihedrals that have been matched\n for dihedral in to_remove:\n try:\n to_fit.remove(dihedral)\n except ValueError:\n to_fit.remove(dihedral[::-1])\n i += 1\n\n # now that we have grouped by param vectors we need to compare the gaff atom types that make up the torsions\n # then if they are different we need to further split the torsions\n # first construct the dictionary of type strings\n torsion_string_dict = {}\n for index, tor_info in self.tor_types.items():\n for j, torsion in enumerate(tor_info[0]):\n # get the tuple of the torsion string\n tor_tup = tuple(self.molecule.AtomTypes[torsion[i]][3] for i in range(4))\n # check if its in the torsion string dict\n try:\n torsion_string_dict[tor_tup][0].append(torsion)\n torsion_string_dict[tor_tup][2].append(tor_info[2][j])\n except KeyError:\n try:\n torsion_string_dict[tuple(reversed(tor_tup))][0].append(torsion)\n torsion_string_dict[tuple(reversed(tor_tup))][2].append(tor_info[2][j])\n except KeyError:\n torsion_string_dict[tor_tup] = [[torsion], tor_info[1], [tor_info[2][j]]]\n\n self.tor_types = OrderedDict((index, k) for index, k in enumerate(torsion_string_dict.values()))\n\n # Make the param_vector of the correct size\n self.param_vector = zeros((1, 4 * len(self.tor_types)))\n\n # now take the master vectors and make the starting parameter list\n # Store the original parameter vectors to use regularisation\n self.starting_params = [list(k)[1][i] for k in self.tor_types.values() for i in range(4)]\n\n @staticmethod\n def rmsd(qm_coords, mm_coords):\n \"\"\"\n Calculate the rmsd between the MM and QM predicted structures from the relaxed scans using pymol;\n this can be added into the penalty function.\n \"\"\"\n\n import __main__\n # Quiet and no GUI\n __main__.pymol_argv = ['pymol', '-qc']\n\n from pymol import cmd as py_cmd\n from pymol import finish_launching\n\n finish_launching()\n py_cmd.load(mm_coords, object='MM_scan')\n py_cmd.load(qm_coords, object='QM_scan')\n rmsd = py_cmd.align('MM_scan', 'QM_scan')[0]\n # Remove the objects from the pymol instance\n py_cmd.delete('MM_scan')\n py_cmd.delete('QM_scan')\n\n return rmsd\n\n def finite_difference(self, x):\n \"\"\"Compute the gradient of changing the parameter vector using central difference scheme.\"\"\"\n\n gradient = []\n for i in range(len(x)):\n x[i] += self.step_size / 2\n plus = self.objective(x)\n x[i] -= self.step_size\n minus = self.objective(x)\n diff = (plus - minus) / self.step_size\n gradient.append(diff)\n return array(gradient)\n\n def scipy_optimiser(self):\n \"\"\"The main torsion parameter optimiser that controls the optimisation method used.\"\"\"\n\n print(f'Running SciPy {self.method} optimiser ... ')\n\n if self.method == 'Nelder-Mead':\n res = minimize(self.objective, self.param_vector, method='Nelder-Mead',\n options={'xtol': self.x_tol, 'ftol': self.error_tol, 'disp': True})\n\n elif self.method == 'BFGS':\n res = minimize(self.objective, self.param_vector, method='BFGS', jac=self.finite_difference,\n options={'disp': True})\n\n else:\n raise NotImplementedError('The optimisation method is not implemented')\n\n print('SciPy optimisation complete')\n\n # Update the tor types dict using the optimised vector\n self.update_tor_vec(res.x)\n\n # return the final fitting error and final param vector after the optimisation\n return res.fun, res.x\n\n def call_force_balance(self):\n \"\"\"Call force balance to do the single point energy matching.\"\"\"\n\n pass\n\n def update_torsions(self):\n \"\"\"Update the torsions being fitted.\"\"\"\n\n forces = {self.simulation.system.getForce(index).__class__.__name__: self.simulation.system.getForce(index) for\n index in range(self.simulation.system.getNumForces())}\n torsion_force = forces['PeriodicTorsionForce']\n i = 0\n for val in self.tor_types.values():\n for j, dihedral in enumerate(val[0]):\n for v_n in range(4):\n torsion_force.setTorsionParameters(index=v_n + val[2][j],\n particle1=dihedral[0], particle2=dihedral[1],\n particle3=dihedral[2], particle4=dihedral[3],\n periodicity=v_n + 1, phase=self.phases[v_n],\n k=val[1][v_n])\n i += 1\n torsion_force.updateParametersInContext(self.simulation.context)\n\n return self.system\n\n @staticmethod\n def convergence_plot(name, objective_dict):\n \"\"\"Plot the convergence of the errors of the fitting.\"\"\"\n\n # sns.set()\n\n # this will be a plot with multipul lines showing the convergence of the errors with each iteration\n iterations = [x for x in range(len(objective_dict['total']))]\n rmsd = objective_dict['rmsd']\n fitting_error = objective_dict['fitting error']\n energy_error = objective_dict['energy error']\n total_error = objective_dict['total']\n\n plt.plot(iterations, energy_error, label='SP energy error')\n plt.plot(iterations, rmsd, label='Rmsd error')\n plt.plot(iterations, fitting_error, label='Fitting error')\n plt.plot(iterations, total_error, label='Total error')\n\n plt.ylabel('Error (kcal/mol)')\n plt.xlabel('Iteration')\n plt.legend()\n plt.savefig(f'{name}.pdf')\n plt.clf()\n\n def plot_test(self, energies):\n \"\"\"Plot the results of the fitting.\"\"\"\n\n # sns.set()\n\n # Make sure we have the same number of energy terms in the QM and MM lists\n assert len(self.qm_energy) == len(self.mm_energy)\n\n # Now adjust the MM energies\n # self.mm_energy -= min(self.mm_energy)\n # self.mm_energy /= 4.184 # convert from kj to kcal\n\n # Make the angle array\n angles = [x for x in range(-165, 195, self.qm_engine.fitting['increment'])]\n plt.plot(angles, self.qm_energy, 'o', label='QM')\n for pos, scan in enumerate(energies):\n self.mm_energy = array(scan)\n self.mm_energy -= min(self.mm_energy)\n plt.plot(angles, self.mm_energy, label=f'MM{pos}')\n plt.ylabel('Relative energy (kcal/mol')\n plt.xlabel('Dihedral angle$^{\\circ}$')\n plt.legend()\n plt.savefig('Plot.pdf')\n\n def plot_results(self, name='Plot', validate=False):\n \"\"\"Plot the results of the scan.\"\"\"\n\n # sns.set()\n\n # Make sure we have the same number of energy terms in the QM and MM lists\n assert len(self.qm_energy) == len(self.mm_energy)\n\n # Adjust the MM energies\n plot_mm_energy = self.mm_energy - min(self.mm_energy)\n\n # Adjust the initial MM energies\n initial_energy = self.initial_energy - min(self.initial_energy)\n\n # Construct the angle array\n angles = [x for x in range(-165, 195, self.qm_engine.fitting['increment'])]\n points = [x for x in range(len(self.qm_energy))] if len(self.qm_energy) > len(angles) else None\n\n if points is not None:\n # Print a table of the results for multiple plots\n print(f'Geometry QM(relative) MM(relative) MM_initial(relative)')\n for i in points:\n print(f'{i:4} {self.qm_energy[i]:15.10f} {plot_mm_energy[i]:15.10f} {initial_energy[i]:15.10f}')\n\n # Plot the qm and mm data\n plt.plot(points, self.qm_energy, 'o', label='QM')\n plt.plot(points, initial_energy, label='MM initial')\n plt.plot(points, plot_mm_energy, label=f'MM final')\n\n plt.xlabel('Geometry')\n\n else:\n # Print a table of the results\n print(f'Angle QM(relative) MM(relative) MM_initial(relative)')\n for pos, angle in enumerate(angles):\n print(\n f'{angle:4} {self.qm_energy[pos]:15.10f} {plot_mm_energy[pos]:15.10f} {initial_energy[pos]:15.10f}')\n\n plt.xlabel('Dihedral angle$^{\\circ}$')\n\n # Plot the qm and mm data\n plt.plot(angles, self.qm_energy, 'o', label='QM data')\n if not validate:\n plt.plot(angles, initial_energy, label='Starting parameters', linestyle='--')\n plt.plot(angles, plot_mm_energy, label='Final parameters')\n\n else:\n plt.plot(angles, plot_mm_energy, label='MM validate')\n\n # Label the graph and save the pdf\n plt.title(f'Relative energy surface for dihedral {self.molecule.dihedrals[self.scan][0][0]}-'\n f'{self.molecule.dihedrals[self.scan][0][1]}-'\n f'{self.molecule.dihedrals[self.scan][0][2]}-{self.molecule.dihedrals[self.scan][0][3]}')\n plt.ylabel('Relative energy (kcal/mol)')\n plt.legend(loc=1)\n plt.savefig(f'{name}.pdf')\n plt.clf()\n\n def make_constraints(self):\n \"\"\"Write a constraint file used by geometric during optimizations.\"\"\"\n\n with open('constraints.txt', 'w+')as constraint:\n constraint.write(\n f'$scan\\ndihedral {self.molecule.dihedrals[self.scan][0][0]} {self.molecule.dihedrals[self.scan][0][1]}'\n f' {self.molecule.dihedrals[self.scan][0][2]} {self.molecule.dihedrals[self.scan][0][3]} -165.0 180 24\\n')\n\n def write_dihedrals(self):\n \"\"\"Write out the torsion drive dihedral file for the current self.scan.\"\"\"\n\n with open('dihedrals.txt', 'w+') as out:\n out.write('# dihedral definition by atom indices starting from 0\\n# i j k l\\n')\n mol_di = self.molecule.dihedrals[self.scan][0]\n out.write(f' {mol_di[0]} {mol_di[1]} {mol_di[2]} {mol_di[3]}\\n')\n\n def drive_mm(self, engine):\n \"\"\"Drive the torsion again using MM to get new structures.\"\"\"\n\n # Write an xml file with the new parameters\n\n # Move into a temporary folder torsion drive gives an error if we use tempdirectory module\n temp = f'{engine}_scan'\n try:\n rmtree(temp)\n except FileNotFoundError:\n pass\n mkdir(temp)\n chdir(temp)\n\n # Write out a pdb file of the qm optimised geometry\n self.molecule.write_pdb(name='openmm')\n # Also need an xml file for the molecule to use in geometric\n self.molecule.write_parameters(name='input')\n # openmm.pdb and input.xml are the expected names for geometric\n with open('log.txt', 'w+')as log:\n if engine == 'torsiondrive':\n self.write_dihedrals()\n completed = system('torsiondrive-launch -e openmm openmm.pdb dihedrals.txt > log.txt')\n if completed == 0:\n positions = self.get_coords(engine='torsiondrive')\n elif engine == 'geometric':\n self.make_constraints()\n sub_run('geometric-optimize --reset --epsilon 0.0 --maxiter 500 --qccnv --openmm openmm.pdb constraints.txt',\n shell=True, stdout=log)\n positions = self.get_coords(engine='geometric')\n else:\n raise NotImplementedError\n\n # move back to the master folder\n chdir('../')\n\n # return the new positions\n return positions\n\n def single_point(self):\n \"\"\"Take set of coordinates of a molecule and do a single point calculation; returns an array of the energies.\"\"\"\n\n sp_energy = []\n # for each coordinate in the system we need to write a qm input file and get the single point energy\n # TODO add progress bar (tqdm?)\n try:\n rmtree(f'Single_points')\n except FileNotFoundError:\n pass\n mkdir('Single_points')\n chdir('Single_points')\n for i, x in enumerate(self.scan_coords):\n mkdir(f'SP_{i}')\n chdir(f'SP_{i}')\n print(f'Doing single point calculations on new structures ... {i + 1}/{len(self.scan_coords)}')\n # now we need to change the positions of the molecule in the molecule array\n for y, coord in enumerate(x):\n for z, pos in enumerate(coord):\n # convert from nanometers in openmm to Angs in QM\n self.qm_engine.molecule.molecule['input'][y][z + 1] = pos * 10\n\n # Write the new coordinate file and run the calculation\n self.qm_engine.generate_input(energy=True)\n\n # Extract the energy and save to the array\n sp_energy.append(self.qm_engine.get_energy())\n\n # Move back to the base directory\n chdir('../')\n\n # move out to the main folder\n chdir('../')\n\n return array(sp_energy)\n\n def update_mol(self):\n \"\"\"When the optimisation is complete, update the PeriodicTorsionForce parameters in the molecule.\"\"\"\n\n for val in self.tor_types.values():\n for dihedral in val[0]:\n for vn in range(4):\n try:\n self.molecule.PeriodicTorsionForce[dihedral][vn][1] = str(val[1][vn])\n except KeyError:\n self.molecule.PeriodicTorsionForce[tuple(reversed(dihedral))][vn][1] = str(val[1][vn])\n\n def opls_lj(self):\n \"\"\"\n This function changes the standard OpenMM combination rules to use OPLS, execp and normal pairs are only\n required if their are virtual sites in the molecule.\n \"\"\"\n\n # Get the system information from the openmm system\n forces = {self.system.getForce(index).__class__.__name__: self.system.getForce(index) for index in\n range(self.system.getNumForces())}\n # Use the nondonded_force to get the same rules\n nonbonded_force = forces['NonbondedForce']\n lorentz = mm.CustomNonbondedForce(\n 'epsilon*((sigma/r)^12-(sigma/r)^6); sigma=sqrt(sigma1*sigma2); epsilon=sqrt(epsilon1*epsilon2)*4.0')\n lorentz.setNonbondedMethod(nonbonded_force.getNonbondedMethod())\n lorentz.addPerParticleParameter('sigma')\n lorentz.addPerParticleParameter('epsilon')\n lorentz.setCutoffDistance(nonbonded_force.getCutoffDistance())\n self.system.addForce(lorentz)\n\n l_j_set = {}\n # For each particle, calculate the combination list again\n for index in range(nonbonded_force.getNumParticles()):\n charge, sigma, epsilon = nonbonded_force.getParticleParameters(index)\n l_j_set[index] = (sigma, epsilon, charge)\n lorentz.addParticle([sigma, epsilon])\n nonbonded_force.setParticleParameters(index, charge, 0, 0)\n\n for i in range(nonbonded_force.getNumExceptions()):\n (p1, p2, q, sig, eps) = nonbonded_force.getExceptionParameters(i)\n # ALL THE 12,13 and 14 interactions are EXCLUDED FROM CUSTOM NONBONDED FORCE\n lorentz.addExclusion(p1, p2)\n if eps._value != 0.0:\n charge = 0.5 * (l_j_set[p1][2] * l_j_set[p2][2])\n sig14 = sqrt(l_j_set[p1][0] * l_j_set[p2][0])\n nonbonded_force.setExceptionParameters(i, p1, p2, charge, sig14, eps)\n # If there is a virtual site in the molecule we have to change the exceptions and pairs lists\n # Old method which needs updating\n # if excep_pairs:\n # for x in range(len(excep_pairs)): # scale 14 interactions\n # if p1 == excep_pairs[x, 0] and p2 == excep_pairs[x, 1] or p2 == excep_pairs[x, 0] and p1 == \\\n # excep_pairs[x, 1]:\n # charge1, sigma1, epsilon1 = nonbonded_force.getParticleParameters(p1)\n # charge2, sigma2, epsilon2 = nonbonded_force.getParticleParameters(p2)\n # q = charge1 * charge2 * 0.5\n # sig14 = sqrt(sigma1 * sigma2) * 0.5\n # eps = sqrt(epsilon1 * epsilon2) * 0.5\n # nonbonded_force.setExceptionParameters(i, p1, p2, q, sig14, eps)\n #\n # if normal_pairs:\n # for x in range(len(normal_pairs)):\n # if p1 == normal_pairs[x, 0] and p2 == normal_pairs[x, 1] or p2 == normal_pairs[x, 0] and p1 == \\\n # normal_pairs[x, 1]:\n # charge1, sigma1, epsilon1 = nonbonded_force.getParticleParameters(p1)\n # charge2, sigma2, epsilon2 = nonbonded_force.getParticleParameters(p2)\n # q = charge1 * charge2\n # sig14 = sqrt(sigma1 * sigma2)\n # eps = sqrt(epsilon1 * epsilon2)\n # nonbonded_force.setExceptionParameters(i, p1, p2, q, sig14, eps)\n\n return self.system\n","repo_name":"jthorton/QUBEKitdev","sub_path":"QUBEKit/dihedrals.py","file_name":"dihedrals.py","file_ext":"py","file_size_in_byte":53781,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"}
+{"seq_id":"22305859879","text":"import tkinter\r\n\r\n# 상수 선언\r\ncolor = 'black'\r\nnowcolor = \"검은색\"\r\np = 1\r\nlastx1, lasty1 = 0, 0\r\n\r\ndef painterpg():\r\n\r\n # 기본 설정\r\n painter = tkinter.Tk()\r\n painter.geometry('600x600')\r\n painter.title('그림판')\r\n painter.resizable(0, 0)\r\n\r\n # 프레임 설정\r\n frame_canvas = tkinter.Frame(painter, width = 400, height = 400, relief = \"solid\", bd = 3)\r\n frame_canvas.pack(side = \"top\")\r\n frame_label = tkinter.Frame(painter, width = 400, height = 100, relief = \"solid\", bd = 2)\r\n frame_label.pack()\r\n\r\n # 캔버스 설정\r\n\r\n # 페인트툴 설정\r\n def paint(event):\r\n global lastx1, lasty1\r\n lastx1, lasty1 = event.x, event.y\r\n x1, y1 = (event.x - p), (event.y - p)\r\n x2, y2 = (event.x + p), (event.y + p)\r\n frame_canvas.create_line(x1, y1, x2, y2, fill = color, width = p)\r\n\r\n # 색상 설정\r\n def change_black():\r\n global color\r\n color = 'black'\r\n nowcolor = \"검은색\"\r\n\r\n def change_red():\r\n global color\r\n color = 'red'\r\n nowcolor = \"빨간색\"\r\n\r\n def change_blue():\r\n global color\r\n color = 'blue'\r\n nowcolor = \"파란색\"\r\n\r\n def change_green():\r\n global color\r\n color = 'green'\r\n nowcolor = \"초록색\"\r\n\r\n def change_yellow():\r\n global color\r\n color = 'yellow'\r\n nowcolor = '노란색'\r\n\r\n # 굵기 설정\r\n def increase_p():\r\n global p\r\n p = p + 1\r\n if p > 50:\r\n p = 50\r\n\r\n def decrease_p():\r\n global p\r\n p = p - 1\r\n if p < 1:\r\n p = 1\r\n\r\n # 전체 지우기, 지우개 툴 설정\r\n def clear():\r\n canvas.delete('all')\r\n\r\n def erase():\r\n global color\r\n color = '#f0f0f0'\r\n\r\n # 메인화면으로 나가기\r\n def exit():\r\n from main_window1 import painter_main\r\n painter.destroy()\r\n painter_main()\r\n\r\n # 프레임 설정\r\n frame_canvas.bind(\"\", paint)\r\n\r\n # 라벨 설정\r\n wid_label = tkinter.Label(frame_label, text = \"굵기:\" + str(p))\r\n wid_label.pack(anchor = 'center')\r\n wid_label.place(y = 100)\r\n nowcolor_label = tkinter.Label(frame_label, text=\"붓 색깔:\" + str(nowcolor))\r\n nowcolor_label.pack()\r\n\r\n # 버튼 설정\r\n b_red = tkinter.Button(painter, bg='red', width=3, height=1, command=change_red)\r\n b_blue = tkinter.Button(painter, bg='blue', width=3, height=1, command=change_blue)\r\n b_green = tkinter.Button(painter, bg='green', width=3, height=1, command=change_green)\r\n b_yellow = tkinter.Button(painter, bg='yellow', width=3, height=1, command=change_yellow)\r\n b_black = tkinter.Button(painter, bg='black', width=3, height=1, command=change_black)\r\n b_thickup = tkinter.Button(painter, text='펜 굵기 증가', font='Arial', width=9, height=1, command=increase_p)\r\n b_thickdown = tkinter.Button(painter, text='펜 굵기 감소', font='Arial', width=9, height=1, command=decrease_p)\r\n b_eraseall = tkinter.Button(painter, text='전체 지우기', font='Arial', width=9, height=1, command=clear)\r\n b_eraser = tkinter.Button(painter, text='지우개', font='Arial', width=6, height=1, command=erase)\r\n b_mainwindow = tkinter.Button(painter, text='메인화면', font='Arial', width=9, height=1, command=exit)\r\n\r\n # 버튼 배치\r\n b_black.place(x=90, y=575)\r\n b_red.place(x=0, y=575)\r\n b_blue.place(x=30, y=575)\r\n b_green.place(x=60, y=575)\r\n b_yellow.place(x=120, y=575)\r\n b_thickup.place(x=3, y=5)\r\n b_thickdown.place(x=3, y=40)\r\n b_eraseall.place(x=507, y=5)\r\n b_eraser.place(x=0, y=530)\r\n b_mainwindow.place(x=507, y=40)\r\n\r\n painter.mainloop()\r\n","repo_name":"Quaxier/painterquaxi","sub_path":"painter1.py","file_name":"painter1.py","file_ext":"py","file_size_in_byte":3731,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"14796380557","text":"import random\n\n\ndef print_list_in_list(board: list):\n for i in board:\n print(i)\n\n\ndef validate_sudoku(board: dict):\n for current_row_id in range(9):\n for current_column_id in range(9):\n number = board[current_row_id][current_column_id]\n for column_id in range(9):\n if number == board[current_row_id][column_id]:\n return False\n for row_id in range(9):\n if number == board[row_id][current_column_id]:\n return False\n box_start_row = current_row_id // 3 * 3\n box_start_col = current_column_id // 3 * 3\n for i in range(3):\n for j in range(3):\n if board[i + box_start_row][j + box_start_col] == number:\n return False\n return True\n\n\ndef is_valid_number(number, input_column_id, input_row_id, board: dict, mode: int):\n for column_id in range(9):\n if number == board[input_row_id][column_id]:\n if mode == 0:\n return False\n else:\n return [input_row_id, column_id]\n for row_id in range(9):\n if number == board[row_id][input_column_id]:\n if mode == 0:\n return False\n else:\n return [row_id, input_column_id]\n box_start_row = input_row_id // 3 * 3\n box_start_col = input_column_id // 3 * 3\n for i in range(3):\n for j in range(3):\n if board[i + box_start_row][j + box_start_col] == number:\n if mode == 0:\n return False\n else:\n return [i + box_start_row, j + box_start_col]\n return True\n\n\ndef sudoku_solver(board: dict, numbers_solved: int):\n while numbers_solved < 81:\n row_id = random.randint(0, 8)\n column_id = random.randint(0, 8)\n if board[row_id][column_id] == \" \":\n generated_number = random.randint(1, 9)\n if is_valid_number(generated_number, column_id, row_id, board, 0):\n board[row_id][column_id] = generated_number\n numbers_solved += 1\n else:\n for z in range(1, 10):\n if is_valid_number(z, column_id, row_id, board, 0):\n board[row_id][column_id] = z\n numbers_solved += 1\n break\n else:\n coordinates = is_valid_number(generated_number, column_id, row_id, board, 1)\n board[int(coordinates[0])][int(coordinates[1])] = \" \"\n numbers_solved -= 1\n return board\n\n\nsudoku = {}\nfor rowIndex in range(9):\n rows = []\n for columnIndex in range(9):\n rows.append(\" \")\n sudoku[rowIndex] = rows\nsudoku = sudoku_solver(sudoku, 0)\nprint_dictionary(sudoku)\n","repo_name":"Michal-Miky-Jankovsky/sudoku","sub_path":"web/sudoku_web.py","file_name":"sudoku_web.py","file_ext":"py","file_size_in_byte":2856,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"45504659374","text":"import tkinter as tk\nimport algorithm as algo\nimport sys\nimport os\nfrom PIL import ImageGrab\nimport time\nimport algo_in_python as algopy\n\n\nclass Application(tk.Frame):\n def __init__(self, master=None):\n super().__init__(master)\n self.clip = False\n self.finish = False\n self.new = True\n self.folder_index = 0\n self.state = 0 # 0 : ear clipping , 1 : optical edge clipping\n self.master = master\n self.pack()\n self.create_widgets()\n\n def create_widgets(self):\n self.canvas = tk.Canvas(self, width=500, height=500, bg=\"white\")\n self.canvas.bind(\"\", self.add_point)\n self.canvas.pack()\n\n self.finish_btn = tk.Button(self, text=\"FINISH\", command=self.finish_polygon)\n self.finish_btn.pack(side=\"left\")\n\n self.redo_btn = tk.Button(self, text=\"REDO\", command=self.redo_polygon)\n self.redo_btn.pack(side=\"left\")\n\n \n\n self.clip_btn = tk.Button(self, text=\"EAR CLIP\", command=self.earclip_polygon, fg=\"red\")\n self.clip_btn.pack(side=\"right\")\n\n self.clip_btn = tk.Button(self, text=\"OPTIMAL CLIP\", command=self.optclip_polygon, fg=\"green\")\n self.clip_btn.pack(side=\"right\")\n\n self.clip_btn = tk.Button(self, text=\"SAVE\", command=self.save_result, fg=\"blue\")\n self.clip_btn.pack(side=\"right\")\n\n self.canvas.bind(\"\", self.track_mouse)\n self.line = None\n\n self.not_finish_lb = tk.Label(fg=\"black\", text=\"Please click the FINISH button first.\")\n self.less_than_2_lb = tk.Label(fg=\"black\", text=\"A polygon must have at least three points.\")\n self.save_lb = tk.Label(fg=\"black\", text=\"Please draw and clip a polygon first.\")\n self.intersect_lb = tk.Label(fg=\"black\", text=\"Polygon is self-intersecting and cannot be triangulated.\")\n\n self.points = []\n self.traingles = []\n\n def track_mouse(self, event):\n # Only track the mouse if there are points on the canvas already.\n if self.points and self.finish == False and self.clip == False:\n # If there is already a tracking line, remove it.\n if self.line is not None:\n self.canvas.delete(self.line)\n # Draw a new tracking line from the last point to the current mouse position.\n last_point = self.points[-1]\n self.line = self.canvas.create_line(last_point.x, last_point.y, event.x, event.y)\n\n def add_point(self, event):\n if self.finish == True:\n return \n if self.clip == True:\n self.points = []\n self.canvas.delete('all')\n self.clip = False\n self.finish = False\n self.clear_label()\n self.new = True\n if self.line is not None:\n self.canvas.delete(self.line)\n self.line = None\n x, y = event.x, event.y\n self.canvas.create_oval(x-2, y-2, x+2, y+2, fill='black')\n point = algo.Point()\n point.x = x\n point.y = y\n self.points.append(point)\n\n # Draw a line from the last point to the new one, but only if it's not the first point.\n if len(self.points) > 1:\n last_point = self.points[-2] # Second to last point.\n self.canvas.create_line(last_point.x, last_point.y, x, y)\n\n def finish_polygon(self):\n if self.line is not None:\n self.canvas.delete(self.line)\n if len(self.points) > 2:\n if self.less_than_2_lb.winfo_exists():\n self.less_than_2_lb.pack_forget()\n self.update_idletasks()\n x1, y1 = self.points[0].x, self.points[0].y\n x2, y2 = self.points[-1].x, self.points[-1].y\n self.canvas.create_line(x1, y1, x2, y2)\n self.finish = True\n else:\n self.less_than_2_lb.pack()\n\n def redo_polygon(self):\n self.clear_label()\n self.points = []\n self.canvas.delete('all')\n self.finish = False\n self.clip = False\n self.new = True\n if self.line is not None:\n self.canvas.delete(self.line)\n self.line = None\n\n def clear_label(self):\n if self.not_finish_lb.winfo_exists():\n self.not_finish_lb.pack_forget()\n if self.intersect_lb.winfo_exists():\n self.intersect_lb.pack_forget()\n if self.less_than_2_lb.winfo_exists():\n self.less_than_2_lb.pack_forget()\n if self.intersect_lb.winfo_exists():\n self.intersect_lb.pack_forget()\n\n def calculate_signed_area(self):\n area = 0\n n = len(self.points)\n for i in range(n):\n p1 = self.points[i]\n p2 = self.points[(i+1)%n]\n area += (p1.x * p2.y) - (p2.x * p1.y)\n return area / 2\n\n def ensure_clockwise(self):\n signed_area = self.calculate_signed_area()\n if signed_area < 0: # If the polygon is counter clockwise\n self.points.append(self.points[0])\n self.points.pop(0)\n self.points.reverse() # Reverse the order of the points\n\n return self.points\n\n def earclip_polygon(self):\n self.clear_label()\n if self.finish == False and self.state == 0:\n self.not_finish_lb.pack()\n self.update_idletasks()\n else:\n self.triangles = []\n self.points = self.ensure_clockwise()\n\n self.triangles = algo.ear_clipping(self.points)\n # self.triangles = algopy.ear_clipping(self.points)\n\n if not self.triangles:\n self.intersect_lb.pack()\n self.update_idletasks()\n else:\n self.state = 0\n self.canvas.delete('all')\n for triangle in self.triangles:\n for i in range(len(triangle)):\n x1, y1 = triangle[i].x, triangle[i].y\n x2, y2 = triangle[(i + 1) % len(triangle)].x, triangle[(i + 1) % len(triangle)].y\n self.canvas.create_line(x1, y1, x2, y2)\n\n self.save_points = self.points.copy()\n \n self.clip = True\n self.finish = False\n \n\n def optclip_polygon(self):\n self.clear_label()\n if self.finish == False and self.state == 1:\n self.not_finish_lb.pack()\n self.update_idletasks()\n else:\n self.state = 1\n self.triangles = []\n self.points = self.ensure_clockwise()\n\n self.triangles = algo.optimal_triangulation(self.points)\n\n if not self.triangles:\n self.intersect_lb.pack()\n self.update_idletasks()\n else:\n self.canvas.delete('all')\n for triangle in self.triangles:\n for i in range(len(triangle)):\n x1, y1 = triangle[i].x, triangle[i].y\n x2, y2 = triangle[(i + 1) % len(triangle)].x, triangle[(i + 1) % len(triangle)].y\n self.canvas.create_line(x1, y1, x2, y2)\n\n self.save_points = self.points.copy()\n # self.points = []\n \n self.clip = True\n self.finish = False\n\n def save_result(self):\n if self.save_lb.winfo_exists():\n self.save_lb.pack_forget()\n if self.clip == False:\n self.save_lb.pack()\n else:\n self.canvas.update_idletasks()\n # Save the image of clipped polygon\n index = 1\n if self.new == True:\n for folder in sorted(os.listdir(\"./draw\")):\n if folder == str(index):\n index += 1\n self.folder_index = index\n os.mkdir(\"./draw/\"+str(self.folder_index))\n self.new = False\n save_path = \"./draw/\" + str(self.folder_index)\n os.chdir(save_path)\n if self.state == 0:\n save_name = \"output_image_ear.png\"\n save_triangle = \"output_triangle_ear.txt\"\n else:\n save_name = \"output_image_opt.png\"\n save_triangle = \"output_triangle_opt.txt\"\n print(save_name)\n print(save_path)\n ImageGrab.grab(bbox=(self.canvas.winfo_rootx(),\n self.canvas.winfo_rooty(),\n self.canvas.winfo_rootx()+self.canvas.winfo_width(),\n self.canvas.winfo_rooty()+self.canvas.winfo_height())).save(save_name)\n\n # Save the input points\n with open('input_point.txt', 'w') as file:\n file.write(str(len(self.save_points)) + '\\n')\n for point in self.save_points:\n file.write(f'{point.x} {point.y}\\n')\n self.save_points = []\n\n # Save the output triangles\n with open(save_triangle, 'w') as file:\n file.write(str(len(self.triangles)) + '\\n')\n for triangle in self.triangles:\n for point in triangle:\n file.write(f'{point.x} {point.y}\\n')\n file.write('\\n')\n os.chdir(\"../..\")\n\ndef calculate_signed_area(polygon):\n area = 0\n n = len(polygon)\n for i in range(n):\n p1 = polygon[i]\n p2 = polygon[(i+1)%n]\n area += (p1.x * p2.y) - (p2.x * p1.y)\n return area / 2\n\ndef ensure_clockwise(polygon):\n signed_area = calculate_signed_area(polygon)\n if signed_area < 0: # If the polygon is clockwise\n polygon.append(polygon[0])\n polygon.pop(0)\n polygon.reverse() # Reverse the order of the points\n\n return polygon\n\ndef input_draw():\n root = tk.Tk()\n sw = root.winfo_screenwidth()\n sh = root.winfo_screenheight()\n\n ww = 600\n wh = 580\n\n x = (sw-ww) / 2\n y = (sh-wh) / 2\n root.geometry(\"%dx%d+%d+%d\" %(ww,wh,x,y))\n root.title(\"PolyClipper\")\n root.resizable(False, False)\n app = Application(master=root)\n app.mainloop()\n\ndef input_file():\n state = sys.argv[2]\n for folder in sorted(os.listdir(\"./file\")):\n case_folder=os.path.join(\"./file\",folder)\n print(folder)\n os.chdir(case_folder)\n if os.path.exists(\"output_point.txt\"):\n print(\"Already have output\")\n os.chdir(\"../..\")\n continue\n if os.path.exists(\"input.txt\"):\n with open(\"input.txt\", 'r') as file:\n num_points = int(file.readline().strip())\n # print(num_points)\n polygon = []\n for _ in range(num_points):\n line = file.readline().strip()\n x, y = map(int, line.split())\n point = algo.Point()\n point.x = x\n point.y = y\n polygon.append(point)\n polygon = ensure_clockwise(polygon)\n if state == 'ear':\n # start = time.time()\n triangles = algo.ear_clipping(polygon)\n # end = time.time()\n # print(f\"Time for ear clipping algo : {end - start} seconds\")\n\n elif state == 'opt':\n triangles = algo.ear_clipping(polygon)\n else:\n print(\"Not a valid algo\")\n with open('output_point.txt', 'w') as file:\n file.write(str(len(triangles)) + '\\n')\n for triangle in triangles:\n for point in triangle:\n file.write(f'{point.x} {point.y}\\n')\n file.write('\\n')\n os.chdir(\"../..\")\n print(\"Done\")\n\n\nif __name__ == '__main__':\n if len(sys.argv) > 1 and sys.argv[1] == 'file':\n input_file()\n\n else:\n input_draw()","repo_name":"jamie212/PolyClipper","sub_path":"interface.py","file_name":"interface.py","file_ext":"py","file_size_in_byte":11811,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"}
+{"seq_id":"25825170735","text":"# -*- coding: utf-8 -*-\n''' SOLVIA Verification Manual. Example A50. \n Arpack solver version.'''\n\nfrom __future__ import print_function\nfrom __future__ import division\n\nimport geom\nimport xc\n\nfrom model import predefined_spaces\nfrom solution import predefined_solutions\nfrom materials import typical_materials\n# from postprocess import output_handler\nimport math\n\n__author__= \"Luis C. Pérez Tato (LCPT)\"\n__copyright__= \"Copyright 2014, LCPT\"\n__license__= \"GPL\"\n__version__= \"3.0\"\n__email__= \"l.pereztato@gmail.com\"\n\nL= 1 # Cantilever length in meters\nb= 0.05 # Cross section width in meters\nh= 0.1 # Cross section depth in meters\nnuMat= 0.3 # Poisson's ratio.\nEMat= 2.0E11 # Young modulus en N/m2.\nespChapa= h # Thickness (m).\narea= b*espChapa # Cross section area en m2\ninertia1= 1/12.0*espChapa*b**3 # Moment of inertia in m4\ninertia2= 1/12.0*b*espChapa**3 # Moment of inertia in m4\ndens= 7800 # Density of the steel en kg/m3\nm= b*h*dens\n\nnumDiv= 10\n\n# Problem type\nfeProblem= xc.FEProblem()\npreprocessor= feProblem.getPreprocessor\nnodes= preprocessor.getNodeHandler\n\nmodelSpace= predefined_spaces.StructuralMechanics3D(nodes)\n# Define materials\nelast= typical_materials.defElasticMembranePlateSection(preprocessor, \"elast\",EMat,nuMat,dens,espChapa)\n\n# Geometry\npoints= preprocessor.getMultiBlockTopology.getPoints\npt1= points.newPoint(1, geom.Pos3d(0.0,0.0,0) )\npt2= points.newPoint(2, geom.Pos3d(b,0.0,0) )\npt3= points.newPoint(3, geom.Pos3d(b,L,0) )\npt4= points.newPoint(4, geom.Pos3d(0,L,0) )\nsurfaces= preprocessor.getMultiBlockTopology.getSurfaces\ns= surfaces.newQuadSurfacePts(1,2,3,4)\ns.nDivI= max(int(numDiv/30),1)\ns.nDivJ= numDiv\n\n# Mesh\nseedElemHandler= preprocessor.getElementHandler.seedElemHandler\nseedElemHandler.defaultMaterial= elast.name\nelem= seedElemHandler.newElement(\"ShellMITC4\",xc.ID([0,0,0,0]))\n\ns.genMesh(xc.meshDir.I)\n# Constraints\n\n\nln= preprocessor.getMultiBlockTopology.getLineWithEndPoints(pt1.tag,pt2.tag)\nlNodes= ln.nodes\nfor n in lNodes:\n n.fix(xc.ID([0,1,2,3,4,5]),xc.Vector([0,0,0,0,0,0])) # UX,UY,UZ,RX,RY,RZ\n\n# Solution procedure\nanalysis= predefined_solutions.frequency_analysis(feProblem, systemPrefix= 'band_arpack')\n#analysis= predefined_solutions.frequency_analysis(feProblem, systemPrefix= 'full_gen')\nnumModes= 2\nanalOk= analysis.analyze(numModes)\neig1= analysis.getEigenvalue(1)\neig2= analysis.getEigenvalue(2)\n\nomega1= math.sqrt(eig1)\nT1= 2*math.pi/omega1\nf1calc= 1.0/T1\nomega2= math.sqrt(eig2)\nT2= 2*math.pi/omega2\nf2calc= 1.0/T2\nperiods= [T1, T2]\n\n\nLambda= 1.87510407\nf1teor= Lambda**2/(2.0*math.pi*L**2)*math.sqrt(EMat*inertia1/m)\nratio1= abs(f1calc-f1teor)/f1teor\nf2teor= Lambda**2/(2*math.pi*L**2)*math.sqrt(EMat*inertia2/m)\nratio2= abs(f2calc-f2teor)/f2teor\n\n'''\nprint(\"omega1= \",omega1)\nprint(\"T1= \",T1)\nprint(\"f1calc= \",f1calc)\nprint(\"f1teor= \",f1teor)\nprint(\"ratio1= \",ratio1)\nprint(\"omega2= \",omega2)\nprint(\"T2= \",T2)\nprint(\"f2calc= \",f2calc)\nprint(\"f2teor= \",f2teor)\nprint(\"ratio2= \",ratio2)\n'''\n\nimport os\nfrom misc_utils import log_messages as lmsg\nfname= os.path.basename(__file__)\nif (abs(ratio2)<1e-3):\n print('test '+fname+': ok.')\nelse:\n lmsg.error(fname+' ERROR.')\n \n# #Graphic stuff.\n# oh= output_handler.OutputHandler(modelSpace)\n\n# for mode in range(1,numModes+1):\n# T= periods[mode-1]\n# f= 1.0/T\n# print('T_'+str(mode)+'= ',T, 's')\n# print('f_'+str(mode)+'= ',f, 'Hz')\n# oh.displayEigenvectors(mode)\n","repo_name":"xcfem/xc","sub_path":"verif/tests/solution/eigenvalues/eigenmodes/cantilever_eigenmodes_03.py","file_name":"cantilever_eigenmodes_03.py","file_ext":"py","file_size_in_byte":3407,"program_lang":"python","lang":"en","doc_type":"code","stars":196,"dataset":"github-code","pt":"31"}
+{"seq_id":"6121367447","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import fields, models, api\nfrom odoo.exceptions import AccessError, UserError\nimport datetime\nfrom datetime import date, datetime\n\n\nclass ProductTemplateExt(models.Model):\n _inherit = 'product.template'\n\n activate_production = fields.Boolean(string='Activate Contractual Production')\n partner_id = fields.Many2one(comodel_name='res.partner', string='Partner', required=True)\n\n\nclass AccountInvoiceExt(models.Model):\n _inherit = 'account.invoice'\n\n de_production_id = fields.Many2many(comodel_name='mrp.production', string='Production Id')\n\n\nclass MrpBomLineExt(models.Model):\n _inherit = 'mrp.bom.line'\n\n @api.onchange('product_id')\n def onchange_product_id(self):\n if self.product_id:\n self.product_uom_id = self.product_id.uom_id.id\n if self.product_id.activate_production == True:\n self.wage_price = self.product_id.list_price\n\n wage_price = fields.Float(string='Wage Price')\n\n\nclass MrpProductionExt(models.Model):\n _inherit = 'mrp.production'\n\n @api.multi\n def post_inventory(self):\n for order in self:\n print('yaseeeeeeeeeeen')\n moves_not_to_do = order.move_raw_ids.filtered(lambda x: x.state == 'done')\n moves_to_do = order.move_raw_ids.filtered(lambda x: x.state not in ('done', 'cancel'))\n for move in moves_to_do.filtered(lambda m: m.product_qty == 0.0 and m.quantity_done > 0):\n move.product_uom_qty = move.quantity_done\n moves_to_do._action_done()\n moves_to_do = order.move_raw_ids.filtered(lambda x: x.state == 'done') - moves_not_to_do\n order._cal_price(moves_to_do)\n moves_to_finish = order.move_finished_ids.filtered(lambda x: x.state not in ('done', 'cancel'))\n moves_to_finish._action_done()\n order.action_assign()\n consume_move_lines = moves_to_do.mapped('active_move_line_ids')\n for moveline in moves_to_finish.mapped('active_move_line_ids'):\n if moveline.product_id == order.product_id and moveline.move_id.has_tracking != 'none':\n if any([not ml.lot_produced_id for ml in consume_move_lines]):\n raise UserError(_('You can not consume without telling for which lot you consumed it'))\n # Link all movelines in the consumed with same lot_produced_id false or the correct lot_produced_id\n filtered_lines = consume_move_lines.filtered(lambda x: x.lot_produced_id == moveline.lot_id)\n moveline.write({'consume_line_ids': [(6, 0, [x for x in filtered_lines.ids])]})\n else:\n # Link with everything\n moveline.write({'consume_line_ids': [(6, 0, [x for x in consume_move_lines.ids])]})\n production_lines = self.env['stock.move'].search(['&', ('raw_material_production_id', '=', order.id), ('state', '=', 'done')])\n for prod in production_lines:\n if prod.product_id.activate_production == True:\n existing_bill = self.env['account.invoice'].search(['&', ('partner_id', '=', prod.product_id.partner_id.id), ('state', '=', 'draft')])\n existing_bill_lines = self.env['account.invoice.line'].search([('invoice_id', '=', existing_bill.id)])\n if existing_bill:\n self.env['account.invoice.line'].create({\n 'invoice_id': existing_bill.id,\n 'product_id': prod.product_id.id,\n 'name': 'Production Product',\n 'quantity': prod.quantity_done,\n 'account_id': 17,\n 'price_unit': prod.product_id.list_price,\n })\n else:\n journal = self.env['account.journal'].search([('name', '=', 'Vendor Bills')])\n supplier_line = {\n 'product_id': prod.product_id.id,\n 'name': 'Production Product',\n 'quantity': prod.quantity_done,\n 'account_id': 17,\n 'price_unit': prod.product_id.list_price,\n }\n record_line = {\n 'reference': order.name,\n 'partner_id': prod.product_id.partner_id.id,\n 'date_invoice': fields.Date.today(),\n 'date_due': date.today(),\n 'type': 'in_invoice',\n 'journal_id': journal.id,\n 'invoice_line_ids': [(0, 0, supplier_line)],\n }\n record = self.env['account.invoice'].create(record_line)\n # rec.bill_generated = 'true'\n return True\n\n","repo_name":"yasinjamii/de_consignment_stock","sub_path":"de_customize_ext/models/product_ext.py","file_name":"product_ext.py","file_ext":"py","file_size_in_byte":4979,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"22030971465","text":"\nimport logging\n\nimport torch\n\nfrom pyRDDLGym import RDDLEnv\nfrom pyRDDLGym import ExampleManager\nfrom pyRDDLGym.XADD.RDDLModelXADD import RDDLModelWXADD\nfrom policy_learning.DQN.agents import DQN_Agent\nfrom utils.dqn_utils import *\n\nfrom pyRDDLGym.Policies.Agents import RandomAgent\n\n\n\nparams = Params(\"./params/dqn_params_inventory.json\")\nprint('-----------------------------')\nprint(params.model_version, params.agent_type)\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\nDOMAIN_PATH = params.domain_path\nINSTANCE_PATH = params.instance_path\n\nmyEnv = RDDLEnv.RDDLEnv(domain=DOMAIN_PATH, instance=INSTANCE_PATH)\nmodel, context = get_xadd_model_from_file(f_domain=DOMAIN_PATH, f_instance=INSTANCE_PATH)\n\nagent = RandomAgent(action_space=myEnv.action_space, num_actions=myEnv.numConcurrentActions)\n\ntotal_reward = 0\nstate = myEnv.reset()\nfor step in range(myEnv.horizon):\n action = agent.sample_action()\n next_state, reward, done, info = myEnv.step(action)\n total_reward += reward\n print()\n print('step = {}'.format(step))\n print('state = {}'.format(state))\n print('action = {}'.format(action))\n print('next state = {}'.format(next_state))\n print('reward = {}'.format(reward))\n state = next_state\n if done:\n break\nprint(\"episode ended with reward {}\".format(total_reward))\nmyEnv.close()","repo_name":"jackliuto/model_diff_XADD","sub_path":"test_simulation.py","file_name":"test_simulation.py","file_ext":"py","file_size_in_byte":1371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"21731031089","text":"# coding=utf-8\n\nimport sys\nimport datetime as dt\nimport pika\n\n# 是否日志MongoDB入库\nMONGDB_ENABLE = False\n\nif MONGDB_ENABLE:\n from pymongo import MongoClient\n client = MongoClient('localhost', 27017)\n\n db = client['mqtt-log']\n mqtt_log = db['mqtt-log']\n\nINFLUXDB_ENABLE = True\nif INFLUXDB_ENABLE:\n from influxdb import InfluxDBClient\n client = InfluxDBClient('localhost', 8086, database='mqtt-log')\n # client.create_database('mqtt-log')\n\nHOST = '127.0.0.1'\nexchange_name = 'amq.topic'\nexchange_type = 'topic'\n# 如果启动多个实例,则同时绑定这个队列,表示轮询给这些实例处理\nqueue_name = 'mqtt-comsumer'\n\nbinding_keys = sys.argv[1:]\nif not binding_keys:\n print('Usage: %s [binding_key]...' % sys.argv[0])\n print(\"default binding_key='#'\")\n binding_keys = ('#',)\n\nconnection = pika.BlockingConnection(pika.ConnectionParameters(host=HOST))\n\nchannel = connection.channel()\nchannel.exchange_declare(exchange=exchange_name, exchange_type=exchange_type, durable=True)\nchannel.queue_declare(queue=queue_name)\n\n\n# binding topic\nfor binding_key in binding_keys:\n channel.queue_bind(exchange=exchange_name, queue=queue_name, routing_key=binding_key)\n\n\ndef callback(ch, method, properties, body):\n topic = method.routing_key.replace('.', '/')\n if body:\n payload = body.decode()\n else:\n payload = ''\n # print(\" [x] %r:%r\" % (topic, payload))\n\n if MONGDB_ENABLE:\n json_body = {\n 'topic': topic,\n 'payload': payload,\n 'create_datetime': dt.datetime.now()\n }\n mqtt_log.insert_one(json_body)\n\n if INFLUXDB_ENABLE:\n json_body = [{\n 'measurement': 'mqtt-log',\n # time字段,主索引,数据库会自动生成\n # 'time': dt.datetime.utcnow(),\n\n # tags:有索引的字段\n \"tags\": {\n \"topic\": topic,\n },\n\n # fileds: 没有索引的字段\n \"fields\": {\n 'payload': payload,\n }\n }]\n client.write_points(json_body)\n\n # 查询过去3s的数据\n # result = client.query(\"\"\"SELECT * FROM \"mqtt-log\" WHERE time > now() - 3s AND \"topic\"='{topic}';\"\"\".format(topic=topic))\n # print(\"Result: {0}\".format(result))\n\n\nif __name__ == \"__main__\":\n print('queue_name:' + queue_name)\n print(' [*] Waiting for {}. To exit press CTRL+C'.format(exchange_name))\n channel.basic_consume(callback, queue=queue_name, no_ack=True)\n channel.start_consuming()\n","repo_name":"AngelLiang/RabbitMQ-MQTT-Consumer-Demo","sub_path":"mqtt_consumer.py","file_name":"mqtt_consumer.py","file_ext":"py","file_size_in_byte":2554,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"74317831449","text":"import copy\nfrom typing import Any, Tuple\n\nfrom flax import linen as nn\nfrom init2winit.model_lib import base_model\nfrom init2winit.model_lib import model_utils\nfrom jax.nn import initializers\nimport jax.numpy as jnp\nfrom ml_collections.config_dict import config_dict\n\n\n# small hparams used for unit tests\nDEFAULT_HPARAMS = config_dict.ConfigDict(\n dict(\n hid_sizes=[20, 10],\n kernel_scales=[1.0, 1.0, 1.0],\n lr_hparams={\n 'base_lr': 0.1,\n 'schedule': 'constant'\n },\n layer_rescale_factors={},\n optimizer='momentum',\n opt_hparams={\n 'momentum': 0.9,\n },\n batch_size=128,\n total_accumulated_batch_size=None,\n activation_function='relu',\n l2_decay_factor=.0005,\n l2_decay_rank_threshold=2,\n label_smoothing=None,\n rng_seed=-1,\n use_shallue_label_smoothing=False,\n model_dtype='float32',\n grad_clip=None,\n ))\n\n\nclass FullyConnected(nn.Module):\n \"\"\"Defines a fully connected neural network.\n\n The model assumes the input data has shape\n [batch_size_per_device, *input_shape] where input_shape may be of arbitrary\n rank. The model flatten the input before applying a dense layer.\n \"\"\"\n num_outputs: int\n hid_sizes: Tuple[int]\n activation_function: Any\n kernel_inits: Tuple[model_utils.Initializer]\n bias_init: model_utils.Initializer = initializers.zeros\n\n @nn.compact\n def __call__(self, x, train):\n del train\n if not isinstance(self.activation_function, str):\n if len(self.activation_function) != len(self.hid_sizes):\n raise ValueError(\n 'The number of activation functions must be equal to the number '\n 'of hidden layers')\n activation_function = copy.deepcopy(self.activation_function)\n else:\n activation_function = [self.activation_function] * len(self.hid_sizes)\n\n x = jnp.reshape(x, (x.shape[0], -1))\n for i, (num_hid, init) in enumerate(\n zip(self.hid_sizes, self.kernel_inits[:-1])):\n x = nn.Dense(num_hid, kernel_init=init, bias_init=self.bias_init)(x)\n x = model_utils.ACTIVATIONS[activation_function[i]](x)\n x = nn.Dense(\n self.num_outputs,\n kernel_init=self.kernel_inits[-1],\n bias_init=self.bias_init)(x)\n return x\n\n\n# pylint: disable=missing-class-docstring\nclass FullyConnectedModel(base_model.BaseModel):\n \"\"\"Model class for fully connected model.\"\"\"\n\n def build_flax_module(self):\n kernel_inits = [\n initializers.variance_scaling(scale, 'fan_in', 'truncated_normal')\n for scale in self.hps.kernel_scales\n ]\n return FullyConnected(\n num_outputs=self.hps['output_shape'][-1],\n hid_sizes=tuple(self.hps.hid_sizes),\n activation_function=self.hps.activation_function,\n kernel_inits=tuple(kernel_inits))\n\n def get_fake_inputs(self, hps):\n \"\"\"Helper method solely for the purpose of initialzing the model.\"\"\"\n dummy_inputs = [\n jnp.zeros((hps.batch_size, *hps.input_shape), dtype=hps.model_dtype)\n ]\n return dummy_inputs\n","repo_name":"google/init2winit","sub_path":"init2winit/model_lib/fully_connected.py","file_name":"fully_connected.py","file_ext":"py","file_size_in_byte":3080,"program_lang":"python","lang":"en","doc_type":"code","stars":66,"dataset":"github-code","pt":"31"}
+{"seq_id":"12258093956","text":"\n\nimport os\n\nfileName = input(\"Enter a filename: \")\n\ninFile = open(fileName, \"r\")\n\ndirName = input(\"Enter a name for the output directory: \")\n\npathToTempDir = \"/mu2e/app/users/bbarton/CrBkgEstims/SubmissionScripts/Fcl_files/\" + dirName + \"/\"\n\nos.system(\"mkdir \" + pathToTempDir)\n\nfor line in inFile.readlines():\n os.system(\"cp \" + line[:-42] + \"/\" + line[-42:-1] + \" \" + pathToTempDir)\n\nos.system(\"cd \" + pathToTempDir)\n\nfileList = os.listdir()\n\nprint(fileList)\n\n\n#appendLine = \"physics.analyzers.digiCompressionCheck.checkTrackerDuplicateSteps : false\"\n#outDirPath = \"/pnfs/mu2e/scratch/users/bbarton/workflow/\" + dirName +\"/\"\n#for fNum in range(len(fileList)):\n# f = open(fileList[fNum], \"a\")\n# f.write(appendLine)\n# f.close()\n\n# os.system(\"cp \" + fileList[fNum] + \" \" + outDirPath)\n\n\n\n \n","repo_name":"99bbarton/CrBkgEstims","sub_path":"SubmissionScripts/ListBuildingScripts/cpDuplicateFailFcl.py","file_name":"cpDuplicateFailFcl.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"73224047128","text":"from __future__ import print_function\nimport sys, os\n\nprint(\"\\xef\\xbb\\xbf\")\n\nscript_dir = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))\nprint('script_dir = ' + script_dir)\nos.chdir(script_dir)\nimport pywinauto\n\napp = pywinauto.Application().start_(os.path.join(script_dir, r\"apps\\MFC_tutorial\\MFC_Tutorial9.exe\"))\nprint('started')\ndlg = app.MFC_Tutorial9\n\ndlg.TypeYourTextEdit.TypeKeys('qqq')\ndlg.Add.Click()\n\ndlg.TypeYourTextEdit.Select()\ndlg.TypeYourTextEdit.TypeKeys('123')\ndlg.Add.Click()\n\ndlg.TypeYourTextEdit.Select()\ndlg.TypeYourTextEdit.TypeKeys('third item', with_spaces=True)\ndlg.Add.Click()\n\nctrl = dlg.ListBox.WrapperObject()","repo_name":"pywinauto/pywinauto-sandbox","sub_path":"debugging/test_ListBox_MFC.py","file_name":"test_ListBox_MFC.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"}
+{"seq_id":"38905917210","text":"\r\nimport dlib\r\nimport face_detect_utils\r\n# pylint: disable=invalid-name12\r\npath = r\"E:\\untitled3\\venv\\Digital\\dataset\\FaceDataSets\"\r\nimport os\r\nimport random\r\nimport numpy as np\r\nimport cv2\r\ndlib_face_detector = dlib.get_frontal_face_detector()\r\n\r\ndef createdir_120(*args):\r\n ''' create dir'''\r\n for item in args:\r\n if not os.path.exists(item):\r\n os.makedirs(item)\r\n\r\nIMGSIZE = 128\r\n\r\ndef getpaddingSize_120(shape):\r\n ''' get size to make image to be a square rect '''\r\n h, w = shape\r\n longest = max(h, w)\r\n result = (np.array([longest]*4, int) - np.array([h, h, w, w], int)) // 2\r\n return result.tolist()\r\n\r\ndef dealwithimage_120(img, h=64, w=64):\r\n ''' dealwithimage '''\r\n #img = cv2.imread(imgpath)\r\n top, bottom, left, right = getpaddingSize(img.shape[0:2])\r\n img = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=[0, 0, 0])\r\n img = cv2.resize(img, (h, w))\r\n return img\r\n\r\ndef relight_120(imgsrc, alpha=1, bias=0):\r\n '''relight'''\r\n imgsrc = imgsrc.astype(float)\r\n imgsrc = imgsrc * alpha + bias\r\n imgsrc[imgsrc < 0] = 0\r\n imgsrc[imgsrc > 255] = 255\r\n imgsrc = imgsrc.astype(np.uint8)\r\n return imgsrc\r\n\r\ndef getfacefromcamera_120(outdir,name,laber):\r\n createdir_120(outdir)\r\n camera = cv2.VideoCapture(0)\r\n haar = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\r\n n = 1\r\n while 1:\r\n if (n <= 50):\r\n print('It`s processing %s image.' % n)\r\n # 读帧-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+\r\n success, img = camera.read()\r\n #-------------------------------------\r\n\r\n # cv2.imshow(\"capture\", frame)\r\n\r\n # if len(dlib_face_detector(frame, 1)) != 0:\r\n # cv2.imwrite((picPath + \"\\\\\" + str(self.num) + '_' + str(self.n) + \".bmp\"), image)\r\n # print((picPath + \"\\\\\" + str(self.num) + '_' + str(self.n) + \".bmp\"))\r\n #\r\n #--------------------------------\r\n\r\n\r\n gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n faces = haar.detectMultiScale(gray_img, 1.3, 5)\r\n # faces = face_detect_utils.detect_and_label(img)\r\n for f_x, f_y, f_w, f_h in faces:\r\n #could deal with face to train12\r\n if len(dlib_face_detector(img, 1)) != 0 :\r\n # img = face_detect_utils.detect_and_label(img)\r\n face = img[f_y:f_y + f_h, f_x:f_x + f_w]\r\n face = cv2.resize(face, (IMGSIZE, IMGSIZE))\r\n face = relight_120(face, random.uniform(0.5, 1.5), random.randint(-50, 50))\r\n cv2.imwrite(os.path.join(outdir, laber+'_'+name+str(n)+'.bmp'), face)\r\n cv2.putText(img, 'text', (f_x, f_y - 20), cv2.FONT_HERSHEY_SIMPLEX, 1, 255, 2) #显示名字\r\n img = cv2.rectangle(img, (f_x, f_y), (f_x + f_w, f_y + f_h), (255, 0, 0), 2)\r\n n+=1\r\n cv2.imshow('img', img)\r\n key = cv2.waitKey(30) & 0xff\r\n if key == 27:\r\n break\r\n else:\r\n break\r\n camera.release()\r\n cv2.destroyAllWindows()\r\n\r\nif __name__ == '__main__':\r\n name = input('please input your name: ')\r\n laber=input('please input your number: ')\r\n getfacefromcamera_120(os.path.join(path, name),name,laber)","repo_name":"zhongxiaj/Face_recognizitioan","sub_path":"getmypic_120.py","file_name":"getmypic_120.py","file_ext":"py","file_size_in_byte":3579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"11421533455","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n/***************************************************************************\n Chole\n A QGIS plugin\n description\n -------------------\n begin : 2017-10-17\n author : Jean-Charles Naud, Olivier Bedel, Hugues Boussard\n\n email : hugues.boussard at inra.fr\n ***************************************************************************/\n\n\"\"\"\n\nfrom builtins import str\n__author__ = 'Jean-Charles Naud/Alkante'\n__date__ = '2017-10-17'\n\n\n# This will get replaced with a git SHA1 when you do a git archive\n\n__revision__ = '$Format:%H$'\n\nimport os\nimport glob\n\nfrom qgis.core import (\n QgsProcessingAlgorithm,\n QgsProcessingParameterVectorLayer,\n QgsProcessingParameterRasterLayer,\n QgsProcessingParameterMultipleLayers,\n QgsProcessingParameterField,\n QgsProcessingParameterNumber,\n QgsProcessingParameterBoolean,\n QgsProcessingParameterString,\n QgsProcessingParameterFeatureSource,\n QgsProcessingParameterFile,\n QgsProcessingParameterEnum,\n QgsProcessingOutputVectorLayer,\n QgsProcessingOutputRasterLayer,\n QgsProcessingOutputFolder,\n QgsProcessingParameterFileDestination,\n QgsProcessingParameterFolderDestination,\n QgsProcessingParameterRasterDestination,\n QgsProcessingOutputFolder,\n QgsProcessingFeedback\n)\n\nfrom processing.tools.system import getTempFilename, isWindows, isMac\nfrom time import gmtime, strftime\nfrom ..ChloeUtils import ChloeUtils\n\n\n# Mother class\nfrom ..chloe_algorithm import ChloeAlgorithm\nfrom ..chloe_algorithm_dialog import ChloeParameterFolderDestination\n\nclass SlidingMultiAlgorithm(ChloeAlgorithm):\n \"\"\"Algorithm sliding multi.\"\"\"\n\n def __init__(self):\n super().__init__()\n\n # def getCustomParametersDialog(self):\n # \"\"\"Define Dialog associed with this algorithm\"\"\"\n # return SlidingMultiAlgorithmDialog(self)\n\n def initAlgorithm(self, config=None):\n # === INPUT PARAMETERS ===\n inputAscParam = QgsProcessingParameterRasterLayer(\n name=self.INPUT_LAYER_ASC,\n description=self.tr('Input layer asc'))\n\n inputAscParam.setMetadata({\n 'widget_wrapper': {\n 'class': 'Chloe.chloe_algorithm_dialog.ChloeAscRasterWidgetWrapper'\n }\n })\n self.addParameter(inputAscParam)\n\n # ANALYZE TYPE\n\n analyzeTypeParam = QgsProcessingParameterEnum(\n name=self.ANALYZE_TYPE,\n description=self.tr('Analyze type'),\n options=self.types_of_analyze)\n\n analyzeTypeParam.setMetadata({\n 'widget_wrapper': {\n 'class': 'Chloe.chloe_algorithm_dialog.ChloeEnumUpdateStateWidgetWrapper',\n 'dependantWidgetConfig': [{ \n 'paramName': self.DISTANCE_FUNCTION, \n 'enableValue': 1\n }]\n }\n })\n\n self.addParameter(analyzeTypeParam)\n\n # DISTANCE FUNCTION\n\n self.addParameter(QgsProcessingParameterString(\n name=self.DISTANCE_FUNCTION,\n description=self.tr('Distance function'),\n optional=True))\n\n windowShapeParam = QgsProcessingParameterEnum(\n name=self.WINDOW_SHAPE,\n description=self.tr('Window shape'),\n options=self.types_of_shape)\n\n windowShapeParam.setMetadata({\n 'widget_wrapper': {\n 'class': 'Chloe.chloe_algorithm_dialog.ChloeEnumUpdateStateWidgetWrapper',\n 'dependantWidgetConfig': [{ \n 'paramName': self.FRICTION_FILE, \n 'enableValue': 2\n }]\n }\n })\n\n self.addParameter(windowShapeParam)\n\n self.addParameter(QgsProcessingParameterFile(\n name=self.FRICTION_FILE,\n description=self.tr('Friction file'),\n optional=True))\n\n windowSizeParam = QgsProcessingParameterString(\n name=self.WINDOW_SIZES,\n description=self.tr('Windows sizes (pixels)')) # [constraint V2.0: \"select only one\"]\n \n windowSizeParam.setMetadata({\n 'widget_wrapper': {\n 'class': 'Chloe.chloe_algorithm_dialog.ChloeIntListWidgetWrapper',\n 'initialValue': 3,\n 'minValue' : 3,\n 'maxValue' : 100001,\n 'oddNum' : True\n }\n })\n \n self.addParameter(windowSizeParam)\n \n self.addParameter(QgsProcessingParameterNumber(\n name=self.DELTA_DISPLACEMENT,\n description=self.tr('Delta displacement (pixels)'),\n defaultValue=1,\n minValue=1))\n\n self.addParameter(QgsProcessingParameterBoolean(\n name=self.INTERPOLATE_VALUES_BOOL,\n description=self.tr('Interpolate Values'),\n defaultValue=False))\n\n fieldsParam = QgsProcessingParameterString(\n name=self.FILTER,\n description=self.tr('Filters - Analyse only'),\n defaultValue='',\n optional=True)\n fieldsParam.setMetadata({\n 'widget_wrapper': {\n 'class': 'Chloe.chloe_algorithm_dialog.ChloeValuesWidgetWrapper'\n }\n })\n self.addParameter(fieldsParam)\n\n fieldsParam = QgsProcessingParameterString(\n name=self.UNFILTER,\n description=self.tr('Filters - Do not analyse'),\n defaultValue='',\n optional=True)\n fieldsParam.setMetadata({\n 'widget_wrapper': {\n 'class': 'Chloe.chloe_algorithm_dialog.ChloeValuesWidgetWrapper'\n }\n })\n self.addParameter(fieldsParam)\n\n self.addParameter(QgsProcessingParameterNumber(\n name=self.MAXIMUM_RATE_MISSING_VALUES,\n description=self.tr('Maximum rate of missing values'),\n minValue=0,\n maxValue=100,\n defaultValue=100))\n\n metricsParam = QgsProcessingParameterString(\n name=self.METRICS,\n description=self.tr('Select metrics'))\n\n metricsParam.setMetadata({\n 'widget_wrapper': {\n 'class': 'Chloe.chloe_algorithm_dialog.ChloeMultipleMetricsSelectorWidgetWrapper',\n 'dictValues': self.types_of_metrics,\n 'initialValue': 'value metrics',\n 'rasterLayerParamName': self.INPUT_LAYER_ASC,\n 'parentWidgetConfig': { 'paramName': self.INPUT_LAYER_ASC, 'refreshMethod': 'refreshMetrics'}\n }\n })\n \n self.addParameter(metricsParam)\n\n # === OUTPUT PARAMETERS ===\n \n self.addParameter(ChloeParameterFolderDestination(\n name=self.OUTPUT_DIR,\n description=self.tr('Output directory')))\n\n self.addParameter(QgsProcessingParameterFileDestination(\n name=self.SAVE_PROPERTIES,\n description=self.tr('Properties file'),\n fileFilter='Properties (*.properties)'))\n\n def name(self):\n return 'sliding multi'\n\n def displayName(self):\n return self.tr('sliding multi')\n\n def group(self):\n return self.tr('landscape metrics')\n\n def groupId(self):\n return 'landscapemetrics'\n\n def commandName(self):\n return 'sliding multi'\n\n def PreRun(self, parameters, context, feedback, executing=True):\n \"\"\"Here is where the processing itself takes place.\"\"\"\n\n # === INPUT\n self.input_layer_asc = self.parameterRasterAsFilePath(\n parameters, self.INPUT_LAYER_ASC, context)\n\n self.window_shape = self.types_of_shape[\n self.parameterAsInt(parameters, self.WINDOW_SHAPE, context)]\n self.friction_file = self.parameterAsString(\n parameters, self.FRICTION_FILE, context)\n self.window_sizes = self.parameterAsString(\n parameters, self.WINDOW_SIZES, context)\n\n self.analyze_type = self.types_of_analyze[\n self.parameterAsInt(parameters, self.ANALYZE_TYPE, context)]\n\n self.distance_formula = self.parameterAsString(parameters, self.DISTANCE_FUNCTION, context)\n\n self.delta_displacement = self.parameterAsInt(\n parameters, self.DELTA_DISPLACEMENT, context)\n self.b_interpolate_values = self.parameterAsBool(\n parameters, self.INTERPOLATE_VALUES_BOOL, context)\n\n self.filter = self.parameterAsString(\n parameters, self.FILTER, context)\n self.unfilter = self.parameterAsString(\n parameters, self.UNFILTER, context)\n\n self.maximum_rate_missing_values = self.parameterAsInt(\n parameters, self.MAXIMUM_RATE_MISSING_VALUES, context)\n self.metrics = self.parameterAsString(\n parameters, self.METRICS, context)\n\n # === OUTPUT\n self.output_dir = self.parameterAsString(\n parameters, self.OUTPUT_DIR, context)\n ChloeUtils.adjustTempDirectory(self.output_dir)\n\n base_in = os.path.basename(self.input_layer_asc)\n name_in = os.path.splitext(base_in)[0]\n ext_in = os.path.splitext(base_in)[1]\n\n # === SAVE_PROPERTIES\n f_save_properties = self.parameterAsString(\n parameters, self.SAVE_PROPERTIES, context)\n\n if f_save_properties:\n self.f_path = f_save_properties\n else:\n if not self.f_path:\n self.f_path = getTempFilename(ext=\"properties\")\n\n # === Properties file\n self.createPropertiesTempFile()\n\n # === output filenames\n self.deduceOutputFilenames()\n\n def createPropertiesTempFile(self):\n \"\"\"Create Properties File\"\"\"\n\n s_time = strftime(\"%Y-%m-%d %H:%M:%S\", gmtime())\n with open(self.f_path, \"w\") as fd:\n fd.write(\"#\"+s_time+\"\\n\")\n\n fd.write(\"treatment=sliding\\n\")\n fd.write(ChloeUtils.formatString(\n 'input_ascii=' + self.input_layer_asc+\"\\n\", isWindows()))\n\n fd.write(ChloeUtils.formatString(\n 'output_folder=' + self.output_dir + \"\\n\", isWindows()))\n\n fd.write(\"window_sizes={\" + self.window_sizes + \"}\\n\")\n fd.write(\"maximum_nodata_value_rate=\"\n + str(self.maximum_rate_missing_values) + \"\\n\")\n \n if self.analyze_type == \"weighted distance\":\n fd.write(\"distance_function=\" + str(self.distance_formula))\n\n fd.write(\"metrics={\" + self.metrics + \"}\\n\")\n fd.write(\"delta_displacement=\"\n + str(self.delta_displacement) + \"\\n\")\n fd.write(\"shape=\" + str(self.window_shape) + \"\\n\")\n if self.window_shape == \"FUNCTIONAL\":\n fd.write(\"friction_map=\" + self.friction_file + \"\\n\")\n\n if self.b_interpolate_values:\n fd.write(\"interpolation=true\\n\")\n else:\n fd.write(\"interpolation=false\\n\")\n\n if self.filter:\n fd.write(\"filters={\" + self.filter + \"}\\n\")\n if self.unfilter:\n fd.write(\"unfilters={\" + self.unfilter + \"}\\n\")\n\n fd.write(\"visualize_ascii=false\\n\")\n\n fd.write(\"export_csv=true\\n\")\n fd.write(\"export_ascii=true\\n\")\n\n def deduceOutputFilenames(self):\n self.outputFilenames = []\n baseOutAsc = os.path.basename(self.input_layer_asc)\n radical = os.path.splitext(baseOutAsc)[0]\n for ws in self.window_sizes:\n for m in self.metrics.split(';'):\n fName = radical + \"_\" + str(self.types_of_shape_abrev[self.window_shape]) + \"_w\" + str(ws) + \"_\" + str(m) + \"_d_\" + str(self.delta_displacement) + \".asc\"\n fFullName = self.output_dir + os.sep + fName\n self.outputFilenames.append(fFullName)","repo_name":"hboussard/chloe_qgis","sub_path":"algorithms/sliding_multi_algorithm.py","file_name":"sliding_multi_algorithm.py","file_ext":"py","file_size_in_byte":11864,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"}
+{"seq_id":"1930183272","text":"from Orange.classification import LogisticRegressionLearner\nfrom Orange.data import table_to_frame\nfrom Orange.widgets.widget import OWWidget, Input, Output\nfrom Orange.data.table import Table\nimport numpy as np\nimport pandas as pd\nfrom scipy.optimize import minimize\nfrom PyQt5.QtCore import Qt\nfrom Orange.widgets import gui, settings\n\nfrom fairness.widgets.table_model import TableModel\n\n\nclass FairSVM(OWWidget):\n name = \"Fair SVM\"\n icon = \"icons/fair_svm_icon.png\"\n\n Thresholds = [-0.5, 0, 0.5]\n t = settings.Setting(1)\n\n want_main_area = False\n\n def __init__(self):\n super().__init__()\n # inputs\n self.y = None\n self.s = None\n self.y_pred = None\n self.X = None\n\n self.box = gui.vBox(self.controlArea, \"Threshold\")\n\n gui.comboBox(\n self.box, self, \"t\",\n items=[str(x) for x in self.Thresholds],\n orientation=Qt.Horizontal, callback=self.zafar_svm)\n\n class Inputs:\n s = Input(\"Sensitive attribute\", Table)\n y = Input(\"Target attribute\", Table)\n X = Input(\"Feature attributes\", Table)\n\n @Inputs.X\n def set_X(self, X):\n \"\"\"Set the input X.\"\"\"\n self.X = X\n self.zafar_svm()\n\n @Inputs.s\n def set_s(self, s):\n \"\"\"Set the input s.\"\"\"\n self.s = s\n self.zafar_svm()\n\n @Inputs.y\n def set_y(self, y):\n \"\"\"Set the input y.\"\"\"\n self.y = y\n self.zafar_svm()\n\n class Outputs:\n coefficients = Output(\"Coefficients\", Table, explicit=True)\n algorithm = Output('Algorithm', str)\n\n def zafar_svm(self):\n def hinge_loss(w, X, y):\n yz = y * np.dot(X, w)\n yz = np.maximum(np.zeros_like(yz), (1 - yz)) # hinge function\n\n return np.mean(yz)\n\n def avg_disp_imp_upper(w, X_0, X_1, y_0, y_1, z_1, z_0, t):\n y_intensity = t + z_1 / z * hinge_loss(w, X_1, y_1) - z_0 / z * hinge_loss(w, X_0, y_0)\n\n return y_intensity\n\n def avg_disp_imp_lower(w, X_0, X_1, y_0, y_1, z_1, z_0, t):\n y_intensity = -z_1 / z * hinge_loss(w, X_1, y_1) + z_0 / z * hinge_loss(w, X_0, y_0) + t\n\n return y_intensity\n if self.s is not None and self.y is not None and self.X is not None:\n\n s = table_to_frame(self.s).iloc[:, 0]\n y = table_to_frame(self.y).iloc[:, 0]\n X = table_to_frame(self.X)\n\n z_1 = len(s[s == 1])\n z_0 = len(s[s == 0])\n z = len(s)\n\n y_0 = y[s == 0]\n y_1 = y[s == 1]\n\n X_0 = X[s == 0]\n X_1 = X[s == 1]\n\n w_0 = np.repeat(0, X.shape[1])\n\n t = self.Thresholds[self.t]\n\n cons = ({'type': 'ineq', 'fun': avg_disp_imp_lower, 'args': (X_0, X_1, y_0, y_1, z_1, z_0, t)},\n {'type': 'ineq', 'fun': avg_disp_imp_upper, 'args': (X_0, X_1, y_0, y_1, z_1, z_0, t)})\n\n model = minimize(fun=hinge_loss, x0=w_0, args=(X, y),\n method='SLSQP', constraints=cons)\n\n self.Outputs.coefficients.send(model.x)\n self.Outputs.algorithm.send('SVM')","repo_name":"sanjarancic/Orange3_Fairness_Add_ons","sub_path":"fairness/widgets/in_processing_fair_svm.py","file_name":"in_processing_fair_svm.py","file_ext":"py","file_size_in_byte":3149,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"21667913012","text":"# Databricks notebook source\n# MAGIC %md # Databricks Utilities \n# MAGIC > Tools for use within databricks notebooks. \n\n# COMMAND ----------\n\n#| default_exp databricksUtils\n\n# COMMAND ----------\n\n#| hide\nfrom nbdev import *\n\n# COMMAND ----------\n\n#| export\n\nimport pytz\n\nfrom datetime import datetime\n\nimport re\n\n# COMMAND ----------\n\n#| export\n\ndef dump_data_to_disk(df, file_stem, databricks_url='https://ie-meta-prod-databricks-workspace.cloud.databricks.com', sep='\\t'):\n ''' \n Save a Pandas's Dataframe to disk and returns a URL where you can download it\n \n `file_stem`: the location to save the file in the databricks file system. String must start with '/dbfs/FileStore/'\n `databricks_url`: is the URL for the Databricks environment being used. Defaults to the CZI workspace. \n '''\n if sep=='\\t':\n suffix = '.tsv'\n elif sep==',':\n suffix = '.csv'\n else:\n raise Exception('separator must be either a TAB or COMMA')\n tz = pytz.timezone('America/Los_Angeles')\n now = datetime.now(tz=tz)\n datestamp = now.strftime(\"%Y_%m_%d\")\n data_path = file_stem+datestamp+suffix\n df = df.replace(r'\\\\\\\\n', ' ', regex=True)\n df.to_csv(data_path, sep=sep, index=False)\n databricks_stem = databricks_url + '/files/'\n url = re.sub('/dbfs/FileStore/', databricks_stem, data_path)\n name = file_stem\n name_match = re.search('/([a-zA-Z0-9_]+)_*$', file_stem)\n if name_match:\n name = name_match.group(1)\n\n return url\n","repo_name":"chanzuckerberg/czLandscapingTk","sub_path":"databricks/utils/00_databricks_utils.py","file_name":"00_databricks_utils.py","file_ext":"py","file_size_in_byte":1431,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"}
+{"seq_id":"3466159737","text":"import numpy as np\nimport pandas as pd\nimport pickle\nimport json\n# from IPython.display import display\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom flask import Flask\nfrom flask import request\nfrom flask import jsonify\nfrom db_class import StorageDatabase\nfrom prediction import model\n\n# db = StorageDatabase(\"sql11.freemysqlhosting.net\",\"3306\",\"sql11593194\",\"sql11593194\",\"2CPjwjQHDQ\")\n# df_NYC = pd.read_sql(\"SELECT * FROM NYC\", db.__connection__)\n# df_MSK = pd.read_sql(\"SELECT * FROM MSK\", db.__connection__)\n# df_TLV = pd.read_sql(\"SELECT * FROM TLV\", db.__connection__)\n# db.__connection__.close()\ndf_NYC = pd.read_csv('NYC.csv')\ndf_TLV = pd.read_csv('TLV.csv')\ndf_MSK = pd.read_csv('MSK.csv')\n\ncity_data = {'TLV' : df_TLV, 'MSK' : df_MSK, 'NYC' : df_NYC}\n\n# df_TLV.to_csv('TLV.csv')\n# df_MSK.to_csv('MSK.csv')\n# df_NYC.to_csv('NYC.csv')\n\n\n\nFEATURES = ['is_male','num_inters','late_on_payment','age','years_in_contract']\n# Reading datafiles\nwith open('churn_model.pkl', 'rb') as file:\n clf = pickle.load(file)\n\nfeatures = FEATURES\n\napp = Flask(__name__)\n\n\n# Individual prediction\n@app.route('/')\ndef get_prediction():\n try:\n observation = pd.DataFrame()\n for feature in features:\n observation[feature] = [float(request.args.get(feature))]\n prediction = str(clf.predict(observation)[0])\n return f\"Predicted value of churn: {prediction}\"\n except:\n return\n\n#Bulk prediction\n@app.route('/predict_churn_bulk',methods=['POST'])\ndef get_bulk_predictions():\n try:\n observations = pd.DataFrame(json.loads(request.get_json()))\n result = {'Prediction' : list(clf.predict(observations).astype(str))}\n return jsonify(result)\n except:\n return\n\n@app.route(\"/get_event\")\ndef get_event():\n try:\n event_id = (request.args.get(\"event_id\"))\n home_city = request.args.get(\"home_city\")\n target_city = request.args.get(\"target_city\")\n\n print(f\"Home {home_city} Target {target_city} ID {event_id}\")\n\n dfr = city_data[home_city]\n sample_text = dfr.loc[int(event_id), 'description']\n\n print(sample_text[:10])\n result = model(city_data[target_city], sample_text, 20)[['id', 'similarity_percentage']]\n data = result.sort_values('similarity_percentage', ascending=False)\n data = data.to_dict(orient='records')\n print(data)\n return jsonify(data)\n except:\n return\n\napp.run(host='0.0.0.0', port=3000)\n#app.run()\n\n\n","repo_name":"astrinleonid/flask_test","sub_path":"inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":2485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"29147525261","text":"# Python 2 and 3\nfrom __future__ import unicode_literals\n\nfrom ..base import Resource\n\n\nclass BaseTransaction(Resource):\n _is_listable = False\n\n _as_is_fields = ['id', 'href', 'status', 'transaction_type', 'error']\n _date_time_fields_utc = ['date_created', 'date_last_modified']\n _price_fields = ['amount']\n _resource_fields = [\n ('booking', 'Booking'),\n ]\n\n\nclass Refund(BaseTransaction):\n _resource_name = 'refunds'\n _price_fields = ['amount', 'commission']\n\n\nclass Payment(BaseTransaction):\n _resource_name = 'payments'\n","repo_name":"gadventures/gapipy","sub_path":"gapipy/resources/booking/transaction.py","file_name":"transaction.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"}
+{"seq_id":"29196908367","text":"from decision_tree.base import DecisionTree\n\n\nclass ClassificationTree(DecisionTree):\n def __init__(\n self,\n is_target_categorical=True,\n max_depth=None,\n min_samples_split=None,\n min_information_gain=1e-10,\n max_categories=20,\n ):\n super().__init__(\n is_target_categorical,\n max_depth,\n min_samples_split,\n min_information_gain,\n max_categories,\n )\n","repo_name":"moseskimc/decision-tree","sub_path":"src/decision_tree/classification.py","file_name":"classification.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"30023042254","text":"import boto3\ndef main():\n client= boto3.resource('dynamodb', region_name='us-east-1')\n\n table = client.create_table(\n TableName='AustGames',\n KeySchema=[\n {\n 'AttributeName': 'gid',\n 'KeyType': 'HASH' #Partition key\n },\n ],\n AttributeDefinitions=[\n\n {\n 'AttributeName': 'gid',\n 'AttributeType':'N'\n },\n\n\n ],\n ProvisionedThroughput={\n 'ReadCapacityUnits': 10,\n 'WriteCapacityUnits': 10\n }\n \n )\n\n # inserting data into dynamodb\n\n table=client.Table(\"AustGames\")\n\n response=table.put_item( Item={ 'gid':1, 'gname': \"Mario\", 'publisher':'nintando','rating': 20 , 'release_date' : '2001', 'genres': { 'info':\"\"}\n })\n\n response1=table.put_item( Item={ 'gid':2, 'gname': \"PubG\", 'publisher':'Tencent','rating': 200 , 'release_date' : '2019', 'genres': { 'info':\"\"}\n })\n response2=table.put_item( Item={ 'gid':3, 'gname': \"Fifa19\", 'publisher':'EA-Sports','rating': 20 , 'release_date' : '2019', 'genres': { 'info':\" \"}\n })\n\nif __name__=='__main__':\n main()\n","repo_name":"Austin306/AWS_Assignment","sub_path":"ques9.py","file_name":"ques9.py","file_ext":"py","file_size_in_byte":1165,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"35474270681","text":"from django.urls import path\r\nfrom . import views\r\n\r\napp_name = \"core_app\"\r\n\r\n\r\nurlpatterns = [\r\n path('', views.index, name='index'),\r\n path('about/', views.about, name='about'),\r\n path('contact/', views.contact, name='contact'),\r\n path('properties/', views.properties, name='list'),\r\n path('search/', views.properties, name='search'),\r\n path('post/', views.post_prop, name='post'),\r\n path(\"property//\", views.property_detail, name=\"property\"),\r\n path(\"inquiry/\", views.inquiry, name=\"inquiry\"),\r\n path(\"queries/\", views.queries, name=\"queries\"),\r\n]\r\n","repo_name":"teknathbh/realEstate","sub_path":"core_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"71344442967","text":"from io import BytesIO\n\nimport pandas as pd\nfrom PIL import Image\n\nfrom airbnb_oslo.helpers.pytorch_helpers import show_images\n\n\ndef open_image(response):\n try:\n img = Image.open(BytesIO(response.content))\n except Exception:\n img = pd.NA\n return img\n\n\ndef main() -> None:\n listings_df = pd.read_pickle(\"../../data/clean/listings.pkl\")\n front_page_responses = pd.read_pickle(\"../../data/clean/front_page_responses.pkl\")\n cnn_pretrained_predictions = pd.read_pickle(\n \"../../data/clean/cnn_pretrained_predictions.pkl\"\n )\n\n response_price_df = (\n pd.merge(\n front_page_responses,\n listings_df[\"price\"],\n left_index=True,\n right_index=True,\n )\n .assign(\n cnn_pretrained_predictions=cnn_pretrained_predictions.groupby(\n cnn_pretrained_predictions.index\n ).mean()\n )\n .rename(columns={\"listing_url\": \"front_page_responses\"})\n .loc[lambda x: (x[\"price\"] > 0) & (x[\"price\"] < 80000)]\n .dropna()\n )\n\n response_price_df = response_price_df.assign(\n front_page_pictures=response_price_df[\"front_page_responses\"].apply(open_image)\n ).dropna()\n\n # SUBSECTION: Small Image with 2x2 Grid\n # choose random images from dataset\n sample_obs = response_price_df.sample(n=4)\n\n show_images(\n images=sample_obs[\"front_page_pictures\"],\n true_prices=sample_obs[\"price\"],\n predicted_prices=sample_obs[\"cnn_pretrained_predictions\"],\n figsize=(6, 6),\n nrows=2,\n ncols=2,\n save_path=\"../../term-paper/images/cnn_examples_small.png\",\n )\n\n # SUBSECTION: Medium Image with 2x4 Grid\n # choose random images from dataset\n sample_obs = response_price_df.sample(n=8)\n\n show_images(\n images=sample_obs[\"front_page_pictures\"],\n true_prices=sample_obs[\"price\"],\n predicted_prices=sample_obs[\"cnn_pretrained_predictions\"],\n figsize=(12, 6),\n nrows=2,\n ncols=4,\n save_path=\"../../term-paper/images/cnn_examples_medium.png\",\n )\n\n # SUBSECTION: Large Image with 4x4 Grid\n sample_obs = response_price_df.sample(n=16)\n\n show_images(\n images=sample_obs[\"front_page_pictures\"],\n true_prices=sample_obs[\"price\"],\n predicted_prices=sample_obs[\"cnn_pretrained_predictions\"],\n save_path=\"../../term-paper/images/cnn_examples.png\",\n )\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"joel-beck/airbnb-oslo","sub_path":"airbnb_oslo/models/cnn_visualization.py","file_name":"cnn_visualization.py","file_ext":"py","file_size_in_byte":2482,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"21864054447","text":"# coding: utf-8\r\n# Sys\r\nimport json\r\nimport re\r\n\r\n# Other\r\nimport os_io.io_wrapper as iow\r\n\r\ndef _is_content_nums(string):\r\n pattern = '^\\d*?$'\r\n result = re.finditer(pattern, string)\r\n for match in result :\r\n s = match.group()\r\n return True\r\n return False\r\n\r\ndef read_file_and_purge_content(fname):\r\n \"\"\" Пока разбор только файлов субтитров\r\n \r\n Returns:\r\n Содержимое файла в чистом виде одной строкой\r\n \r\n Known Issues:\r\n Сокращения принимаются за коней предложения\r\n \"\"\"\r\n settings = {\r\n 'name': fname, \r\n 'howOpen': 'r', \r\n 'coding': 'cp866' }\r\n \r\n readed_lst = iow.file2list(settings)\r\n purged_lst = list()\r\n for at in readed_lst:\r\n at_copy = at.replace('\\r','')\r\n at_copy = at_copy.replace('\\n','')\r\n if at_copy:\r\n if not '-->' in at_copy:\r\n if not _is_content_nums(at_copy):\r\n at_copy = at_copy.replace('','')\r\n at_copy = at_copy.replace('','')\r\n purged_lst.append(at_copy)\r\n \r\n # Теперь нужно разить на предложения\r\n one_line = ' '.join(purged_lst)\r\n return one_line\r\n\r\ndef get_url_names():\r\n \"\"\" Получение ссылок на контент \r\n \r\n Returns:\r\n Здесь - список файлов формата *.str\r\n \"\"\"\r\n files = ['srts/Iron Man02x26.srt', 'srts/Iron1and8.srt']\r\n return files\r\n\r\ndef save_process_result(process_result):\r\n # Запаковали. Можно сохранятся\r\n to_file = [json.dumps(process_result, sort_keys=True, indent=2)]\r\n \r\n settings = {\r\n 'name': 'extracted_words.json', \r\n 'howOpen': 'w', \r\n 'coding': 'cp866' }\r\n \r\n iow.list2file(settings, to_file)","repo_name":"bezbukv/knowledges-maps-builder","sub_path":"research/models/srt_analyser/os_dal.py","file_name":"os_dal.py","file_ext":"py","file_size_in_byte":1947,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"1040861122","text":"# coding: utf-8\n\n\"\"\"\n Wavefront REST API\n\n
The Wavefront REST API enables you to interact with Wavefront servers using standard REST API tools. You can use the REST API to automate commonly executed operations such as automatically tagging sources.
When you make REST API calls outside the Wavefront REST API documentation you must add the header \\\"Authorization: Bearer <<API-TOKEN>>\\\" to your HTTP requests.
# noqa: E501\n\n OpenAPI spec version: v2\n Contact: chitimba@wavefront.com\n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\n\nclass AccessControlListSimple(object):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n swagger_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n swagger_types = {\n 'can_modify': 'list[str]',\n 'can_view': 'list[str]'\n }\n\n attribute_map = {\n 'can_modify': 'canModify',\n 'can_view': 'canView'\n }\n\n def __init__(self, can_modify=None, can_view=None): # noqa: E501\n \"\"\"AccessControlListSimple - a model defined in Swagger\"\"\" # noqa: E501\n\n self._can_modify = None\n self._can_view = None\n self.discriminator = None\n\n if can_modify is not None:\n self.can_modify = can_modify\n if can_view is not None:\n self.can_view = can_view\n\n @property\n def can_modify(self):\n \"\"\"Gets the can_modify of this AccessControlListSimple. # noqa: E501\n\n\n :return: The can_modify of this AccessControlListSimple. # noqa: E501\n :rtype: list[str]\n \"\"\"\n return self._can_modify\n\n @can_modify.setter\n def can_modify(self, can_modify):\n \"\"\"Sets the can_modify of this AccessControlListSimple.\n\n\n :param can_modify: The can_modify of this AccessControlListSimple. # noqa: E501\n :type: list[str]\n \"\"\"\n\n self._can_modify = can_modify\n\n @property\n def can_view(self):\n \"\"\"Gets the can_view of this AccessControlListSimple. # noqa: E501\n\n\n :return: The can_view of this AccessControlListSimple. # noqa: E501\n :rtype: list[str]\n \"\"\"\n return self._can_view\n\n @can_view.setter\n def can_view(self, can_view):\n \"\"\"Sets the can_view of this AccessControlListSimple.\n\n\n :param can_view: The can_view of this AccessControlListSimple. # noqa: E501\n :type: list[str]\n \"\"\"\n\n self._can_view = can_view\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n if issubclass(AccessControlListSimple, dict):\n for key, value in self.items():\n result[key] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, AccessControlListSimple):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n","repo_name":"AlexJabbourLacework/python-client","sub_path":"wavefront_api_client/models/access_control_list_simple.py","file_name":"access_control_list_simple.py","file_ext":"py","file_size_in_byte":4289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"31"}
+{"seq_id":"526202246","text":"# flask\nimport flask.ext.login\nfrom flask import request\nfrom flask.ext.login import login_required\nfrom flask import render_template\n\n# python\nimport json\nimport config\n\n# application\nfrom db import sanitation, delivery, user\nfrom auth_views import app\nimport auth.forms\nc_u = flask.ext.login.current_user\n\n\n@app.route(\"/\")\n@app.route(\"/index\")\ndef index():\n pass\n\n\n@app.route('/home/charts')\n@login_required\ndef chart():\n activities = user.get_user_stat(c_u.user_id)\n contract = user.get_user_contract(c_u.user_id)\n data = []\n if contract == 'P':\n aim = {'Cleaning': 15, 'Pest': 5, 'Temperature': 10}\n else:\n aim = {'Cleaning': 22, 'Pest': 8, 'Temperature': 25}\n for k, v in activities.items():\n data.append({\"stat\": k, \"value\": v, \"aim\": aim[k]})\n return json.dumps(data)\n\n\n@app.route(\"/home/notes\", methods=[\"GET\"])\n@login_required\ndef notes():\n a = request.args.get('a')\n if a:\n result = user.set_notes(c_u.user_id, a)\n return json.dumps({\"result\": result})\n else:\n notes = user.get_notes(c_u.user_id)\n if notes:\n return json.dumps(notes)\n else:\n return json.dumps(\"No notes to display\")\n\n\n@app.route(\"/home\")\n@login_required\ndef home():\n form = auth.forms.AlertForm()\n cleaningcount = sanitation.get_count_remaining_tasks(config.cleaning)\n pestcount = sanitation.get_count_remaining_tasks(config.pest)\n suppliers = delivery.get_todays_suppliers()\n context = {\"cleaningcount\": cleaningcount,\n \"pestcount\": pestcount,\n \"suppliers\": suppliers}\n return render_template('landingpage.html', form=form, **context)\n","repo_name":"sgrieve03/KitchenKontrol","sub_path":"views/home_views.py","file_name":"home_views.py","file_ext":"py","file_size_in_byte":1670,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"71634404248","text":"#find all the subsequences of a given array\n'''\neg. arr = [3,1,2]\nans = [3] [3,1] [3,1,2] [1] [1,2] [2] [] [3,2]\nlists can be any order\n'''\n\n\n\nfrom typing import List\n\n\ndef get_subsequnce(i:int, ans: List, lst: List, ip: List) -> List:\n\n if i >= len(ip):\n print(lst)\n return\n\n #add the number to lst\n lst.append(ip[i])\n get_subsequnce(i+1, ans, lst, ip)\n\n #remove the number and call\n lst.pop()\n get_subsequnce(i+1, ans, lst, ip)\n\nget_subsequnce(0, [], [], [3,1,2])\n\n\n#time complexity analysis\n\n\"\"\"\nfor every function call we are calling out 2 new recusions\nso for n functions it would be 2^n\n\n\"\"\"\nprint(\"======================================================\")\n\n#all Subsequence with sum equals to k\n'''\neg. arr = [3,1,2] k = 3\nans = [3] [1,2]\nlists can be any order\n'''\n\ndef get_subsequence_sum(i: int, inp: List, ans: List, k: int) -> None:\n\n if i >= len(inp):\n if sum(ans) == k:\n print(ans)\n return\n\n ans.append(inp[i])\n get_subsequence_sum(i+1, inp, ans, k)\n\n ans.pop()\n get_subsequence_sum(i+1, inp, ans, k)\n\nget_subsequence_sum(0,[3,1,2],[],3)\n\n\n#subsequence sum equals to k print/return only first matching subsequence\n\"\"\"\neg. arr = [3,1,2] k = 3\nmatching subsequences = [3] [1,2]\nans = [3]\n\"\"\"\n\ndef first_subsequnce_sum(i:int, inp: List, ans: List, k=int):\n \n if i >= len(inp):\n if sum(ans) == k:\n print(ans)\n return True\n else:\n return False\n\n ans.append(inp[i])\n if first_subsequnce_sum(i+1, inp, ans, k):\n return True\n ans.pop()\n if first_subsequnce_sum(i+1, inp, ans, k):\n return True\n\nprint(\"////////////////////////////////////////////////////////\")\n\nprint(first_subsequnce_sum(0,[3,1,2], [], 3))\nprint(\"\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\")\n\n\n#count of subsequence sum equals to k print/return only first matching subsequence\n\n\"\"\"\nCOUNTS ARE USEFUL IN DP\neg. arr = [3,1,2] k = 3\nmatching subsequences = [3] [1,2]\nans = 2\n\nhere to optimize we will calculate the sum while recursing\n\"\"\"\n\ndef count_subsequence_sum_k(i:int, inp: List, k, su:int) -> int:\n\n if i >= len(inp):\n if su == k:\n return 1\n else:\n return 0\n\n su += inp[i]\n first = count_subsequence_sum_k(i+1, inp, k, su)\n\n su -= inp[i]\n second = count_subsequence_sum_k(i+1, inp, k, su) \n\n return first + second \n\n\nans = count_subsequence_sum_k(0,[3,1,2], 3, 0)\nprint(ans)\n\n","repo_name":"GammaWind/dsa","sub_path":"new/recursion/subsequences.py","file_name":"subsequences.py","file_ext":"py","file_size_in_byte":2473,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"}
+{"seq_id":"2538454141","text":"\"\"\"\nModule containing the necessary classes and functions to build a CART Decision Tree.\n\"\"\"\n\nfrom utilities.utils import class_counts\nfrom utilities.math import find_best_split, partition\n\nclass Leaf:\n \"\"\"\n A leaf node classifies data.\n\n It holds a dictionary of class -> number of times it appears in the rows \n from the training data that reached the leaf.\n \"\"\"\n\n\nclass DecisionNode:\n \"\"\"\n A decision node asks a question.\n\n It holds a reference to a question and to the two child nodes.\n \"\"\"\n \n\ndef build_tree(rows, headers):\n \"\"\"\n Builds the tree following this rules:\n 1. Believe that it works.\n 2. Start by checking for the base case (no further info gain).\n 3. Prepare for giant stack traces.\n \"\"\"\n \n\ndef classify(row, node):\n \"\"\" Classify a given input on a given tree. \"\"\"\n \n\ndef print_tree(node, spacing=\"\"):\n \"\"\" Print the tree to the standard output. \"\"\"\n # base case: we've reached a leaf.\n if isinstance(node, Leaf):\n print(spacing + \"Predict\", node.predictions)\n return\n # print the question at the current node\n print(spacing + str(node.question))\n # call this function recursively on the true and false branches\n print(spacing + \"--> True:\")\n print_tree(node.true_branch, spacing + \" \")\n print(spacing + \"--> False:\")\n print_tree(node.false_branch, spacing + \" \")\n\ndef print_leaf(counts):\n \"\"\" A nicer way to print the predictions at a leaf. \"\"\"\n total = sum(counts.values()) * 1.0\n probs = {}\n for lbl in counts.keys():\n probs[lbl] = str(int(counts[lbl] / total * 100)) + '%'\n return probs\n","repo_name":"mmorenoc2/ST0245-Eafit","sub_path":"proyecto/codigo/python/decision_tree.py","file_name":"decision_tree.py","file_ext":"py","file_size_in_byte":1628,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"37036463967","text":"import apportionment.methods as app\n\n\"\"\"\nDominik's remark:\nIt is actually not without loss of generality to focus just on ties that still appear in the end.\nHere is an example: votes = [720, 720, 120, 120], house size h = 8. Then the quota method selects\nexactly the following: 3 seats go to each of the big parties, and then choose 1 big party and 1\nsmall party and give those a seat each. This last structure can't be captured by ties just at the\nend. (In contrast, for divisor methods, the ties are always of the form \"assign necessary seats\n(say there are t of them), and then choose an arbitrary subset of size h - t from a specified\nset S of parties\".)\n\"\"\"\n\nvotes = [720, 720, 120, 120]\nseats = 8\n\nprint(\"votes: \", votes)\nprint(seats, \"seats\")\n\nresult = app.compute(\"quota\", votes, seats, verbose=True)\n","repo_name":"martinlackner/apportionment","sub_path":"examples/quota-ties.py","file_name":"quota-ties.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"31"}
+{"seq_id":"36917797479","text":"#!/usr/bin/python\n\nimport numpy as np\n\nfrom lazyflow.graph import Graph, InputSlot, OutputSlot\nfrom lazyflow.operator import Operator\n\nclass OpTest(Operator):\n A = InputSlot()\n B = OutputSlot()\n \n def __init__(self, *args, **kwargs):\n super(OpTest, self).__init__(*args, **kwargs)\n self.B.connect(self.A)\n \n def propagateDirty(self, slot, subindex, roi):\n pass\n\nif __name__ == \"__main__\":\n \n op = OpTest(graph=Graph())\n \n print(\"Test 1:\")\n op.A.setValue(np.zeros((3,3)))\n out = op.B[...].wait()\n print(out)\n \n print(\"Test 2:\")\n op.A.setValue([[0,0],[1,1]])\n out = op.B[...].wait()\n print(out)\n \n","repo_name":"burgerdev/turbo-dangerzone","sub_path":"opaque_ops.py","file_name":"opaque_ops.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"15860039006","text":"def egg_carton_box(eggs): \n \"\"\"\n int -> list\n\n returns a list with integers, each of which represents number \n of eggs in each box\n >>> egg_carton_box(12) # дві коробки по 6 яєць\n [6, 6]\n >>> egg_carton_box(28) # три коробки по 10 яєць. Варіант з двома коробками по 10 та двома по 4 відкидається бо це 4 коробки\n [10, 10, 10]\n >>> egg_carton_box(24) # дві коробки по 10 яєць та одна коробка на 4\n [4, 10, 10] \n \"\"\" \n four_num = [1, 2, 3, 4, 13, 14, 23, 24]\n six_num = [5, 6, 11, 12, 15, 16, 21, 22, 25, 26]\n main = []\n while (eggs > 0):\n if eggs in four_num:\n main.append(4)\n eggs -= 4\n elif eggs in six_num:\n main.append(6)\n eggs -= 6\n else:\n main.append(10)\n eggs -= 10\n return sorted(main)\n","repo_name":"maxymkuz/cs_first_semester","sub_path":"lection5/egg_carton_box.py","file_name":"egg_carton_box.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"uk","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"27894151959","text":"import pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nimport datetime\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport matplotlib.pyplot as plt\nfrom torch.optim.lr_scheduler import StepLR\nimport numpy as np\n\ntrainingSeed = 2\nshuffleLabel = 1 # shuffle the training set label to make random weights.\nsave = 0\nshowFig = 0\nprint('training seed: %d' % trainingSeed)\ntorch.manual_seed(trainingSeed)\nnp.random.seed(0) # fix the train_test_split output.\n\niteration = 1000\n\nclass Net(nn.Module):\n # define nn\n def __init__(self):\n super(Net, self).__init__()\n num1, num2 = 8, 8\n self.fc1 = nn.Linear(4, num1)\n self.fc2 = nn.Linear(num1, num2)\n self.fc3 = nn.Linear(num2, 3)\n self.softmax = nn.Softmax(dim=1)\n\n def forward(self, X):\n X = F.relu(self.fc1(X))\n X = self.fc2(X)\n X = self.fc3(X)\n X = self.softmax(X)\n\n return X\n \n# load IRIS dataset\ndataset = pd.read_csv('data/iris.csv')\n\n# transform species to numerics\ndataset.loc[dataset.species=='Iris-setosa', 'species'] = 0\ndataset.loc[dataset.species=='Iris-versicolor', 'species'] = 1\ndataset.loc[dataset.species=='Iris-virginica', 'species'] = 2\n\n\ntrain_X, test_X, train_y, test_y = train_test_split(dataset[dataset.columns[0:4]].values,\n dataset.species.values, test_size=0.3333)\n\ntrain_X = torch.Tensor(train_X)\ntest_X = torch.Tensor(test_X)\ntrain_y = torch.Tensor(train_y).long()\ntest_y = torch.Tensor(test_y).long()\ntestsize = train_y.shape[0]\n\ncriterion = nn.CrossEntropyLoss()# cross entropy loss\n\nnow = datetime.datetime.now()\naccuracy, weight = [], []\nfor iteration in range(iteration):\n if shuffleLabel:\n train_y = train_y[torch.randperm(testsize)]\n if iteration % 1000 == 0:\n print('iter %d' % iteration)\n net = Net()\n if showFig:\n loss_train = []\n \n net.train()\n optimizer = torch.optim.SGD(net.parameters(), lr=1)\n scheduler = StepLR(optimizer, step_size=1, gamma=0.97)\n for epoch in range(100):\n optimizer.zero_grad()\n out = net(train_X)\n loss = criterion(out, train_y)\n loss.backward()\n optimizer.step()\n scheduler.step()\n if showFig:\n loss_train.append(loss)\n \n net.eval()\n predict_out = net(test_X)\n _, predict_y = torch.max(predict_out, 1)\n acc = accuracy_score(test_y.data, predict_y.data)\n# if acc == 0:\n# print(torch.stack([test_y, predict_y], dim=1))\n accuracy.append(acc)\n weightlist = [net.state_dict()['fc1.weight'].view(1, -1).squeeze(),\n net.state_dict()['fc1.bias'],\n net.state_dict()['fc2.weight'].view(1, -1).squeeze(),\n net.state_dict()['fc2.bias'],\n net.state_dict()['fc3.weight'].view(1, -1).squeeze(),\n net.state_dict()['fc3.bias']\n ]\n catweight = torch.cat(weightlist, dim=0)\n weight.append(catweight)\n\nif showFig:\n fig, ax = plt.subplots(1, 1, figsize=(7,7))\n ax.plot(loss_train, '-', color='forestgreen')\n plt.tight_layout()\n\nprint('avg accuracy: %.3f +- %.3f' % (sum(accuracy)/len(accuracy), np.std(accuracy)))\nallAcc = torch.FloatTensor(accuracy)\nallWeight = torch.stack(weight, dim=0)\nif shuffleLabel:\n name1 = 'data/irisShuffleAcc_%d.pt' % trainingSeed\n name2 = 'data/irisShuffleWeight_%d.pt' % trainingSeed\nelse:\n name1 = 'data/irisAcc_%d.pt' % trainingSeed\n name2 = 'data/irisWeight_%d.pt' % trainingSeed\nif save:\n torch.save(allAcc, name1)\n torch.save(allWeight, name2)\n\nprint('finished in %d seconds.' % (datetime.datetime.now()-now).seconds)\n","repo_name":"sevenquarkoniums/WeightClassification","sub_path":"irisExample.py","file_name":"irisExample.py","file_ext":"py","file_size_in_byte":3735,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"24545204348","text":"# 个人中心\n\nimport time\nfrom datetime import datetime, timedelta\n\nfrom flask import render_template, request, current_app, jsonify, session, redirect, url_for, g, abort\n\nfrom info import db\nfrom info.modules.admin import admin_blu\nfrom info.utils.common import file_upload\nfrom info.utils.constants import ADMIN_USER_PAGE_MAX_COUNT, ADMIN_NEWS_PAGE_MAX_COUNT, QINIU_DOMIN_PREFIX\nfrom info.utils.models import User, News, Category\nfrom info.utils.response_code import RET, error_map\n\n\n# 后台登录页\n@admin_blu.route(\"/login\", methods=[\"GET\", \"POST\"])\ndef login():\n if request.method == \"GET\":\n\n user_id = session.get(\"user_id\")\n is_admin = session.get(\"is_admin\")\n if user_id and is_admin:\n return redirect(url_for(\"admin.index\"))\n\n return render_template(\"admin/login.html\")\n\n # post\n # 获取参数\n username = request.form.get(\"username\")\n password = request.form.get(\"password\")\n\n # 校验参数\n if not all([username, password]):\n current_app.logger.error(\"参数不足\")\n return render_template(\"admin/login.html\", errmsg=\"参数不足\")\n\n try:\n user = User.query.filter(User.mobile == username, User.is_admin == True).first()\n except BaseException as e:\n current_app.logger.error(e)\n return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])\n\n if not user:\n return render_template(\"admin/login.html\", errmsg=\"管理员不存在\")\n\n if not user.check_password(password):\n return render_template(\"admin/login.html\", errmsg=\"密码错误\")\n\n # 保存session 数据,实现免密码登录\n session[\"user_id\"] = user.id\n session[\"is_admin\"] = True\n\n return redirect(url_for(\"admin.index\"))\n\n\n# 后台首页\n@admin_blu.route(\"/index\")\ndef index():\n # user_id = session.get(\"user_id\")\n # try:\n # user = User.query.filter_by(id=user_id).first()\n # except BaseException as e:\n # current_app.logger.error(e)\n # return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])\n # return render_template(\"admin/index.html\", user=user.to_dict())\n return render_template(\"admin/index.html\", user=g.user.to_dict())\n\n\n# 后台退出\n@admin_blu.route('/logout')\ndef logout():\n # 删除session 数据\n session.pop(\"user_id\", None)\n session.pop(\"is_admin\", None)\n\n # 重定向到后台登录\n return redirect(url_for(\"admin.login\"))\n\n\n# 后台用户统计\n@admin_blu.route(\"/user_count\")\ndef user_count():\n # 用户总人数\n try:\n total_count = User.query.filter(User.is_admin == False).count()\n except BaseException as e:\n current_app.logger.error(e)\n total_count = 0\n\n # 月新增人数 注册时间 >= 本月1号0点\n # 获取当前时间的年和月\n t = time.localtime()\n\n # 构建日期字符串 2019-01-04\n mon_date_str = \"%d-%02d-01\" % (t.tm_year, t.tm_mon)\n\n # 转换为日期对象\n mon_date = datetime.strptime(mon_date_str, \"%Y-%m-%d\")\n\n try:\n mon_count = User.query.filter(User.is_admin == False, User.create_time >= mon_date).count()\n except BaseException as e:\n current_app.logger.error(e)\n mon_count = 0\n\n # 日新增人数\n # 构建日期字符串 2019-01-04\n day_date_str = \"%d-%02d-%02d\" % (t.tm_year, t.tm_mon, t.tm_mday)\n day_date = datetime.strptime(day_date_str, \"%Y-%m-%d\")\n try:\n day_count = User.query.filter(User.is_admin == False, User.create_time >= day_date).count()\n except BaseException as e:\n current_app.logger.error(e)\n day_count = 0\n\n # 某日的注册人数 注册时间 >= 当日0点, < 次日0点\n active_count = []\n active_time = []\n\n for i in range(0, 30):\n begin_date = day_date - timedelta(days=i) # 当日0点\n end_date = begin_date + timedelta(days=1) # 次日0点\n\n try:\n one_day_count = User.query.filter(User.is_admin == False, User.create_time >= begin_date,\n User.create_time < end_date).count()\n\n active_count.append(one_day_count) # 存放日期对应的注册人数\n\n # 将日期对象转为日期字符串\n one_day_str = begin_date.strftime(\"%Y-%m-%d\")\n active_time.append(one_day_str) # 存放日期字符串\n\n except BaseException as e:\n current_app.logger.error(e)\n one_day_count = 0\n\n # 日期和注册量倒序\n active_time.reverse()\n active_count.reverse()\n\n data = {\n \"total_count\": total_count,\n \"mon_count\": mon_count,\n \"day_count\": day_count,\n \"active_count\": active_count,\n \"active_time\": active_time\n }\n\n return render_template(\"admin/user_count.html\", data=data)\n\n\n# 后台用户列表\n@admin_blu.route('/user_list')\ndef user_list():\n p = request.args.get(\"p\", 1) # 页数\n # 校验参数\n try:\n p = int(p)\n except BaseException as e:\n current_app.logger.error(e)\n return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])\n\n # 查询当前用户发布的新闻发布时间倒序,分页查询\n try:\n pn = User.query.order_by(User.last_login.desc()).paginate(p, ADMIN_USER_PAGE_MAX_COUNT)\n except BaseException as e:\n current_app.logger.error(e)\n return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])\n\n data = {\n \"user_list\": [user.to_admin_dict() for user in pn.items],\n \"total_page\": pn.pages,\n \"cur_page\": pn.page\n\n } # 注意要传递的数据是否正确\n\n return render_template(\"admin/user_list.html\", data=data)\n\n\n# 后台新闻审核\n@admin_blu.route('/news_review')\ndef news_review():\n p = request.args.get(\"p\", 1) # 页数\n keyword = request.args.get(\"keyword\") # 关键字搜索\n # 校验参数\n try:\n p = int(p)\n except BaseException as e:\n current_app.logger.error(e)\n return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])\n\n filter_list = []\n if keyword:\n filter_list.append(News.title.contains(keyword))\n # 查询当前用户发布的新闻发布时间倒序,分页查询\n try:\n pn = News.query.filter(*filter_list).order_by(News.create_time.desc()).paginate(p, ADMIN_NEWS_PAGE_MAX_COUNT)\n except BaseException as e:\n current_app.logger.error(e)\n return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])\n\n data = {\n \"news_list\": [news.to_review_dict() for news in pn.items],\n \"total_page\": pn.pages,\n \"cur_page\": pn.page\n\n } # 注意要传递的数据是否正确\n\n return render_template(\"admin/news_review.html\", data=data)\n\n\n# 后台新闻审核详情页\n@admin_blu.route('/news_review_detail')\ndef news_review_detail():\n news_id = request.args.get(\"news_id\")\n try:\n news_id = int(news_id)\n # 查询新闻信息\n news = News.query.get(news_id)\n except BaseException as e:\n current_app.logger.error(e)\n return abort(500)\n\n return render_template(\"admin/news_review_detail.html\", news=news.to_dict())\n\n\n# 后台新闻审核提交\n@admin_blu.route('/news_review_action', methods=[\"POST\"])\ndef news_review_action():\n news_id = request.json.get(\"news_id\")\n action = request.json.get(\"action\")\n reason = request.json.get(\"reason\")\n\n if not all([news_id, action]):\n return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])\n\n if not action in [\"accept\", \"reject\"]:\n return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])\n\n try:\n news_id = int(news_id)\n # 查询新闻信息\n news = News.query.get(news_id)\n except BaseException as e:\n current_app.logger.error(e)\n return abort(403)\n\n if action == \"accept\":\n news.status = 0\n return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])\n\n # reject\n if not reason:\n return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])\n else:\n news.reason = reason\n news.status = -1\n\n return jsonify(errno=RET.OK, errmsg=error_map[RET.OK], news_id=news_id)\n\n\n# 后台新闻板式编辑\n@admin_blu.route('/news_edit')\ndef news_edit():\n p = request.args.get(\"p\", 1) # 页数\n keyword = request.args.get(\"keyword\") # 关键字搜索\n # 校验参数\n try:\n p = int(p)\n except BaseException as e:\n current_app.logger.error(e)\n return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])\n\n filter_list = []\n if keyword:\n filter_list.append(News.title.contains(keyword))\n # 查询当前用户发布的新闻发布时间倒序,分页查询\n try:\n pn = News.query.filter(*filter_list).order_by(News.create_time.desc()).paginate(p, ADMIN_NEWS_PAGE_MAX_COUNT)\n except BaseException as e:\n current_app.logger.error(e)\n return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])\n\n data = {\n \"news_list\": [news.to_review_dict() for news in pn.items],\n \"total_page\": pn.pages,\n \"cur_page\": pn.page\n\n } # 注意要传递的数据是否正确\n\n return render_template(\"admin/news_edit.html\", data=data)\n\n\n# 后台新闻版式详情页\n@admin_blu.route('/news_edit_detail/')\ndef news_edit_detail(news_id):\n try:\n news = News.query.get(news_id)\n except BaseException as e:\n current_app.logger.error(e)\n return abort(500)\n\n # 查询所有分类\n try:\n categories = Category.query.filter(Category.id != 1).all()\n except BaseException as e:\n current_app.logger.error(e)\n return abort(500)\n\n category_list = []\n for category in categories:\n category_dict = category.to_dict()\n is_select = False\n if category.id == news.category_id:\n is_select = True\n\n category_dict[\"is_select\"] = is_select\n category_list.append(category_dict)\n\n return render_template(\"admin/news_edit_detail.html\", news=news.to_dict(), category_list=category_list)\n\n\n@admin_blu.route('/news_edit_detail', methods=[\"POST\"])\ndef news_edit_detail_post():\n # POST\n # 获取参数\n news_id = request.form.get(\"news_id\")\n title = request.form.get(\"title\")\n category_id = request.form.get(\"category_id\")\n digest = request.form.get(\"digest\")\n content = request.form.get(\"content\")\n index_image = request.files.get(\"index_image\")\n\n # 校验参数\n if not all([news_id, title, category_id, digest, content]):\n return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])\n\n try:\n news_id = int(news_id)\n category_id = int(category_id)\n except BaseException as e:\n current_app.logger.error(e)\n return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])\n\n # 查找新闻\n try:\n news = News.query.get(news_id)\n except BaseException as e:\n current_app.logger.error(e)\n return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])\n\n # 修改新闻数据\n news.title = title\n news.category_id = category_id\n news.digest = digest\n news.content = content\n\n if index_image:\n try:\n # 读取图片内容\n img_bytes = index_image.read()\n file_name = file_upload(img_bytes)\n news.index_image_url = QINIU_DOMIN_PREFIX + file_name\n except BaseException as e:\n current_app.logger.error(e)\n return jsonify(errno=RET.THIRDERR, errmsg=error_map[RET.THIRDERR])\n\n return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])\n\n\n@admin_blu.route('/news_type',methods=[\"GET\",\"POST\"])\ndef news_type():\n if request.method == \"GET\":\n try:\n categories = Category.query.filter(Category.id != 1).all()\n except BaseException as e:\n current_app.logger.error(e)\n return jsonify(errno=RET.DBERR,errmsg=error_map[RET.DBERR])\n\n return render_template(\"admin/news_type.html\",categories=categories)\n\n # POST\n id = request.json.get(\"id\")\n name = request.json.get(\"name\")\n\n if not name:\n return jsonify(errno=RET.PARAMERR,errmsg=error_map[RET.PARAMERR])\n\n if id:\n category = Category.query.get(id)\n category.name = name\n else:\n # 新增 分类\n news_category = Category(name=name)\n db.session.add(news_category)\n\n return jsonify(errno=RET.OK,errmsg=error_map[RET.OK])\n\n","repo_name":"shanesl/InfoNews","sub_path":"info/modules/admin/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":12408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"32948960629","text":"from flask import Flask, jsonify, request, make_response,jsonify,json\nfrom flask_restful import Resource, Api, marshal_with, fields,reqparse\nfrom Models.Bean import *\nfrom Models.Return import Return\nfrom Models.Database import Database\n\nclass BALCustomers:\n def getCustomersList(self,id=None,deleted=0,status=1,flag=2):\n customersList=[]\n where=\"\"\n field=\" id, name, mobile, email \"\n if(flag==1):\n field=field+\",status \"\n query=\"select \"+field+\" from customers \" \n if(status!=None):\n where=where+\" status=\"+str(status)+\" and \"\n if(id!=None):\n where=where+\" id=\"+str(id)+\" and \"\n if(deleted!=None):\n where=where+\" deleted=\"+str(deleted)+\" and \"\n if(len(where)>0):\n query=query+\" where \"+where.rsplit(\"and \",1)[0]\n cursor=Database.getCursor(query)\n if(cursor==\"201\"):\n return customersList \n for row in cursor:\n element=CustomerModel()\n element.id=row[0]\n element.name=row[1]\n element.mobile=row[2]\n element.email=row[3] \n if(flag==1):\n element.status=row[4]\n customersList.append(element.__dict__)\n return customersList\n \n def getCustomerEmailList(self):\n customerEmails=[]\n func=BALCustomers()\n customerList=func.getCustomersList(None)\n for customerObj in customerList:\n customerEmails.append(customerObj['email'])\n return customerEmails","repo_name":"jaydev7178/CryptocurrencyApp","sub_path":"BAL/BALCustomers.py","file_name":"BALCustomers.py","file_ext":"py","file_size_in_byte":1567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"11712067078","text":"import argparse\nimport json\nimport hashlib\n\n# 定义命令行参数\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-i\", \"--input\", help=\"input file path\")\nparser.add_argument(\"-o\", \"--output\", help=\"output file path\")\nargs = parser.parse_args()\n\n# 打开输入文件并加载所有行\nwith open(args.input, \"r\") as f:\n lines = f.readlines()\n\n# 创建一个空集合用于存储唯一的哈希值\nunique_hashes = set()\n\n# 循环遍历每一行 JSON 数据\nfor line in lines:\n # 将 JSON 字符串转换为 Python 字典\n data = json.loads(line)\n if \"asn\" in data:\n asn = data[\"asn\"].get(\"as_number\", [])\n else:\n asn = []\n # asn = data[\"asn\"].get(\"as_number\",[])\n # 提取需要计算的字段\n # body_md5 = data.get(\"hash\", {}).get(\"body_md5[]\", [])\n body_md5 = data[\"hash\"][\"body_md5\"]\n # asn = data[\"asn\"][\"as_number\"]\n words = data.get(\"words\", [])\n webserver = data.get(\"webserver\", [])\n a = data.get(\"a\", [])\n status_code = data.get(\"status_code\", [])\n content_length = data.get(\"content_length\", [])\n title = data.get(\"title\", [])\n lines = data.get(\"lines\", [])\n # a = data[\"a\"]\n\n\n # 计算新的哈希值\n only_md5 = hashlib.md5(\"{}{}{}{}{}{}{}{}{}\".format(body_md5, words, webserver, a,status_code,content_length,title,lines,asn).encode()).hexdigest()\n\n # 将新字段添加到原始字典中\n data[\"only_md5\"] = only_md5\n\n # 如果哈希值不在集合中,则将更新后的字典写入输出文件,并将哈希值添加到集合中\n if only_md5 not in unique_hashes:\n with open(args.output, \"a\") as f:\n f.write(json.dumps(data) + \"\\n\")\n unique_hashes.add(only_md5)\n","repo_name":"york-cmd/SuperDict","sub_path":"domain/url-qc.py","file_name":"url-qc.py","file_ext":"py","file_size_in_byte":1698,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"}
+{"seq_id":"39960365018","text":"from project.library import Library\n\nfrom unittest import TestCase, main\n\n\nclass TestLibrary(TestCase):\n def setUp(self) -> None:\n self.name = \"Library\"\n self.library = Library(self.name)\n self.author = \"Author\"\n self.title = \"Title\"\n self.reader = \"Reader\"\n\n def test_library_initialisation_with_correct_name(self):\n self.assertEqual(self.name, self.library.name)\n self.assertEqual({}, self.library.books_by_authors)\n self.assertEqual({}, self.library.readers)\n\n def test_library_initialisation_with_empty_string_for_name_raises_error(self):\n name = \"\"\n with self.assertRaises(ValueError) as error:\n Library(name)\n\n self.assertEqual(\"Name cannot be empty string!\", str(error.exception))\n\n def test_add_book_with_new_author_who_is_not_in_books_dict(self):\n self.library.add_book(self.author, self.title)\n self.assertEqual([self.title], self.library.books_by_authors[self.author])\n\n def test_add_book_with_existing_author_non_existing_title(self):\n new_title = \"New Title\"\n self.library.add_book(self.author, self.title)\n self.library.add_book(self.author, new_title)\n expected_result = [self.title, new_title]\n self.assertEqual(expected_result, self.library.books_by_authors[self.author])\n\n def test_add_book_with_existing_author_and_existing_title(self):\n self.library.add_book(self.author, self.title)\n self.library.add_book(self.author, self.title)\n expected_result = [self.title]\n self.assertEqual(expected_result, self.library.books_by_authors[self.author])\n\n def test_add_reader_creates_empty_list_with_new_reader(self):\n self.library.add_reader(self.reader)\n self.assertEqual([], self.library.readers[self.reader])\n\n def test_add_reader_who_exists_returns_string(self):\n self.library.add_reader(self.reader)\n actual = self.library.add_reader(self.reader)\n\n self.assertEqual(f\"{self.reader} is already registered in the {self.name} library.\", actual)\n\n def test_rent_book_not_registered_reader_returns_string(self):\n actual = self.library.rent_book(self.reader, self.author, self.title)\n self.assertEqual(f\"{self.reader} is not registered in the {self.name} Library.\", actual)\n\n def test_rent_book_with_not_registered_author_returns_string(self):\n self.library.add_reader(self.reader)\n actual = self.library.rent_book(self.reader, self.author, self.title)\n self.assertEqual(f\"{self.name} Library does not have any {self.author}'s books.\", actual)\n\n def test_rent_book_with_not_existing_book_title(self):\n self.library.add_reader(self.reader)\n self.library.add_book(self.author, self.title)\n new_title = \"new_title\"\n actual = self.library.rent_book(self.reader, self.author, new_title)\n self.assertEqual(f\"\"\"{self.name} Library does not have {self.author}'s \"{new_title}\".\"\"\", actual)\n\n def test_rent_book_with_existing_reader_author_and_book_title(self):\n self.library.add_reader(self.reader)\n self.library.add_book(self.author, self.title)\n self.library.rent_book(self.reader, self.author, self.title)\n self.assertEqual([{self.author: self.title}], self.library.readers[self.reader])\n self.assertEqual({self.author: []}, self.library.books_by_authors)\n\n\n\n\n\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"nmoskova/Python-OOP","sub_path":"exam_preparation/23_08_2021/testing/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3445,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"9323680643","text":"#!/usr/bin/python\r\n# -*- coding: utf-8 -*-\r\n#\r\n# Copyright (C) 2010 ZHENG Zhong \r\n#\r\n# Created on 2010-05-04.\r\n# $Id$\r\n#\r\n\r\nfrom django.conf.urls.defaults import *\r\nfrom friday.apps.tagging.views import *\r\n\r\n\r\nurlpatterns = patterns(\"\",\r\n url(\r\n r\"^$\",\r\n view_tags,\r\n name=\"friday.view_tags\"\r\n ),\r\n url(\r\n r\"^category/(?P\\w+)/$\",\r\n view_tags,\r\n name=\"friday.view_tags\"\r\n ),\r\n url(\r\n r\"^cloud/(?P\\w+)/$\",\r\n view_tag_cloud,\r\n name=\"friday.view_tag_cloud\"\r\n ),\r\n)\r\n\r\n\r\n# EOF\r\n","repo_name":"BGCX262/zzheng-hg-to-git","sub_path":"friday/website/friday/apps/tagging/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"44037108355","text":"\"\"\"\nTwo friends like to pool their money and go to the ice cream parlor. They always choose two distinct flavors and they spend all of their money.\n\nGiven a list of prices for the flavors of ice cream, select the two that will cost all of the money they have.\n\nExample. \n\nThe two flavors that cost and meet the criteria. Using -based indexing, they are at indices and .\n\nFunction Description\n\nComplete the icecreamParlor function in the editor below.\n\nicecreamParlor has the following parameter(s):\n\nint m: the amount of money they have to spend\nint cost[n]: the cost of each flavor of ice cream\nReturns\n\nint[2]: the indices of the prices of the two flavors they buy, sorted ascending\nInput Format\n\nThe first line contains an integer, , the number of trips to the ice cream parlor. The next sets of lines each describe a visit.\n\nEach trip is described as follows:\n\nThe integer , the amount of money they have pooled.\nThe integer , the number of flavors offered at the time.\n space-separated integers denoting the cost of each flavor: .\nNote: The index within the cost array represents the flavor of the ice cream purchased.\n\nConstraints\n\n, ∀ \nThere will always be a unique solution.\nSample Input\n\nSTDIN Function\n----- --------\n2 t = 2\n4 k = 4\n5 cost[] size n = 5\n1 4 5 3 2 cost = [1, 4, 5, 3, 2]\n4 k = 4\n4 cost[] size n = 4\n2 2 4 3 cost=[2, 2,4, 3]\n\"\"\"\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n#\n# Complete the 'icecreamParlor' function below.\n#\n# The function is expected to return an INTEGER_ARRAY.\n# The function accepts following parameters:\n# 1. INTEGER m\n# 2. INTEGER_ARRAY arr\n#\n\n\"\"\"\n #this is a two sime problem . because i am looking for two numbers that have to sum up to money and i cannot\n I cannot laso have a negative sum as in the ice cream man will pay one of the friends to give an ice cream my approach is to simply subtract the given number in the array\n from money. if that number exists then we have two numbers that sum to m. return the index at which they are found\n \"\"\" \n\ndef icecreamParlor(m, arr):\n # Write your code here\n complement = {}\n \n money = m\n results = []\n \n for i in range(len(arr)):\n comp = m -arr[i]\n if arr[i] in complement:\n \n results = [complement[arr[i]]+1,i+1]\n else:\n if comp >=1:\n complement[comp] = i\n \n return results","repo_name":"AlexeiVartoumian/leetcodeRepository","sub_path":"HackerRank/Dictionary/iceCreamParlour.py","file_name":"iceCreamParlour.py","file_ext":"py","file_size_in_byte":2472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"20603921088","text":"from tkinter import *\nfrom tkinter.messagebox import *\nimport os\n\n\ndef sql_get_terminals():\n ls = []\n for i in range(10):\n ls.append([i, 'Terminal_{}'.format(i), 'description'])\n return ls\n\n\nclass TableGrid(Frame):\n def __init__(self, parent=None, titles=None, rows=0, *args):\n super().__init__(parent)\n for index, title in enumerate(titles):\n Label(self, text=title).grid(row=0, column=index)\n self.rebuild(rows=rows, columns=3)\n self.pack()\n\n def rebuild(self, rows=0, columns=0):\n self.cells = []\n self.vars = []\n for i in range(1, rows+1):\n self.vars.append([])\n for j in range(columns):\n var = StringVar()\n self.vars[i-1].append(var)\n ent = Entry(self, textvariable=var)\n ent.grid(row=i, column=j)\n self.cells.append(ent)\n\n def get_terminals(self):\n sql_data = sql_get_terminals()\n self.rebuild(len(sql_data), len(sql_data[0]))\n for index, data in enumerate(sql_data):\n for i, d in enumerate(data):\n self.vars[index][i].set(d)\n\ndef not_implemented(x=13):\n print('Not implemented yet!', x)\n # showerror('Not implemented yet!')\n\n\ndef not_implemented_2(event):\n print('Not implemented_2 yet!', event)\n\nmain_window = Tk()\nmain_window.minsize(400, 400)\ngrid = TableGrid(main_window, ('Id', 'Name', 'Description'), 3)\nmain_window.resizable(width=False, height=False)\nmain_window.title('Star administrator')\n# fr1 = Frame(main_window)\n# fr1.pack(side=LEFT)\n# label = Label(fr1, text='This is first frame')\n# label.pack()\nfr2 = Frame(main_window)\nfr3 = Frame(main_window)\nfr3.pack(side=RIGHT)\nfor i in range(5):\n btn = Button(fr2, text='Create DB', command=lambda x=i: not_implemented(x))\n btn.grid(row=0, column=i)\nfr2.pack(side=BOTTOM)\nbtn = Button(fr3, text='Get terminals', command=sql_get_terminals)\nbtn.pack()\n\n# left, wheel, right mouse buttons accordingly\nmain_window.bind('', not_implemented_2)\nmain_window.bind('', not_implemented_2)\nmain_window.bind('', not_implemented_2)\nmain_menu = Menu(main_window)\nfile_menu = Menu(main_menu )\nfile_menu.add_command(label='Terminals', command=lambda g=grid: g.get_terminals())\nmain_menu.add_cascade(label='Database', menu=file_menu)\nmain_window.config(menu=main_menu)\nmainloop()\n","repo_name":"k1r91/course2","sub_path":"l4-gui_tkinter/lesson/gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":2400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"17800118121","text":"\nfrom unittest import TestCase\nimport json\nimport os\n\nimport pytest\n\nfrom lily_assistant.config import Config\n\n\nclass ConfigTestCase(TestCase):\n\n @pytest.fixture(autouse=True)\n def initfixtures(self, mocker, tmpdir):\n self.mocker = mocker\n\n self.tmpdir = tmpdir\n\n def setUp(self):\n\n self.lily_dir = self.tmpdir.mkdir('.lily')\n self.mocker.patch.object(\n os, 'getcwd').return_value = str(self.tmpdir)\n\n self.lily_dir.join('config.json').write(json.dumps({\n 'name': 'hello',\n 'src_dir': 'some_service',\n 'repository': 'bithub',\n 'version': '0.1.9',\n 'last_commit_hash': '940594',\n 'next_version': '0.2.1',\n 'next_last_commit_hash': 'fd898fd',\n }))\n\n #\n # GET_PROJECT_PATH\n #\n def test_get_project_path(self):\n\n assert Config.get_project_path() == str(self.tmpdir)\n\n #\n # GET_CONFIG_PATH\n #\n def test_get_config_path(self):\n\n assert Config.get_config_path() == str(\n self.tmpdir.join('.lily').join('config.json'))\n\n #\n # GET_LILY_PATH\n #\n def test_get_lily_path(self):\n\n assert Config.get_lily_path() == str(self.tmpdir.join('.lily'))\n\n #\n # EXISTS\n #\n def test_exists(self):\n\n assert Config.exists() is True\n\n os.remove(str(self.tmpdir.join('.lily').join('config.json')))\n\n assert Config.exists() is False\n\n #\n # CREATE_EMPTY\n #\n def test_create_empty(self):\n\n os.remove(str(self.tmpdir.join('.lily').join('config.json')))\n\n Config.create_empty('some_service')\n\n assert json.loads(\n self.tmpdir.join('.lily').join('config.json').read()\n ) == {\n 'last_commit_hash': '... THIS WILL BE FILLED AUTOMATICALLY ...',\n 'name': '... PUT HERE NAME OF YOUR PROJECT ...',\n 'repository': '... PUT HERE URL OF REPOSITORY ...',\n 'src_dir': 'some_service',\n 'version': '... PUT HERE INITIAL VERSION ...',\n 'next_version': None,\n 'next_last_commit_hash': None,\n }\n\n def test_create_empty__lily_folder_does_not_exist(self):\n\n self.tmpdir.join('.lily').remove()\n\n Config.create_empty('some_service')\n\n assert json.loads(\n self.tmpdir.join('.lily').join('config.json').read()\n ) == {\n 'last_commit_hash': '... THIS WILL BE FILLED AUTOMATICALLY ...',\n 'name': '... PUT HERE NAME OF YOUR PROJECT ...',\n 'repository': '... PUT HERE URL OF REPOSITORY ...',\n 'src_dir': 'some_service',\n 'version': '... PUT HERE INITIAL VERSION ...',\n 'next_version': None,\n 'next_last_commit_hash': None,\n }\n\n #\n # PROPERTIES: GETTERS & SETTERS\n #\n def test_properties__getters(self):\n\n config = Config()\n\n assert config.name == 'hello'\n assert config.src_dir == 'some_service'\n assert config.src_path == str(self.tmpdir.join('some_service'))\n assert config.repository == 'bithub'\n assert config.version == '0.1.9'\n assert config.last_commit_hash == '940594'\n assert config.next_version == '0.2.1'\n assert config.next_last_commit_hash == 'fd898fd'\n\n def test_properties__setters(self):\n\n def read_from_conf(prop):\n conf = json.loads(self.lily_dir.join('config.json').read())\n\n return conf[prop]\n\n config = Config()\n\n # -- version\n config.version = '9.9.1'\n assert read_from_conf('version') == '9.9.1'\n\n # -- next_version\n config.next_version = '9.0.8'\n assert read_from_conf('next_version') == '9.0.8'\n\n # -- src_dir\n config.src_dir = 'entity_service'\n assert read_from_conf('src_dir') == 'entity_service'\n\n # -- last_commit_hash\n config.last_commit_hash = 'f7d87cd78'\n assert read_from_conf('last_commit_hash') == 'f7d87cd78'\n\n # -- next_last_commit_hash\n config.next_last_commit_hash = 'f7d87cd78'\n assert read_from_conf('next_last_commit_hash') == 'f7d87cd78'\n","repo_name":"cosphere-org/lily-assistant","sub_path":"tests/test_config.py","file_name":"test_config.py","file_ext":"py","file_size_in_byte":4140,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"}
+{"seq_id":"27477925737","text":"import unittest\n\nfrom midi_to_dataframe import NoteMapper, MidiReader\n\nMIDI_FILE_1 = \"resources/midi/Bomfunk_MCs_-_Freestyler.mid\"\n\n\nclass MidiReaderTests(unittest.TestCase):\n\n def __init__(self, *args, **kwargs):\n super(MidiReaderTests, self).__init__(*args, **kwargs)\n\n # Prepare tests objects\n note_mapping_config_path = \"resources/config/map-to-group.json\"\n note_mapper = NoteMapper(note_mapping_config_path)\n self.reader = MidiReader(note_mapper)\n\n def test_sequence_extraction(self):\n self.reader.set_extract_timestamp(False)\n self.reader.set_extract_time_signature(False)\n\n # Convert MIDI file to sequential text representation\n dataframe = self.reader.convert_to_dataframe(MIDI_FILE_1)\n self.assertTrue(dataframe.shape[0] > 0)\n\n\ndef main():\n unittest.main()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"TaylorPeer/midi-to-dataframe","sub_path":"tests/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"}
+{"seq_id":"42687955081","text":"\"\"\"\n# Sync A2W NWS Stages by State\n\n- Get NWS Stages\n\n - [AHPS Report](https://water.weather.gov/monitor/ahpsreport.php?type=csv)\n\n - Returns the locations and stages from the AHAPS report as a list of objects\n\n\n- Get USGS sites from Water API\n\n - Returns the existing USGS stage numbers in the Water API\n\n\n- Sync NWS Stages to Water\n\n - Build the payload and post to Water API\n\n\"\"\"\nimport csv\nimport json\nfrom datetime import datetime, timedelta\nfrom io import StringIO\nfrom textwrap import dedent\n\nimport helpers.water as water\nimport requests\nfrom airflow import DAG\nfrom airflow.exceptions import AirflowSkipException\nfrom airflow.operators.python import PythonOperator\n\n# Default arguments\ndefault_args = {\n \"owner\": \"airflow\",\n \"depends_on_past\": False,\n \"start_date\": (datetime.utcnow() - timedelta(days=2)).replace(minute=0, second=0),\n \"catchup_by_default\": False,\n \"email_on_failure\": False,\n \"email_on_retry\": False,\n \"retries\": 1,\n \"retry_delay\": timedelta(minutes=10),\n \"schedule\": \"@daily\"\n # 'max_active_runs':1,\n # 'concurrency':4,\n}\n\n\nwith DAG(\n default_args=default_args,\n dag_id=\"a2w_sync_nws_stages\",\n tags=[\"a2w\", \"nws\"],\n doc_md=dedent(__doc__),\n) as dag:\n\n ########################################\n # Returns the Locations and Stages from the NWS as a list of objects\n def get_nws_stages():\n\n url = \"https://water.weather.gov/monitor/ahpsreport.php?type=csv\"\n\n r = requests.get(url)\n buff = StringIO(r.text)\n reader = csv.reader(buff, delimiter=\",\")\n\n keys = []\n result = []\n\n # Convert the csv to a list of json objects\n # with headers as keys\n for idx, line in enumerate(reader):\n if idx == 0:\n # this is the header\n keys = line\n else:\n # Build each line (object) by setting the keys and values\n _line = {}\n for i, k in enumerate(keys):\n _line[k] = line[i].strip()\n result.append(_line)\n\n return json.dumps(result)\n\n ########################################\n # Returns the existing USGS Stages Numbers in the Water API\n def get_water_usgs_site_numbers():\n\n sites = json.loads(water.get_usgs_sites_by_state(state=\"all\"))\n\n result_sites = []\n for site in sites:\n result_sites.append(site[\"site_number\"])\n\n return json.dumps(result_sites)\n\n ########################################\n # Returns the existing NWS Stages in the Water API\n def get_water_nws_stages():\n\n stages = json.loads(water.get_nws_stages_by_site(site=\"all\"))\n\n existing_stages = {}\n for site_stages in stages:\n existing_stages[site_stages[\"nwsid\"]] = site_stages\n\n return json.dumps(existing_stages)\n\n ########################################\n def sync_nws_stages_to_water(\n state, nws_stages, water_nws_stages, water_usgs_site_numbers\n ):\n\n water_usgs_site_numbers = json.loads(water_usgs_site_numbers)\n water_nws_stages = json.loads(water_nws_stages)\n\n post_items = []\n put_items = []\n\n for idx, line in enumerate(json.loads(nws_stages)):\n\n if line[\"state\"].strip() == state.lower():\n\n # Entry must have:\n # 1) USGSID must be in API sites\n # 2) NWSID = 5 chars\n # 3) a proper USGS ID\n # 4) stage must have a unit of 'FT\n # 5) all stages cannot be 0\n if (\n line[\"usgs id\"].strip() in water_usgs_site_numbers\n and len(line[\"nws shef id\"].strip()) == 5\n and line[\"usgs id\"].strip() != \"\"\n and len(line[\"usgs id\"].strip()) >= 8\n and line[\"usgs id\"].strip().isnumeric()\n and line[\"flood stage unit\"].strip() == \"FT\"\n and float(line[\"action stage\"].strip()) != 0\n and float(line[\"flood stage\"].strip()) != 0\n and float(line[\"moderate flood stage\"].strip()) != 0\n and float(line[\"major flood stage\"].strip()) != 0\n ):\n\n if line[\"proximity\"].strip() in [\"at\", \"near\", \"below\", \"near\"]:\n # ex: Name above xyz lake\n name = f\"{line['location name'].strip()} {line['proximity'].strip()} {line['river/water-body name'].strip()}\"\n else:\n name = line[\"location name\"].strip()\n\n nwsid = line[\"nws shef id\"].strip()\n usgs_id = line[\"usgs id\"].strip()\n action = float(line[\"action stage\"].strip())\n flood = float(line[\"flood stage\"].strip())\n moderate_flood = float(line[\"moderate flood stage\"].strip())\n major_flood = float(line[\"major flood stage\"].strip())\n\n # Build payload\n payload = {}\n payload[\"nwsid\"] = nwsid\n payload[\"usgs_site_number\"] = usgs_id\n payload[\"name\"] = name\n payload[\"action\"] = action\n payload[\"flood\"] = flood\n payload[\"moderate_flood\"] = moderate_flood\n payload[\"major_flood\"] = major_flood\n\n # API Post Payload\n if nwsid in water_nws_stages.keys():\n # site stages already in database, test for changes, if changes use put\n print(\n f\"NWS site {nwsid} already in DB. Checking for changes...\"\n )\n if (\n water_nws_stages[nwsid][\"action\"] != action\n or water_nws_stages[nwsid][\"flood\"] != flood\n or water_nws_stages[nwsid][\"moderate_flood\"]\n != moderate_flood\n or water_nws_stages[nwsid][\"major_flood\"] != major_flood\n ):\n water.put_nws_stages(nwsid, payload)\n put_items.append(nwsid)\n else:\n # new site stages record, use POST\n try:\n # POST single site stages to the water API\n water.post_nws_stages(payload)\n post_items.append(nwsid)\n except:\n continue\n\n # Show task as skipped if no work done\n if len(put_items) == 0 and len(post_items) == 0:\n raise AirflowSkipException\n\n return\n\n ########################################\n\n # Build two DAGSs\n # ----------------\n states = water.get_states()\n\n get_water_usgs_sites_task = PythonOperator(\n task_id=\"get_water_usgs_sites\", python_callable=get_water_usgs_site_numbers\n )\n\n get_nws_stages_task = PythonOperator(\n task_id=\"get_nws_stages\", python_callable=get_nws_stages\n )\n\n get_water_nws_stages_task = PythonOperator(\n task_id=\"get_water_nws_stages\", python_callable=get_water_nws_stages\n )\n\n for state in states:\n sync_task_id = f\"sync_nws_stages_{state}\"\n sync_nws_stages_task = PythonOperator(\n task_id=sync_task_id,\n python_callable=sync_nws_stages_to_water,\n op_kwargs={\n \"state\": state,\n \"nws_stages\": \"{{task_instance.xcom_pull(task_ids='get_nws_stages')}}\",\n \"water_nws_stages\": \"{{task_instance.xcom_pull(task_ids='get_water_nws_stages')}}\",\n \"water_usgs_site_numbers\": \"{{task_instance.xcom_pull(task_ids='get_water_usgs_sites')}}\",\n },\n )\n\n (\n get_nws_stages_task\n >> get_water_usgs_sites_task\n >> get_water_nws_stages_task\n >> sync_nws_stages_task\n )\n","repo_name":"USACE/airflow-config","sub_path":"dags/water/a2w_sync_nws_stages.py","file_name":"a2w_sync_nws_stages.py","file_ext":"py","file_size_in_byte":8070,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"}
+{"seq_id":"13786950156","text":"import os\nimport json\n\nimport torch\nimport torch.utils.data as data\nimport torchvision.transforms as transforms\nimport numpy as np\nimport pandas as pd\nfrom PIL import Image\n\nfrom randaugment import RandAugment\n\nclass miniImageNetData(data.Dataset):\n def __init__(self, phase, data_path, category_path, train_path, test_path, val_path, output_path, num_classes, rand_aug, logger):\n super(miniImageNetData, self).__init__()\n valid_phase = ['train', 'val', 'test']\n assert phase in valid_phase\n\n self.num_classes = num_classes\n self.dataset_info = {}\n self.phase = phase\n self.data_path = data_path\n self.train_path = train_path\n self.test_path = test_path\n self.val_path = val_path\n self.rand_aug = rand_aug\n\n self.transform = self.get_data_transform(phase)\n\n # load dataset category info\n logger.info('=====> Load dataset category info')\n self.id2label, self.label2id = self.load_data_info(category_path)\n\n # load all image info\n if phase == 'train':\n logger.info('=====> Load train image info')\n self.img_paths, self.labels = self.load_img_info(self.train_path)\n elif phase == 'val':\n logger.info('=====> Load val image info')\n self.img_paths, self.labels = self.load_img_info(self.val_path)\n else:\n logger.info('=====> Load test image info')\n self.img_paths, self.labels = self.load_img_info(self.test_path)\n\n # save dataset info\n logger.info('=====> Save dataset info')\n self.save_dataset_info(output_path)\n\n\n def __len__(self):\n return len(self.labels)\n\n\n def __getitem__(self, index):\n path = self.img_paths[index]\n label = self.labels[index]\n \n with open(path, 'rb') as f:\n sample = Image.open(f).convert('RGB')\n \n if self.transform is not None:\n sample = self.transform(sample)\n\n return sample, label, index\n\n\n #######################################\n # Load image info\n #######################################\n def load_img_info(self, path):\n data_file = pd.read_csv(path).values\n\n labels = []\n img_paths = []\n\n for item in data_file:\n name = item[1]\n label = self.label2id[item[2]]\n img_path = os.path.join(self.data_path, name)\n labels.append(label)\n img_paths.append(img_path)\n\n # save dataset info\n self.dataset_info['labels'] = labels\n self.dataset_info['img_paths'] = img_paths\n\n return img_paths, labels\n\n\n #######################################\n # Load dataset category info\n #######################################\n def load_data_info(self, path):\n id2label = {} # id to label, e.g., n02119789\n label2id = {} \n\n category_list = pd.read_csv(path).values\n\n for item in category_list:\n id = int(item[0])\n label = str(item[1])\n id2label[id] = label\n label2id[label] = id\n\n # save dataset info\n self.dataset_info['id2label'] = id2label\n self.dataset_info['label2id'] = label2id\n assert len(id2label) == self.num_classes\n assert len(label2id) == self.num_classes\n \n return id2label, label2id\n \n\n #######################################\n # Save dataset info\n #######################################\n def save_dataset_info(self, output_path):\n\n with open(os.path.join(output_path, 'dataset_info_{}.json'.format(self.phase)), 'w') as f:\n json.dump(self.dataset_info, f)\n\n del self.dataset_info\n\n\n #######################################\n # transform\n #######################################\n def get_data_transform(self, phase):\n transform_info = {}\n\n if phase == 'train':\n if self.rand_aug:\n trans = transforms.Compose([\n transforms.Resize(64),\n transforms.RandomCrop(64, padding=8, padding_mode='reflect'),\n RandAugment(),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n ])\n transform_info['operations'] = ['Resize(64)', 'RandomCrop(64)', 'RandAugment()', 'RandomHorizontalFlip()', 'ToTensor()',]\n else:\n trans = transforms.Compose([\n transforms.Resize(64),\n transforms.RandomCrop(64, padding=8, padding_mode='reflect'),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n ])\n transform_info['operations'] = ['Resize(64)', 'RandomCrop(64)', 'RandomHorizontalFlip()', 'ToTensor()',]\n else:\n trans = transforms.Compose([\n transforms.Resize(72),\n transforms.CenterCrop(64),\n transforms.ToTensor(),\n ])\n transform_info['operations'] = ['Resize(72)', 'CenterCrop(64)', 'ToTensor()',]\n \n # save dataset info\n self.dataset_info['transform_info'] = transform_info\n\n return trans","repo_name":"KaihuaTang/CiiV-Adversarial-Robustness.pytorch","sub_path":"data/dt_mini_imagenet.py","file_name":"dt_mini_imagenet.py","file_ext":"py","file_size_in_byte":5365,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"31"}
+{"seq_id":"74240030487","text":"class Solution:\n def maximumRequests(self, n: int, requests: List[List[int]]) -> int:\n def backtrack(idx, count):\n nonlocal max_count\n\n if idx == len(requests):\n # Check if the net change is zero for all buildings\n if all(balance == 0 for balance in balances):\n max_count = max(max_count, count)\n return\n\n from_building, to_building = requests[idx]\n\n # Simulate the request by decrementing the balance of the 'from_building'\n # and incrementing the balance of the 'to_building'\n balances[from_building] -= 1\n balances[to_building] += 1\n backtrack(idx + 1, count + 1)\n\n # Undo the request by decrementing the balance of the 'to_building'\n # and incrementing the balance of the 'from_building'\n balances[from_building] += 1\n balances[to_building] -= 1\n backtrack(idx + 1, count)\n\n max_count = 0\n balances = [0] * n\n\n backtrack(0, 0)\n\n return max_count\n","repo_name":"GunalanD95/LeetCode","sub_path":"1601-maximum-number-of-achievable-transfer-requests/1601-maximum-number-of-achievable-transfer-requests.py","file_name":"1601-maximum-number-of-achievable-transfer-requests.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"168577595","text":"import asyncio\nimport threading\nimport janus\n\nfrom asyncio import QueueEmpty as AsyncQueueEmpty\n\nfrom .singleton import Singleton\n\n# _____ _\n# | ___| | |\n# | |____ _____ _ __ | |_ ___\n# | __\\ \\ / / _ \\ '_ \\| __/ __|\n# | |___\\ V / __/ | | | |_\\__ \\\n# \\____/ \\_/ \\___|_| |_|\\__|___/\n#\n\n@Singleton\nclass Events():\n def __init__(self):\n \"\"\" Event class constructor\n \"\"\"\n self._loop = asyncio.new_event_loop()\n self._queue = janus.Queue(loop=self._loop)\n self._callback = {}\n self._callback_lock = threading.RLock()\n\n def start(self):\n while True:\n event_tuple = self._queue.sync_q.get()\n with self._callback_lock:\n event = event_tuple[0]\n if event in self._callback:\n for func in self._callback[event]:\n func(event_tuple[1])\n\n def register_callback(self, event, callback):\n with self._callback_lock:\n if event in self._callback:\n self._callback[event].append(callback)\n else:\n self._callback[event] = [callback]\n\n def notify(self, event, data):\n self._queue.sync_q.put((event, data))\n\n","repo_name":"peteremiljensen/freechain-python","sub_path":"events.py","file_name":"events.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"}
+{"seq_id":"74137161048","text":"# Aiogram\nfrom loader import dp, bot\nfrom aiogram import types\nfrom aiogram.types import LabeledPrice, ContentType\nfrom aiogram.dispatcher import FSMContext\n\n# Database\nfrom database.memberships_db import info_membersips\nfrom database.msg_id_history_db import add_message_from_bot\n\n# Other\nfrom keybords.menu_buttons import r_back_to_menu\nfrom other.func_other import dell_message\nfrom config import PAYMENT_TOKEN\n\n\n@dp.callback_query_handler(lambda c: c.data.startswith('abon'))\nasync def action_member_inline(c: types.CallbackQuery, state: FSMContext):\n\n id_membersip = int(c.data.split('-')[1])\n memberships_info = await info_membersips(id_membersip)\n\n await c.answer('Чудовий вибір👍🏻')\n\n if memberships_info[1] == 'Програма F3':\n msg = await bot.send_message(c.from_user.id,\n f'💳Абонемент: {memberships_info[1]}\\n\\n'\n f'🏋🏻Перелік послуг:\\n'\n f'- {memberships_info[4]} тренування з тренером\\n'\n f'- рекомендації по раціону харчування від дієтолога\\n'\n f'- контроль харчування дієтологом\\n'\n f'- заміри параметрів тіла раз на тиждень\\n'\n f'- фото \"до/після\" раз на тиждень\\n\\n'\n f'⏳Термін дії - {memberships_info[3]} місяць\\n\\n'\n f'▪️Ціна: {memberships_info[2]} грн',\n reply_markup=r_back_to_menu,\n parse_mode='HTML'\n )\n await dell_message(c.from_user.id)\n await add_message_from_bot(msg)\n else:\n msg = await bot.send_message(c.from_user.id,\n f'💳Абонемент: {memberships_info[1]}\\n\\n'\n f'🏋🏻Перелік послуг:\\n'\n f'- {memberships_info[4]} тренування з тренером\\n\\n'\n f'⏳Термін дії - {memberships_info[3]} місяць\\n\\n'\n f'▪️Ціна: {memberships_info[2]} грн',\n reply_markup=r_back_to_menu,\n parse_mode='HTML'\n )\n await dell_message(c.from_user.id)\n await add_message_from_bot(msg)\n\n msg = await bot.send_invoice(\n chat_id=c.from_user.id,\n title=f'Абонемент: {memberships_info[1]}',\n description='Ви за крок до спортивного та здорового тіла😎',\n payload='membership',\n provider_token=PAYMENT_TOKEN,\n currency='UAH',\n prices=[\n LabeledPrice(\n label=f'Абонемент: {memberships_info[1]}',\n amount=memberships_info[2] * 100\n ),\n ],\n )\n await add_message_from_bot(msg)\n\n\n await state.update_data(id_membersip=id_membersip)\n\n\n","repo_name":"KaliuzhnyiArtem/F3_bot","sub_path":"handlers/cliets/memberships.py","file_name":"memberships.py","file_ext":"py","file_size_in_byte":3373,"program_lang":"python","lang":"uk","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"}
+{"seq_id":"29934312601","text":"from svmutil import *\n\ntrainFile = '/home/manikaran/M.tech/MachineLearning/Assignment2/mnist/trainLibSVMScaled.txt'\ntestFile = '/home/manikaran/M.tech/MachineLearning/Assignment2/mnist/testLibSVMScaled.txt'\n\ny,x = svm_read_problem(trainFile)\n\n''' struct svm_problem describes the problem:\n\n struct svm_problem\n {\n int l;\n double *y;\n struct svm_node **x;\n };\n \n where `l' is the number of training data, and `y' is an array containing\n their target values. (integers in classification, real numbers in\n regression) `x' is an array of pointers, each of which points to a sparse\n representation (array of svm_node) of one training vector.'''\n\nproblem = svm_problem(y,x)\n\n''' struct svm_parameter describes the parameters of an SVM model \noptions:\n-s svm_type : set type of SVM (default 0)\n 0 -- C-SVC\n 1 -- nu-SVC''\n 2 -- one-class SVM\n 3 -- epsilon-SVR\n 4 -- nu-SVR\n-t kernel_type : set type of kernel function (default 2)\n 0 -- linear: u'*v\n 1 -- polynomial: (gamma*u'*v + coef0)^degree\n 2 -- radial basis function: exp(-gamma*|u-v|^2)\n 3 -- sigmoid: tanh(gamma*u'*v + coef0)\n-d degree : set degree in kernel function (default 3)\n-g gamma : set gamma in kernel function (default 1/num_features)\n-r coef0 : set coef0 in kernel function (default 0)\n-c cost : set the parameter C of C-SVC, epsilon-SVR, and nu-SVR (default 1)\n-n nu : set the parameter nu of nu-SVC, one-class SVM, and nu-SVR (default 0.5)\n-p epsilon : set the epsilon in loss function of epsilon-SVR (default 0.1)\n-m cachesize : set cache memory size in MB (default 100)\n-e epsilon : set tolerance of termination criterion (default 0.001)\n-h shrinking: whether to use the shrinking heuristics, 0 or 1 (default 1)\n-b probability_estimates: whether to train a SVC or SVR model for probability estimates, 0 or 1 (default 0)\n-wi weight: set the parameter C of class i to weight*C, for C-SVC (default 1)\n'''\nparam = svm_parameter('-t 0 -c 1 -g 0.05')\n\n'''Function: struct svm_model *svm_train(const struct svm_problem *prob,\n const struct svm_parameter *param);\n \n This function constructs and returns an SVM model according to\n the given training data and parameters.\n \n struct svm_model stores the model obtained from the training procedure.\n'''\n\nmodel = svm_train(problem,param)\n\n''' Function: double svm_predict(const struct svm_model *model,\n const struct svm_node *x);\n\n This function does classification or regression on a test vector x\n given a model. '''\nsvm_save_model('linearModel', model)\nyTest,xTest = svm_read_problem(testFile)\npredicted = svm_predict(yTest, xTest, model)\n\nyScaled,xScaled = svm_read_problem(trainFile)\nproblemScaled = svm_problem(yScaled,xScaled)\nparamScaled = svm_parameter('-t 2 -c 1 -g 0.05')\nmodelGaussianScaled = svm_train(problemScaled, paramScaled)\nyTestScaled,xTestScaled = svm_read_problem(testFile)\npredictedScaled = svm_predict(yTestScaled, xTestScaled, modelGaussianScaled)","repo_name":"Manikaran1996/NaiveBayesAndSVM","sub_path":"a2q2c.py","file_name":"a2q2c.py","file_ext":"py","file_size_in_byte":3038,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"12581571916","text":"\nfrom django.shortcuts import render\nfrom rest_framework.response import Response\nfrom .models import Video, Video_word\nfrom rest_framework.views import APIView\nfrom .serializers import VideoWordSerializer, VideoSerializer\n\n\nimport os \ncredential_path = \"C:/Users/82104/OneDrive/창업동아리/speech-to-text-333411-f6c9847c1934.json\"\nos.environ['GOOGLE_APPLICATION_CREDENTIALS'] = credential_path\n\nimport subprocess\nimport shlex\nimport datetime\n\n#영상 목록 보여주기\n\nclass fileUpload(APIView):\n \n def upload_blob(bucket_name, source_file_name, destination_blob_name):\n \"\"\"Uploads a file to the bucket.\"\"\"\n \n \n storage_client = storage.Client()\n bucket = storage_client.get_bucket(bucket_name)\n blob = bucket.blob(destination_blob_name)\n\n blob.upload_from_filename(source_file_name)\n\n print(\n \"File {} uploaded to {}.\".format(\n source_file_name, destination_blob_name\n )\n )\n\n# 영상 업로드\n def put(self, request, pk, format=None):\n\n bucket_name = \"sttbucket-fever\"\n # The path to your file to uplo\n source_file_name = \"C:/10.wav\"\n #os.path.abspath(source_file_name)\n # The ID of your GCS object\n destination_blob_name = \"test\"\n upload_blob(bucket_name, source_file_name, destination_blob_name)\n \n\n def get(self, request):\n queryset = Product.objects.all()\n print(queryset)\n serializer = ProductSerializer(queryset, many=True)\n return Response(serializer.data)\n\ndef transcribe_gcs(gcs_uri):\n from google.cloud import speech\n\n client = speech.SpeechClient()\n audio = speech.RecognitionAudio(uri=gcs_uri)\n config = speech.RecognitionConfig(\n encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,\n #sample_rate_hertz=16000,\n audio_channel_count=2,\n enable_word_time_offsets=True,\n language_code='ko-KR')\n operation = client.long_running_recognize(config=config,audio=audio)\n response = operation.result(timeout=3000)\n #return response\n #response = transcribe_gcs(\"gs://sttbucket-fever/10.wav\")\n\n import json\n from collections import OrderedDict\n file_data = OrderedDict()\n\n for result in response.results:\n alternative = result.alternatives[0]\n print(\"Transcript: {}\".format(alternative.transcript))\n print(\"Confidence: {}\".format(alternative.confidence))\n\n for word_info in alternative.words:\n word = word_info.word\n start_time = word_info.start_time.total_seconds()\n end_time = word_info.end_time.total_seconds()\n file_data['video_id'] = 1\n file_data['word'] = word\n file_data['start_time'] = start_time\n file_data['end_time'] = end_time\n file_data['date'] = \"2021-11-29\"\n\n serializer = VideoWordSerializer(data=file_data)\n\n if serializer.is_valid(): #유효성 검사\n serializer.save() # 저장\n\n \n#영상 편집하기\nclass VideoEdit(APIView):\n # 참가 인원 추가하기\n def post(self, request):\n # request.data는 사용자의 입력 데이터\n serializer = VideoWordSerializer(data=request.data)\n if serializer.is_valid(): #유효성 검사\n serializer.save() # 저장\n return Response({\"MESSAGE\" : \"Success!\"}, status=status.HTTP_201_CREATED)\n #return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n return Response({\"MESSAGE\" : \"ERORR\"}, status=status.HTTP_400_BAD_REQUEST)\n\n\n \n #영상 스크립트 생성\n def get(self, request):\n \n #transcribe_gcs(\"gs://sttbucket-fever/10.wav\")\n queryset = Video_word.objects.all()\n serializer = VideoWordSerializer(queryset, many=True)\n return Response(serializer.data)\n \n\n \n#특정 단어 없애기\nclass ScriptDelete(APIView):\n def delete(self, request, format=None):\n\n cid = Video_word.objects.filter(video_id = request.data[\"video_id\"]).filter(wid = request.data[\"wid\"])\n #print(cid,\"에러에러에러에러에러에러에러\")\n cid.delete()\n return Response({\"MESSAGE\" : \"Success!\"}) \n\n#영상 합치기\nclass VideoPlus(APIView):\n\n def get(self, request):\n #transcribe_gcs(\"gs://sttbucket-fever/10.wav\")\n\n queryset = Video_word.objects.filter(video_id = request.data[\"video_id\"]).values('start_time','end_time','wid')\n #serializer = VideoWordSerializer(queryset, many=True)\n #print(queryset)\n\n\n delete = {}\n i = 0\n \n for idx, val in enumerate(queryset): \n #print(idx,val)\n \n\n #wid가 +1이 아니면..\n try:\n next = queryset[idx+1]\n except:\n break\n\n try:\n front = queryset[idx-1]\n except:\n break\n\n #삭제된 구간찾기\n if(val['wid']+1 != next['wid']):\n \n delete['idx'] = i\n delete['start'] = val['end_time']\n delete['end'] = next['start_time']\n i=i+1\n\n \n start = \"0\"\n hall = []\n if(val['wid']+1 != next['wid']):\n \n\n time = {}\n time['start'] = 0\n time['end'] = val[\"end_time\"]\n\n\n hall +=time\n\n time['start']\n\n \n print(delete,\"에러에러에러에러에러에러에러에러\")\n\n start = '0'\n \n for idx, val in enumerate(delete):\n \n try:\n next = delete[idx+1]\n except:\n break\n \n end = val['start']\n vname = idx+'.mp4'\n \n\n #동영상 자르기\n command=\"ffmpeg -i input.mp4 -ss \"+start+\"-to \"+end+ \"-c copy \"+ vname\n \n\n #동영상 합치기\n command2 = \"ffmpeg -f concat -i 'list.txt' -c copy output.mp4\"\n\n process = subprocess.Popen(shlex.split(command), stdout = subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)\n \n for line in process.stdout:\n now = datetime.datetime.now()\n print(now, line)\n\n\n return Response({\"MESSAGE\" : \"Success!\"}) \n\n #return Response(serializer.data)","repo_name":"fever-fever-fever/STT-Back","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6614,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"16706667919","text":"from Snake import Snake\nfrom Board import Board\nfrom SnakeBody import SnakeBody\nfrom Food import Food\nfrom collections import defaultdict\nimport pygame\nimport time\nimport numpy as np\nimport random\n\n\nglobal clock\nglobal window_width\nglobal window_height\nglobal display_width\nglobal display_height\nglobal game\nglobal sleep\n\nglobal score\nglobal game_display\nglobal snake\nglobal food\n\nglobal font\nglobal text\n\nglobal x_change\nglobal y_change\nglobal first_time\nglobal eat\nglobal mov\nglobal maxScore \nglobal gen\n\ndef setTimeSleepUp():\n sleep+=0.01\n \ndef setTimeSleepDown():\n sleep-=0.01 \n\ndef sscore(_score,maxsc):\n text1 = font.render(\"Score: \" + str(_score), False, Board.teal)\n game_display.GAME_display.blit(text1, (game_display.width - 150, 100))\n \n text2 = font.render(\"Max score: \" + str(maxsc), False, Board.red)\n game_display.GAME_display.blit(text2, (game_display.width - 150, 130))\n \n text3 = font.render(\"Game number: \" + str(gen), False, Board.blue_black)\n game_display.GAME_display.blit(text3, (game_display.width - 150, 70))\n \n text4 = font.render(\"Speed: \" + str(sleep), False, Board.red)\n game_display.GAME_display.blit(text4, (game_display.width - 150, 160))\n\n\ndef update_data_set(data_set, mov, snake, food):\n # initDataSet('DataSets.csv')\n new_row = np.array([0] * 66) # initiate a new row of 0\n new_row[((int(food.food_y / 10) - 1) * 8) + ((int(food.food_x / 10) - 1))] = 1 # computes the index of the food and puts 1.\n for i in range(0, (len(snake) - 1)):\n if i == 0:\n new_row[((int(snake[i].y / 10) - 1) * 8) + ((int(snake[i].x / 10) - 1))] = 3 # computes the index of the head and puts 3.\n else:\n new_row[((int(snake[i].y / 10) - 1) * 8) + ((int(snake[i].x / 10) - 1))] = 2 # computes the index of the food and puts 2.\n\n new_row[65] = mov # The action we took.\n\n data_set = np.vstack([data_set, new_row]) # Stacks the row into the CSV file.\n return data_set\n\ndef what_is_cur_state(snake, food):\n head_pos = [(int(snake[0].y / 10) - 1),(int(snake[0].x / 10) - 1)]\n tail_pos = [(int(snake[len(snake)-1].y / 10) - 1),(int(snake[len(snake)-1].x / 10) - 1)]\n food_pos = [(int(food.food_y / 10) - 1), (int(food.food_x / 10) - 1)]\n tail_rel = ((head_pos[1]-tail_pos[1]),(head_pos[0]-tail_pos[0]))\n food_rel = ((head_pos[1]-food_pos[1]),(head_pos[0]-food_pos[0]))\n \n return (tail_rel,food_rel,len(snake))\n\ndef reset():\n global clock\n global window_width\n global window_height\n global display_width\n global display_height\n global game\n global score\n global game_display\n global snake\n global food\n #global _score\n global font\n global text\n global gen\n global x_change\n global y_change\n global first_time\n global eat\n global mov\n global maxScore \n global sleep\n\n score = 60\n game_display = Board(window_width, window_height)\n snake = Snake(20, 20, 3)\n food = Food(10, display_width, display_height, 10, snake)\n \n font = pygame.font.SysFont('Time New Roman, Arial', 20)\n #text = font.render('Score: %d' % tuple([game_display.game_score]), False, Board.gold)\n\n x_change = 0\n y_change = 0\n first_time = True\n eat = True\n mov = 0\n \n return what_is_cur_state(snake,food)\n \ndef step(action):\n global clock\n global window_width\n global window_height\n global display_width\n global display_height\n global game\n global score\n global game_display\n global snake\n global food\n \n global font\n global text\n global gen\n global x_change\n global y_change\n global first_time\n global eat\n global mov\n global maxScore \n \n reward = -0.25\n for event in pygame.event.get():\n if event.type == pygame.QUIT: # if clicked on the window's X.\n pygame.quit()\n game = False\n# if event.type == pygame.KEYDOWN:\n# if event.key == pygame.K_UP: # if it was the up arrow\n# setTimeSleepUp()\n# elif event.key == pygame.K_DOWN: # if it was the down arrow\n# setTimeSleepDown()\n \n #first_time = False\n if action==4: # if it was the left arrow\n if x_change != 10:\n x_change = -10\n y_change = 0\n mov = 4\n elif action==6: # if it was the right arrow\n if x_change != -10:\n x_change = 10\n y_change = 0\n mov = 6\n elif action==8: # if it was the up arrow\n if y_change != 10:\n x_change = 0\n y_change = -10\n mov = 8\n elif action==2: # if it was the down arrow\n if y_change != -10:\n x_change = 0\n y_change = 10\n mov = 2\n #if not first_time: # if it's while we haven't clicked anything when the window pops.\n #data_sets = update_data_set(data_sets, mov, snake, food)\n snake.update(score)\n if score % 10 == 0 and eat: # still need to figure out.--------------\n snake.append(SnakeBody(snake[len(snake) - 1].x, snake[len(snake) - 1].y))\n print(len(snake))\n eat = False\n snake.move_head(x_change, y_change) # changes the head's x,y. making it \"move\"\n state = what_is_cur_state(snake,food)\n\n if (snake[0].x < food.food_x + 10 and snake[0].x >= food.food_x\n and snake[0].y < food.food_y + 10 and snake[0].y >= food.food_y):\n score += 10\n game_display.game_score += 1\n food = Food(10, display_width, display_height, 10, snake)\n eat = True\n reward = 1\n\n if snake.check_death(display_width, display_height):\n #if game_display.pop_exit_window():#):\n reward = -1\n state = what_is_cur_state(snake,food)\n done = (len(snake)==64)\n state = what_is_cur_state(snake,food)\n print (\"death\")\n return state, reward, done\n\n game_display.clean()\n game_display.borders(display_height, display_width)\n pygame.draw.rect(game_display.GAME_display, Board.red,\n (food.food_x, food.food_y, Snake.factor, Snake.factor))\n snake.draw(game_display.GAME_display)\n #game_display.GAME_display.blit(text, (game_display.width - 50, 50))############################\n #max_score(len(snake)-4)\n if maxScore < len(snake)-4:\n maxScore = game_display.game_score\n \n sscore(len(snake)-4, maxScore)\n pygame.display.flip()\n time.sleep(0.120)\n clock.tick(60)\n \n done = (len(snake)==64)\n return state, reward, done\n\n\n\n\ndef main():\n \n global clock\n global window_width\n global window_height\n global display_width\n global display_height\n global game\n global maxScore \n global gen\n global sleep\n clock = pygame.time.Clock()\n window_width = 300\n window_height = 300\n display_width = 80\n display_height = 80\n sleep = 0.005\n game = True\n \n action_space = [2,4,6,8]\n Q = defaultdict(dict)\n alpha = 0.618\n \n for episode in range(1,500000):\n done = False\n G, rwrd = 0,0\n maxScore=0\n gen = 1\n \n state = reset()\n while not done:\n if state in Q:\n action = (np.argmax(Q[state])+1)*2\n else:\n Q[state] = np.zeros([4])\n action = (np.argmax(Q[state])+1)*2\n nxt_state, rwrd, done = step(action)\n if state in Q:\n if action in Q[state]:\n if nxt_state in Q:\n Q[state][int(action/2)-1] += alpha * (rwrd + np.max(Q[nxt_state]) - Q[state][action])\n else:\n Q[state][int(action/2)-1] += ((alpha * rwrd) - Q[state][action])\n else:\n if nxt_state in Q:\n Q[state][int(action/2)-1] = alpha * (rwrd + np.max(Q[nxt_state]))\n else:\n Q[state][int(action/2)-1] = (alpha * rwrd)\n else:\n Q[state] = np.zeros([4])\n if nxt_state in Q:\n Q[state][int(action/2)-1] = alpha * (rwrd + np.max(Q[nxt_state]))\n else:\n Q[state][int(action/2)-1] = (alpha * rwrd)\n G += rwrd\n state = nxt_state\n if rwrd == -1:\n gen+=1\n state = reset()\n\n #data_sets = np.arange(66)\n\n #while True: # while the program runs.\n \n \n \n\nif __name__ == \"__main__\":\n main()\n","repo_name":"nunii/AI-Snake","sub_path":"AI-Snake/RL.py","file_name":"RL.py","file_ext":"py","file_size_in_byte":8503,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"11454776651","text":"\"\"\"\nCore XML Parsing of RSS documents. This is generally focused on RSS 2.0\n\"\"\"\nimport requests\nfrom xml.etree import ElementTree\nfrom pprint import pprint\nimport csv\nfrom pathlib import Path\nfrom urllib.parse import urlparse\nimport datetime\nfrom typing import NamedTuple, List\n\nclass SourceRSS(NamedTuple):\n \"\"\"Extract of raw RSS data\"\"\"\n title: str #: The title\n link: str #: The link\n description: str #: The description\n pubDate: str #: The publication date\n\n\nclass ExpandedRSS(NamedTuple):\n \"\"\"\n Data expanded by the :func:`title_transform()` function.\n\n Note that the names of the fields in this class will be the column\n titles on saved CSV files. Any change here will be reflected in the files\n created.\n \"\"\"\n title: str #: The title\n link: str #: The link\n description: str #: The description\n pubDate: str #: The publication date\n docket: str #: The parsed docket from the title\n parties_title: str #: The parsed parties from the title\n\n\ndef xml_reader(url: str) -> List[SourceRSS]:\n \"\"\"\n Extract RSS data given a URL to read.\n\n The root document is the ```` tag which has a single ```` tag.\n The ```` has some overall attributes, but contains a sequence\n of ```` tags.\n\n This will gather \"title\", \"link\", \"description\", and \"pubDate\" from each item\n and build a :class:`SourceRSS` object.\n\n It might be helpful to return the overall channel properties along with\n the list of items.\n\n :param url: URL to read.\n :return: All of the SourceRSS from the channel of the feed, List[SourceRSS].\n \"\"\"\n items = []\n response = requests.get(url)\n rss = ElementTree.fromstring(response.content)\n channel = rss.find('channel')\n\n # Dump the overall channel properties\n print(\"title\", channel.findtext('title'))\n print(\"link\", channel.findtext('link'))\n print(\"description\", channel.findtext('description'))\n print(\"last build date\", channel.findtext('lastBuildDate'))\n\n for item in channel.iter('item'):\n item_row = SourceRSS(\n title=item.findtext('title'),\n link=item.findtext('link'),\n description=item.findtext('description'),\n pubDate=item.findtext('pubDate'),\n )\n items.append(item_row)\n return items\n\ndef title_transform(items: List[SourceRSS]) -> List[ExpandedRSS]:\n \"\"\"\n A \"transformation\": this will parse titles for court docket RSS feeds.\n\n >>> from rss_status import title_transform, SourceRSS, ExpandedRSS\n\n The data is a list witha single document [SourceRSS()]\n\n >>> data = [\n ... SourceRSS(\n ... title='1:15-cv-00791 SAVAGE v. BURWELL et al',\n ... link='https://ecf.dcd.uscourts.gov/cgi-bin/DktRpt.pl?172013',\n ... description='[Reply to opposition to motion] (137)',\n ... pubDate='Thu, 05 Jul 2018 06:26:07 GMT'\n ... ),\n ... ]\n >>> title_transform(data)\n [ExpandedRSS(title='1:15-cv-00791 SAVAGE v. BURWELL et al', link='https://ecf.dcd.uscourts.gov/cgi-bin/DktRpt.pl?172013', description='[Reply to opposition to motion] (137)', pubDate='Thu, 05 Jul 2018 06:26:07 GMT', docket='15-cv-00791', parties_title='SAVAGE v. BURWELL et al')]\n\n :param items: A list of :class:`SourceRSS` items built by :func:`xml_reader`\n :return: A new list of :class:`ExpandedRSS`, with some additional attributes for each item.\n \"\"\"\n new_items = []\n for row in items:\n docket, _, parties_title = row.title.partition(' ')\n _, _, real_docket = docket.partition(\":\")\n result = ExpandedRSS(\n title=row.title,\n link=row.link,\n description=row.description,\n pubDate=row.pubDate,\n docket=real_docket,\n parties_title=parties_title,\n )\n new_items.append(result)\n return new_items\n\ndef csv_dump(data: List[ExpandedRSS], output_path: Path) -> None:\n \"\"\"\n Save expanded data to a file, given the Path.\n\n Note that the headers are the field names from the ExpandedRSS class definition.\n This assures us that all fields will be written properly.\n\n :param data: List of :class:`ExpandedRSS` items, built by :func:`title_transform`.\n :param output_path: Path to which to write the file.\n \"\"\"\n with output_path.open('w', newline='') as output_file :\n headings = list(ExpandedRSS._fields)\n writer = csv.DictWriter(output_file, headings)\n writer.writeheader()\n for row in data:\n writer.writerow(row._asdict())\n\n\ndef csv_load(input_path: Path) -> List[ExpandedRSS]:\n \"\"\"\n Recover expanded data from a file, given a Path.\n\n Note that the headers **must be** the field names from the ExpandedRSS class definition.\n If their isn't a trivial match, then this won't read properly.\n\n :param input_path: Path from which to read the file.\n :returns: List of ExpandedRSS objects used to compare previous day's feed\n with today's feed.\n \"\"\"\n data = []\n with input_path.open() as input_file:\n reader = csv.DictReader(input_file)\n for row in reader:\n expanded_rss = ExpandedRSS(**row)\n data.append(expanded_rss)\n return data\n\n\ndef path_maker(url: str, now: datetime.datetime=None, format: str=\"%Y%m%d\") -> Path:\n \"\"\"\n Builds a Path from today's date and the base name of the URL.\n\n The default format is \"%Y%m%d\" to transform the date to a YYYYmmdd string.\n An alternative can be \"\"%Y%W%w\" to create a YYYYWWw string,\n where WW is the week of the year and w is the day of the week.\n\n >>> from rss_status import path_maker\n >>> import datetime\n >>> now = datetime.datetime(2018, 9, 10)\n >>> str(path_maker(\"https://ecf.dcd.uscourts.gov/cgi-bin/rss_outside.pl\", now))\n '20180910/rss_outside'\n\n :param url: An RSS-feed URL.\n :param now: Optional date/time object. Defaults to datetime.datetime.now().\n :return: A Path with the date string / base name from the URL.\n \"\"\"\n url_details = urlparse(url)\n base_name = Path(url_details.path).stem\n if not now:\n now = datetime.datetime.now()\n today_str = now.strftime(format)\n return Path(today_str) / base_name\n\n\ndef find_yesterday(directory: Path, url: str, date_pattern: str='[0-9]*') -> Path:\n \"\"\"\n We need to search for the most recent previous entry. While we can hope for\n dependably running this every day, that's a difficult thing to guarantee.\n\n It's much more reliable to look for the most recent date which\n contains files for a given channel. This means\n\n Example. Here's two dates. One date has one channel, the other has two channels.\n\n ::\n\n 20180630/one_channel/daily.csv\n 20180630/one_channel/new.csv\n 20180630/one_channel/save.csv\n 20180701/one_channel/daily.csv\n 20180701/one_channel/new.csv\n 20180701/one_channel/save.csv\n 20180701/another_channel/daily.csv\n 20180701/another_channel/new.csv\n 20180701/another_channel/save.csv\n\n If there's nothing available, returns None.\n\n :param directory: The base directory to search\n :param url: The full URL from which we can get the base name\n :param date_pattern: Most of the time, the interesting filenames will begin with a digit\n If the file name pattern is changed, however, this can be used to match dates,\n and exclude non-date files that might be confusing.\n :return: A Path with the date string / base name from the URL or None.\n \"\"\"\n url_details = urlparse(url)\n base_name = Path(url_details.path).stem\n candidates = list(directory.glob(f\"{date_pattern}/{base_name}\"))\n if candidates:\n return max(candidates)\n\n\ndef channel_processing(url: str, directory: Path=None, date: datetime.datetime=None):\n \"\"\"\n The daily process for a given channel.\n\n Ideally there's a \"yesterday\" directory. Pragmatically, this may not exist.\n We use :func:`find_yesterday` to track down the most recent file and\n work with that. If there's no recent file, this is all new. Welcome.\n\n :param url: The URL for the channel\n :param directory: The working directory, default is the current working directory.\n :param date: The date to assign to the files, by default, it's datetime.datetime.now.\n \"\"\"\n if directory is None:\n directory = Path.cwd()\n\n if date is None:\n date = datetime.datetime.now()\n\n yesterdays_path = find_yesterday(directory, url)\n todays_path = path_maker(url)\n\n todays_data = title_transform(xml_reader(url))\n if yesterdays_path:\n saved_data = csv_load(yesterdays_path / \"save.csv\")\n else:\n saved_data = []\n\n new_data = set(todays_data) - set(saved_data)\n all_data = set(todays_data) | set(saved_data)\n\n todays_path.mkdir(parents=True, exist_ok=True)\n csv_dump(todays_data, todays_path / \"daily.csv\")\n csv_dump(new_data, todays_path / \"new.csv\")\n csv_dump(all_data, todays_path / \"save.csv\")\n\n\ndef demo():\n \"\"\"\n This is downloads, enriches, and saves the daily files to the current\n working directory.\n \"\"\"\n target_path = Path.cwd()\n\n data1 = xml_reader(\"https://ecf.dcd.uscourts.gov/cgi-bin/rss_outside.pl\")\n data1_decomposed = title_transform(data1)\n # pprint(data1_decomposed)\n csv_dump(data1_decomposed, target_path / \"file1.csv\")\n\n data2 = xml_reader(\"https://ecf.nyed.uscourts.gov/cgi-bin/readyDockets.pl\")\n data2_decomposed = title_transform(data2)\n # pprint(data2_decomposed)\n csv_dump(data2_decomposed, target_path / \"file2.csv\")\n\n recovered = csv_load(target_path / \"file2.csv\")\n assert set(recovered) == set(data2_decomposed), \"Weird, recovering the file was a problem.\"\n\n\nif __name__ == \"__main__\":\n # demo()\n for channel_url in (\n \"https://ecf.dcd.uscourts.gov/cgi-bin/rss_outside.pl\",\n \"https://ecf.nyed.uscourts.gov/cgi-bin/readyDockets.pl\",\n # More channels here.\n ):\n channel_processing(channel_url)","repo_name":"slott56/simple-rss-status","sub_path":"rss_status.py","file_name":"rss_status.py","file_ext":"py","file_size_in_byte":10174,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"}
+{"seq_id":"29475753678","text":"from flask import Blueprint, Markup, session, redirect, request, render_template\nfrom datetime import datetime\nfrom server.db import Payed, get_data\n\n\nrouter = Blueprint(\"index\", __name__)\n\n@router.route('/', methods=['GET'])\ndef index():\n if \"username\" not in session:\n return redirect(\"/login\")\n\n msg = ''\n if \"msg\" in session:\n msg = session['msg']\n session.pop('msg', None)\n\n date = ''\n if request.remote_addr == \"192.168.6.111\":\n try:\n date = request.args.get('date')\n except:\n pass\n\n data = get_data(date)\n\n week = datetime.now().strftime(\"%U\")\n guys1 = []\n\n for i in range(1, 4):\n ll = Payed.find({\"week\": str(int(week) - i), \"payed\": 0})\n if ll is None:\n break\n for l in ll:\n guys1.append(l)\n payed = True\n\n for guy in guys1:\n if guy['name'] == session['username']:\n payed = False\n break\n\n return render_template('index.html', msg=Markup(msg), image_list=data, payed=payed)\n","repo_name":"clitetailor/mummum","sub_path":"server/routes/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"40776871308","text":"import numpy as np\nimport pandas as pd\n\ndef csv_to_close(csv_filepath, field_names):\n \"\"\"\n Returns\n -------\n close : DataFrame\n Close prices for each ticker and date\n \"\"\"\n \n price_df = pd.read_csv(csv_filepath, names=field_names)\n\n close_prices = price_df.pivot(index='date', columns='ticker', values='close')\n \n print(close_prices)\n \n return close_prices\n \ndef days_to_weeks(open_prices, high_prices, low_prices, close_prices):\n \"\"\"\n Returns\n -------\n open_prices_weekly : DataFrame\n Weekly open prices for each ticker and date\n high_prices_weekly : DataFrame\n Weekly high prices for each ticker and date\n low_prices_weekly : DataFrame\n Weekly low prices for each ticker and date\n close_prices_weekly : DataFrame\n Weekly close prices for each ticker and date\n \"\"\"\n # print(open_prices.resample('W').first())\n \n return open_prices.resample('W').first(),high_prices.resample('W').high(), low_prices.resample('W').last(), close_prices.resample('W').last()\n\n\ndates = pd.date_range('10/10/2018', periods=11, freq='D')\nclose_prices = np.arange(len(dates))\n\nclose = pd.Series(close_prices, dates)\nclose","repo_name":"kamleshg/fin-ml","sub_path":"sample.py","file_name":"sample.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"7342003196","text":"from sequence_lib import read_fasta\nfrom rand_aln_prob import rand_Aln\nfrom math import log,sqrt\nfrom FastSP import FastSP\n\nclass merger:\n\tdef __init__(self,ref_aln_file):\n\t\ttaxa_names, ref_aln = read_fasta(ref_aln_file)\n\t\tself.ref_aln = ref_aln\t\n\t\tself.tax2seqidx = {}\n\t\tself.wp = 1 # P(true|ref_aln): probability that a homology is true given it is found in ref_aln (modeler)\n\t\tself.wn = 0 # P(true|~ref_aln): probability that a homology not found in ref_aln is true\n\t\t\t # = P(true|~ref_aln) = P(~ref_aln|true)*P(true)/P(~ref_aln) = SPFN*P(true)/P(~ref_aln)\n\n\t\tfor i in range(len(taxa_names)):\n\t\t\tself.tax2seqidx[taxa_names[i]] = i\n\n\tdef show_taxa(self):\n\t\treturn self.tax2seqidx.keys()\n\n\tdef seqidx(self,tax):\n\t\treturn self.tax2seqidx[tax]\n\n\tdef __eval(self,aln,taxa):\n\t\tM = []\n\t\tcount = 0\n\t\tsubtr = 0\n\n\t\tfor i,tax in enumerate(taxa):\n\t\t\tM.append(self.ref_aln[self.tax2seqidx[tax]])\n\t\t\tl = len([x for x in aln[i] if x != '-'])\n\t\t\tcount += l\n\t\t\tsubtr += l*(l-1)/2\n\n\t\thshared,hA,hM = FastSP(aln,M)\n\t\th_all=count*(count-1)/2 - subtr\n\t\twp = 1.0*hshared/hM\n\t\twn = (1.0-hshared/hA)*hA/(h_all-hM)\n\t\t\n\t\treturn wp,wn\n\n\tdef evalRef(self,aln1,taxa1,aln2=None,taxa2=None):\n\t\twp1,wn1 = self.__eval(aln1,taxa1)\n\n\t\tif aln2 is None or taxa2 is None:\n\t\t\tself.wp = wp1\n\t\t\tself.wn = wn1\n\t\telse:\n\t\t\twp2,wn2 = self.__eval(aln2,taxa2)\n\t\t\tself.wp = sqrt(wp1*wp2)\n\t\t\tself.wn = sqrt(wn1*wn2)\n\t\t\n\n\tdef ref_matching(self,aln1,taxa1,aln2,taxa2):\n\t\tm = len(self.ref_aln[0])\n\t\tn = len(aln1) + len(aln2)\n\t\tmatching = [[-1 for x in range(m)] for y in range(n)]\n\t\t#match1 = [[-1 for x in range(len(aln1[0])+1)] for y in range(len(aln1))] # the last column stores the length of each sequence\n\t\t#match2 = [[-1 for x in range(len(aln2[0])+1)] for y in range(len(aln2))] # the last column stores the length of each sequence\n\n\t\t# match aln1 to ref_aln\n\t\tfor j1 in range(len(aln1)):\n\t\t\ttax = taxa1[j1]\n\t\t\tj = self.seqidx(tax)\n\t\t\ti1 = 0\n\t\t\tk = 0\n\t\t\t#gap1 = 0\n\t\t\tfor i in range(m):\n\t\t\t\tif self.ref_aln[j][i] == '-':\n\t\t\t\t\t#gap1 += 1\n\t\t\t\t\tcontinue\n\t\t\t\twhile aln1[j1][i1] == '-':\n\t\t\t\t\ti1 += 1\n\t\t\t\t#match1[j1][i1] = k\n\t\t\t\tk += 1\n\t\t\t\tif aln1[j1][i1] == self.ref_aln[j][i]:\n\t\t\t\t\tmatching[j1][i] = i1\n\t\t\t\t\ti1 += 1\n\t\t\t\telse:\n\t\t\t\t\tprint(\"reference alignment and alignment 1 are not matched at taxon \" + tax)\n\t\t\t#match1[j1][len(aln1[0])] = k\n\t\t# match aln2 to ref_aln\n\t\tfor j2 in range(len(aln2)):\n\t\t\ttax = taxa2[j2]\n\t\t\tj = self.seqidx(tax)\n\t\t\ti2 = 0\n\t\t\tk = 0\n\t\t\tgap2 = 0\n\t\t\tfor i in range(m):\n\t\t\t\tif self.ref_aln[j][i] == '-':\n\t\t\t\t\t#gap2 += 1\n\t\t\t\t\tcontinue\n\t\t\t\twhile aln2[j2][i2] == '-':\n\t\t\t\t\ti2 += 1\n\t\t\t\t#match2[j2][i2] = k\n\t\t\t\tk += 1\n\t\t\t\tif aln2[j2][i2] == self.ref_aln[j][i]:\n\t\t\t\t\tmatching[j2+len(aln1)][i] = i2\n\t\t\t\t\ti2 += 1\n\t\t\t\telse:\n\t\t\t\t\tprint(\"reference alignment and alignment 2 are not matched at taxon \" + tax)\n\t\t\t#match2[j2][len(aln2[0])] = k\n\t\treturn matching #,match1,match2\n\n\tdef residue_count(self,aln):\n\t\tR = []\n\t\tfor j in range(len(aln[0])):\n\t\t\tR += [0]\n\t\t\tfor i in range(len(aln)):\n\t\t\t\tif aln[i][j] != '-':\n\t\t\t\t\tR[j] += 1\n\t\treturn R\n\n\tdef heuristic_score(self,aln1,taxa1,aln2,taxa2,w=1):\n\t\tR1 = self.residue_count(aln1)\n\t\tR2 = self.residue_count(aln2)\t\t\n\t\tmatching = self.ref_matching(aln1,taxa1,aln2,taxa2)\n\t\tm = len(matching[0])\n\t\tn = len(matching)\n\t\tscore_tab = {}\n\t\t\n\t\tfor i in range(len(aln1[0])):\n\t\t\tscore_tab[(i,-1)] = 0\n\n\t\tfor j in range(len(aln2[0])):\n\t\t\tscore_tab[(-1,j)] = 0\n\t\t\n\t\tfor i in range(len(aln1[0])):\n\t\t\tfor j in range(len(aln2[0])):\n\t\t\t\tscore_tab[(i,j)] = (w-1)*R1[i]*R2[j]\n\t\t\t\n\t\tfor i in range(m):\n\t\t\tL1 = []\n\t\t\td1 = {}\n\t\t\tL2 = []\n\t\t\td2 = {}\n\t\t\tfor j in range(n):\n\t\t\t# below L and d are used as \"references\" (just as pointers in C++): they are not deep copy, but a shallow copy of L1|L2 and d1|d2\n\t\t\t\tif j < len(aln1):\n\t\t\t\t\tL = L1\n\t\t\t\t\td = d1\n\t\t\t\telse:\n\t\t\t\t\tL = L2\n\t\t\t\t\td = d2\n\t\t\t\tif matching[j][i] >= 0:\n\t\t\t\t\tif matching[j][i] in d:\n\t\t\t\t\t\td[matching[j][i]] += 1\n\t\t\t\t\telse:\n\t\t\t\t\t\tL += [matching[j][i]]\n\t\t\t\t\t\td[matching[j][i]] = 1\n\t\t\tfor x in L1:\n\t\t\t\tfor y in L2:\n\t\t\t\t\tscore_tab[(x,y)] += (2*w-1)*d1[x]*d2[y]\n\n\n\t\treturn score_tab,R1,R2 #,m1,m2\n\n\tdef TP_score(self,aln1,taxa1,aln2,taxa2):\n\t\treturn self.heuristic_score(aln1,taxa1,aln2,taxa2,w=1)\n\n\tdef llh_score(self,aln1,taxa1,aln2,taxa2):\n\t\tTP_score,R1,R2 = self.TP_score(aln1,taxa1,aln2,taxa2)\n\t\tscore_tab = {}\n\n\t\tself.evalRef(aln1,taxa1,aln2,taxa2)\n\t\tprint(self.wp,self.wn)\n\n\t\tfor j in range(len(aln2[0])):\n\t\t\tscore_tab[(-1,j)] = 0\n\t\t\tfor i in range(len(aln1[0])):\n\t\t\t\tH_ij = R1[i]*R2[j]\n\t\t\t\tp = 1.0-(self.wp*TP_score[(i,j)]+self.wn*(H_ij-TP_score[(i,j)]))/H_ij\n\t\t\t\tscore_tab[(-1,j)] += log(p)\n\n\t\tfor i in range(len(aln1[0])):\n\t\t\tscore_tab[(i,-1)] = 0\n\t\t\tfor j in range(len(aln2[0])):\n\t\t\t\tH_ij = R1[i]*R2[j]\n\t\t\t\tp = 1.0-(self.wp*TP_score[(i,j)]+self.wn*(H_ij-TP_score[(i,j)]))/H_ij\n\t\t\t\t#print(p)\n\t\t\t\tscore_tab[(i,-1)] += log(p)\n\n\t\tfor (i,j) in TP_score:\n\t\t\tH_ij = R1[i]*R2[j]\n\t\t\tscore_tab[(i,j)] = log((self.wp*TP_score[(i,j)]+self.wn*(H_ij-TP_score[(i,j)]))/H_ij)\n\n\t\treturn score_tab\n\t\n\tdef logodd_score(self,aln1,taxa1,aln2,taxa2,rand_P):\n\t\t#score_tab,match1,match2= self.heuristic_score(aln1,taxa1,aln2,taxa2)\n\t\tscore_tab,R1,R2 = self.heuristic_score(aln1,taxa1,aln2,taxa2)\n\t\t#print(gap_rate1)\n\t\t#print(gap_rate2)\n\t\tfor key in score_tab:\n\t\t\t'''\n\t\t\tprint(key)\n\t\t\tp = 0\n\t\t\tfor s1 in match1:\n\t\t\t\tfor s2 in match2:\n\t\t\t\t\tif s1[key[0]] >= 0 and s2[key[1]] >= 0 :\n\t\t\t\t\t\tp += rand_P.prob(s1[-1],s2[-1],s1[key[0]]+1,s2[key[1]]+1)\n\t\t\t\t\t\t#print(p)\n\t\t\t#score_tab[key] = log(score_tab[key]/rand_P.prob(len(aln1[0]),len(aln2[0]),key[0]+1,key[1]+1))\n\t\t\tp = p/len(aln1)/len(aln2)\n\t\t\t#print(p)\n\t\t\tscore_tab[key] = log(score_tab[key]/p)\n\t\t\t#print(score_tab[key])\n\t\t#print(score_tab)\n\t\t\t'''\n\t\t\tif score_tab[key]:\n\t\t\t\tscore_tab[key] = log(score_tab[key]/rand_P.prob(len(aln1[0]),len(aln2[0]),key[0]+1,key[1]+1))\n\t\t#del_score = log(gap_rate2/rand_P.del_rate(len(aln1[0]),len(aln2[0]),1))\n\t\t#ins_score = log(gap_rate1/rand_P.ins_rate(len(aln1[0]),len(aln2[0]),1))\n\t\treturn score_tab #,del_score,ins_score\n\t\n\t\n\tdef merge(self,aln1,aln2,score_tab,default=0):\n\t\tn = len(aln1[0])\n\t\tm = len(aln2[0])\n\n\t\taln_score = [[0 for i in range(m+1)] for j in range(n+1)]\n\t\tbacktrack = [['-' for i in range(m+1)] for j in range(n+1)]\n\t\tfor i in range(1,m+1):\n\t\t\tbacktrack[0][i] = 'L'\n\t\t\taln_score[0][i] = aln_score[0][i-1] + score_tab[(-1,i-1)]#+ ins_score\n\t\tfor j in range(1,n+1):\n\t\t\tbacktrack[j][0] = 'U'\n\t\t\taln_score[j][0] = aln_score[j-1][0] + score_tab[(j-1,-1)]#+ del_score\n\n\t\tfor j in range(1,n+1):\n\t\t\tfor i in range(1,m+1):\n\t\t\t\tms = aln_score[j-1][i-1] + score_tab[(j-1,i-1)] \n\t\t\t\tg1 = aln_score[j][i-1] + score_tab[(-1,i-1)] #+ ins_score\n\t\t\t\tg2 = aln_score[j-1][i] + score_tab[(j-1,-1)] #+ del_score\n\n\t\t\t\tif ms >= g1 and ms >= g2:\n\t\t\t\t\taln_score[j][i] = ms\n\t\t\t\t\tbacktrack[j][i] = 'D'\n\t\t\t\telif g1 >= ms and g1 >= g2:\n\t\t\t\t\taln_score[j][i] = g1\n\t\t\t\t\tbacktrack[j][i] = 'L'\n\t\t\t\telse:\n\t\t\t\t\taln_score[j][i] = g2\n\t\t\t\t\tbacktrack[j][i] = 'U'\n\n\t\ti = m\n\t\tj = n\n\t\tM1 = \"\"\n\t\tM2 = \"\"\n\t\twhile (i > 0 or j > 0):\n\t\t\tif backtrack[j][i] == 'D':\n\t\t\t\tM1 = \".\" + M1\n\t\t\t\tM2 = \".\" + M2\n\t\t\t\ti -= 1\n\t\t\t\tj -= 1\t\n\t\t\telif backtrack[j][i] == 'L':\n\t\t\t\tM2 = \".\" + M2\n\t\t\t\tM1 = \"-\" + M1\n\t\t\t\ti -= 1\n\t\t\telse:\n\t\t\t\tM2 = \"-\" + M2\n\t\t\t\tM1 = \".\" + M1\n\t\t\t\tj -= 1\n\t\treturn aln_score[n][m], M1, M2\t\t\n\n\tdef heuristic_merge(self,aln1,taxa1,aln2,taxa2):\n\t\tscore_tab,R1,R2 = self.heuristic_score(aln1,taxa1,aln2,taxa2)\n\t\treturn self.merge(aln1,aln2,score_tab)\n\n\tdef ML_merge(self,aln1,taxa1,aln2,taxa2):\n\t\tscore_tab = self.llh_score(aln1,taxa1,aln2,taxa2)\n\t\treturn self.merge(aln1,aln2,score_tab)\n\n\tdef logodd_merge(self,aln1,taxa1,aln2,taxa2,rand_P):\n\t\tscore_tab= self.logodd_score(aln1,taxa1,aln2,taxa2,rand_P)\n\t\treturn self.merge(aln1,aln2,score_tab)\n","repo_name":"uym2/PASTA_with_structure","sub_path":"merger.py","file_name":"merger.py","file_ext":"py","file_size_in_byte":7625,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"34071252762","text":"from unidecode import unidecode\n\n\nclass DataPreProcessor:\n def __init__(self, data):\n self.data = data\n self.books_keyword_map = {}\n\n def parse_data(self):\n \"\"\"\n modifying the data in place after escaping and decoding\n :return:\n \"\"\"\n titles = self.data.get(\"titles\", [])\n\n for idx in range(len(titles)):\n summary = self.data.get(\"summaries\", [])[idx]\n title = self.data.get(\"titles\", [])[idx]\n summary[\"summary\"] = unidecode(summary.get(\"summary\").decode('unicode-escape'))\n self.data.get(\"titles\", [])[idx] = unidecode(title.decode('unicode-escape'))\n\n def process_data(self):\n summaries = self.data.get(\"summaries\", [])\n titles = self.data.get(\"titles\", [])\n\n # creating a dictionary of words of summaries as key and value as list of books containing this word/key\n for summary in summaries:\n book_id = summary.get(\"id\")\n book_title = titles[book_id]\n\n # combining book_title with the summary so that book name can also be included in search\n book_summary = \"{} {}\".format(book_title, summary.get(\"summary\"))\n keys = book_summary.replace(\"The Book in Three Sentences: \", \"\").replace(\".\", \"\").lower().split()\n\n for key in keys:\n self.books_keyword_map.setdefault(key, {})\n self.books_keyword_map[key].setdefault(book_id, 0)\n self.books_keyword_map[key][book_id] += 1\n\n for key, value in self.books_keyword_map.items():\n self.books_keyword_map[key] = sorted(value.items(), key=lambda item: item[1])\n\n def start(self):\n self.parse_data()\n self.process_data()\n return self.books_keyword_map\n","repo_name":"vvknain/search_project","sub_path":"search_server/search_utility/pre_process_data.py","file_name":"pre_process_data.py","file_ext":"py","file_size_in_byte":1779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"25240130712","text":"def find(x):\n if P[x] != x:\n P[x] = find(P[x])\n return P[x]\n\ndef union(a, b):\n a = find(a)\n b = find(b)\n if a < b:\n P[b] = a\n else:\n P[a] = b\n\nwhile True:\n M, N = map(int, input().split())\n if (M, N) == (0, 0):\n break\n\n E = []\n for _ in range(N):\n a, b, c = map(int, input().split())\n E.append((c, a, b))\n P = [i for i in range(M)]\n\n result = 0\n E.sort()\n for i in E:\n c, a, b = i\n if find(a) != find(b):\n union(a, b)\n else:\n result += c\n\n print (result)","repo_name":"juntae6942/ANA-Daily-Algorithm","sub_path":"손봉우/6497.py","file_name":"6497.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"31"}
+{"seq_id":"1306732733","text":"from django.urls import path\n\nfrom adminapp.views import index, UserListView, UserCreateView, UserUpdateView, UserDeleteView, UserRestoreView,ProductCategoryListView\n\napp_name = 'adminapp'\n\nurlpatterns = [\n path('', index, name='index'),\n path('admin-users-read/', UserListView.as_view(), name='admin_users_read'),\n path('admin-users-create/', UserCreateView.as_view(), name='admin_users_create'),\n path('admin-users-update//', UserUpdateView.as_view(), name='admin_users_update'),\n path('admin-user-remove//', UserDeleteView.as_view(), name='admin_user_remove'),\n path('admin-user-restore//', UserRestoreView.as_view(), name='admin_user_restore'),\n path('admin-product-category-read/', ProductCategoryListView.as_view(), name='admin_product_category_read'),\n\n]\n","repo_name":"DimonYarkin/repogeek-server","sub_path":"adminapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"3415969801","text":"\"\"\"Evaluation of CNN\"\"\"\n# Standar modules\nimport argparse\n\n# Third party modules\nimport matplotlib.pyplot as plt\nimport torch\nfrom plot_metric.functions import BinaryClassification\nfrom torchvision import datasets, transforms\n\n# Local modules\nfrom utils.constants import SIZE, MEAN, STD\n\n\n# Define argument parser\nparser = argparse.ArgumentParser()\nparser.add_argument(\n \"--model\",\n type=str,\n default=\"model_best.pth.tar\",\n help=\"path to input PyTorch model (default: model_best.pth.tar)\",\n)\nparser.add_argument(\"--test\", type=str, default=\"\", help=\"desired path of images\")\nparser.add_argument(\"--type\", type=str, default=\"\", help=\"age, gender, or employee\")\nopt = parser.parse_args()\n\n# Set the device\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n# Type of dataset\ndataset_type = opt.type\nif dataset_type == \"gender\":\n LABELS_MAP = ['f','m']\nelif dataset_type == \"employee\":\n LABELS_MAP = ['client','employee']\nelse:\n LABELS_MAP = ['0-15','16-24','25-34','35-44','45-54','55-65','65-100']\n\n# Load model\nmodel = torch.load(opt.model)\nmodel.to(device)\nmodel.eval()\n\n# Define image transformations\ntfms = transforms.Compose(\n [\n transforms.Resize(SIZE),\n transforms.ToTensor(),\n transforms.Normalize(MEAN, STD),\n ]\n)\n\n# Create Dataset and Dataloader from folder\ndataset = datasets.ImageFolder(opt.test, transform=tfms)\ndataloader = torch.utils.data.DataLoader(dataset, batch_size=50, shuffle=True)\n\n# Performs forward pass for classification\nfor batch, labels in iter(dataloader):\n batch, labels = batch.to(device), labels.to(device)\n with torch.no_grad():\n outputs = model(batch)\n outputs = torch.softmax(outputs, dim=1).argmax(dim=1)\n\n\n# Visualisation with plot_metric [https://github.com/yohann84L/plot_metric]\nbc = BinaryClassification(\n labels.cpu().data.numpy(), outputs.cpu().data.numpy(), labels=LABELS_MAP\n)\n\n# Figures\nplt.figure(figsize=(15, 10))\nplt.subplot2grid(shape=(2, 6), loc=(0, 0), colspan=2)\nbc.plot_roc_curve()\nplt.subplot2grid((2, 6), (0, 2), colspan=2)\nbc.plot_precision_recall_curve()\nplt.subplot2grid((2, 6), (0, 4), colspan=2)\nbc.plot_class_distribution()\nplt.subplot2grid((2, 6), (1, 1), colspan=2)\nbc.plot_confusion_matrix()\nplt.subplot2grid((2, 6), (1, 3), colspan=2)\nbc.plot_confusion_matrix(normalize=True)\nplt.show()\nbc.print_report()","repo_name":"jorgechang/VICO_classifier","sub_path":"evaluation.py","file_name":"evaluation.py","file_ext":"py","file_size_in_byte":2364,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"38789259899","text":"#!/usr/bin/env python\n\nfrom file.FileWriter import FileWriter\nfrom bs4 import BeautifulSoup\nfrom argparse import ArgumentParser\nfrom urllib.request import urlretrieve, urlopen\nfrom urllib.parse import unquote\nimport os\n\nparser = ArgumentParser(description='Extract link urls of a website.')\nparser.add_argument('url', help='url of website to parse')\nparser.add_argument('--distinct', action='store_true', help='result list should not contain duplicate link urls, '\n 'do not preserve order')\nparser.add_argument('--filter-should-contain', help='only parse urls containing given string')\nparser.add_argument('--download', action='store_true', help='save all found urls to files')\nparser.add_argument('--save', action='store_true', help='write found files into a .txt file')\nargs = parser.parse_args()\n\nurl = args.url\ndistinct = args.distinct\ndownload_files = args.download\nsave_to_file = args.save\ndirectory = \"result\"\n\ntry:\n response = urlopen(url)\nexcept:\n print(\"Could not access URL \" + url)\n exit(1)\n\npage = str(BeautifulSoup(response.read().decode(\"utf8\"), \"html.parser\"))\nresponse.close()\n\n\ndef getURL(page):\n \"\"\"Extract next url from page.\n :param page: html of web page \n :return: urls in that page \n \"\"\"\n start_link = page.find(\"a href\")\n if start_link == -1:\n return None, 0\n start_quote = page.find('\"', start_link)\n end_quote = page.find('\"', start_quote + 1)\n url = page[start_quote + 1: end_quote]\n return url, end_quote\n\n\ndef filter_url(url):\n \"\"\"Returns True if all configured filters are passed and False if not.\"\"\"\n if args.filter_should_contain is not None and args.filter_should_contain not in url:\n return False\n return True\n\n\ndef download_file(url):\n \"\"\"Download a file from given url an use last url segment as filename to directory 'download/'.\"\"\"\n if not os.path.exists(directory):\n os.makedirs(directory)\n image_name = directory + \"/\" + unquote(url.rsplit('/', 1)[-1])\n urlretrieve(url, image_name)\n print(\" -> Save file \" + image_name)\n\n\n\nurls = list()\nwhile True:\n url, n = getURL(page)\n page = page[n:]\n if not url:\n break\n if filter_url(url):\n urls.append(url)\n\nprint(str(len(urls)) + \" URLs found!\")\n\nif distinct:\n urls = set(urls)\n\nfor url in urls:\n print(url)\n if download_files:\n download_file(url)\n\nif save_to_file:\n file_path = FileWriter(\"result\", \"urls.txt\").write_list(urls)\n print(\" -> URLs written to file \" + file_path)\n","repo_name":"sikell/python-scripts","sub_path":"extractUrls.py","file_name":"extractUrls.py","file_ext":"py","file_size_in_byte":2552,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"73341810007","text":"\"\"\"Add is_private column to contribution types table\n\nRevision ID: 566d5de4e0e5\nRevises: 1d512a9ebb30\nCreate Date: 2017-11-01 11:49:47.532339\n\"\"\"\n\nimport sqlalchemy as sa\nfrom alembic import op\n\n\n# revision identifiers, used by Alembic.\nrevision = '566d5de4e0e5'\ndown_revision = '1d512a9ebb30'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n op.add_column(\n 'contribution_types',\n sa.Column('is_private', sa.Boolean(), nullable=False, server_default='false'),\n schema='events'\n )\n op.alter_column('contribution_types', 'is_private', server_default=None, schema='events')\n\n\ndef downgrade():\n op.drop_column('contribution_types', 'is_private', schema='events')\n","repo_name":"indico/indico","sub_path":"indico/migrations/versions/20171101_1149_566d5de4e0e5_add_is_private_column_to_contribution_types.py","file_name":"20171101_1149_566d5de4e0e5_add_is_private_column_to_contribution_types.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","stars":1560,"dataset":"github-code","pt":"31"}
+{"seq_id":"5702572018","text":"from django.contrib import admin\nfrom solo.admin import SingletonModelAdmin\n\nfrom .models import *\n\n\nclass OrderAdmin(admin.ModelAdmin):\n fields = (\n \"number\",\n \"name\",\n \"surname\",\n \"email\",\n \"phone_number\",\n \"products\",\n \"total_price\",\n \"delivery_type\",\n \"commit\",\n \"city\",\n \"address\",\n \"sum_delivery\",\n )\n list_filter = ((\"commit\", admin.EmptyFieldListFilter),)\n list_display = [\n \"number\",\n \"name\",\n \"surname\",\n \"delivery_type\",\n \"total_price\",\n ]\n list_display_links = (\n \"number\",\n \"name\",\n \"surname\",\n \"delivery_type\",\n \"total_price\",\n )\n\n def has_add_permission(self, request, obj=None):\n return False\n\n def has_delete_permission(self, request, obj=None):\n return False\n\n def changelist_view(self, request, extra_context=None):\n extra_context = {\"title\": f\"Выберите заказ для просмотра.\"}\n return super(OrderAdmin, self).changelist_view(request, extra_context=extra_context)\n\n\nadmin.site.register(Slider)\nadmin.site.register(About, SingletonModelAdmin)\nadmin.site.register(PrivacyPolicy, SingletonModelAdmin)\nadmin.site.register(Thanks, SingletonModelAdmin)\nadmin.site.register(Order, OrderAdmin)\nadmin.site.site_header = \"Админ-панель сайта Там-Там\"\n","repo_name":"retxrika/Ceramic-Project","sub_path":"main/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"113279267","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.get_routes, name=\"routes\"),\n\n path('notes/', views.GetNotes.as_view(), name=\"notes\"),\n path('note/create', views.CreateNote.as_view(), name=\"create-note\"),\n path('note//update/', views.UpdateNote.as_view(), name=\"update-note\"),\n path('note//delete/', views.DeleteNote.as_view(), name=\"delete-note\"),\n path('note//', views.GetNote.as_view(), name=\"note\"),\n]\n","repo_name":"MilliesXu/django_full_stack","sub_path":"api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"1874798775","text":"from odoo import models,fields,api\n\nclass SaleSplit(models.TransientModel):\n\t_name='sale.split.wizard'\n\n\n\tname = fields.Char(string='Name')\n\tproduct_ids = fields.One2many(string='Product',comodel_name='sale.order.line.wizard',inverse_name='quotation_id')\n\t\n\t\n\t@api.model\n\tdef default_get(self, fields_list):\n\t\tres = super(SaleSplit,self).default_get(fields_list)\n\t\tvals = self.env['sale.order'].browse(self.env.context.get('order_id'))\n\t\tlines = []\n\t\tfor val in vals.picking_ids.move_ids_without_package: \n\t\t\tprint(\"_________________________________________vvv\",val.product_id.name)\n\t\t\tprint(\"_________________________________________vvvidddddd\",val.id)\n\t\t\tline=(0,0,{\n\t\t\t\t\t'product_id':val.product_id,\n\t\t\t\t\t'hidden_move_id':val\n\n\t\t\t\t\t})\n\t\t\tprint(\"________line\",line)\n\t\t\t\n\t\t\tprint('picking_id----------------------',val.picking_id)\n\t\t\tlines.append(line)\n\t\tres.update({\n\t\t\t'product_ids':lines\n\t\t\t})\n\n\n\n\t\treturn res\n\t\n\tdef split_quotation(self):\n\t\tsale_id = self.env['sale.order'].browse(self.env.context.get('order_id'))\n\t\ttransfer = sale_id.env['stock.picking'].create({\n\t\t\t'picking_type_id': 2,\n\t\t\t'location_id': 8,\n\t\t\t'location_dest_id' :10,\n\t\t\t'note' : \"note\",\n\t\t\t'origin':sale_id.name\n\t\t\t})\n\t\t\n\t\tprint('sale_id---------------',sale_id)\n\t\t\t\n\t\tfor wiz_line in self.product_ids:\n\t\t\tif wiz_line.split_quotation == True:\n\t\t\t\twiz_line.hidden_move_id.write({\n\t\t\t\t\t'picking_id':transfer.id\n\t\t\t\t\t})\n\nclass SaleSplitLine(models.TransientModel):\n\t_name='sale.order.line.wizard'\n\n\tquotation_id = fields.Many2one(string='Quotation',comodel_name='sale.split.wizard')\n\tproduct_id = fields.Many2one(string='Product',comodel_name='product.product')\n\tsplit_quotation = fields.Boolean(string='Order Split?')\n\thidden_move_id =fields.Many2one(string='hidden move ID', comodel_name='stock.move')\n\n","repo_name":"Jayrajthakkar/library","sub_path":"library_management/wizard/sale_split_wizard.py","file_name":"sale_split_wizard.py","file_ext":"py","file_size_in_byte":1779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"5535891552","text":"#!/usr/bin/env python3\n\n# This file is part of ODM and distributed under the terms of the\n# MIT license. See COPYING.\n\nimport json\nimport sys\n\nimport odm.cli\nimport odm.ms365\n\n\ndef main():\n cli = odm.cli.CLI(['site', 'action', '--incremental'])\n client = cli.client\n\n site = odm.ms365.Site(client, cli.args.site)\n\n if cli.args.action == 'show':\n result = site.show()\n if result:\n print(json.dumps(result, indent=2))\n else:\n print('Site {} not found'.format(cli.args.site), file=sys.stderr)\n sys.exit(1)\n\n elif cli.args.action == 'list-items':\n base = {\n 'items': {},\n }\n\n if cli.args.incremental:\n with open(cli.args.incremental, 'rb') as f:\n base = json.load(f)\n\n site.drive.delta(base)\n\n print(json.dumps(base, indent=2))\n\n elif cli.args.action == 'list-pages':\n print(json.dumps(client.get_list('https://graph.microsoft.com/beta/sites/{}/pages'.format(site._id)), indent=2))\n\n elif cli.args.action == 'list-lists':\n print(json.dumps(site.lists, indent=2))\n\n for l in site.lists:\n print(json.dumps(client.get_list('sites/{}/lists/{}/items'.format(site._id, l['id'])), indent=2))\n\n else:\n print('Unsupported action {}'.format(cli.args.action), file=sys.stderr)\n sys.exit(1)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"UMCollab/ODM","sub_path":"odm/libexec/odm_site.py","file_name":"odm_site.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"13864909050","text":"from dndraces import Race\nimport random\n\n\nclass Elf(Race):\n NAME = \"elf\"\n LAWFULNESS = (-3, 2) # mu, sigma\n GOODNESS = (2, 2) # mu, sigma\n\n HAIR = {\"black\": 20,\n \"brown\": 35,\n \"blond\": 15,\n \"ginger\": 8,\n \"green\": 1,\n \"blue\": 1,\n \"white\": 1,\n \"red\": 1,\n }\n\n EYES = {\"blue\": 20,\n \"brown\": 40,\n \"green\": 10,\n \"black\": 10,\n \"red\": 1,\n \"violet\": 1,\n }\n\n MALE_NAME = [\"Aramil\",\n \"Aust\",\n \"Enialis\",\n \"Heian\",\n \"Himo\",\n \"Ivellios\",\n \"Lau-cian\",\n \"Quarion\",\n \"Soverliss\",\n \"Thamior\",\n \"Tharivol\"]\n\n FEMALE_NAME = [\"Anastrianna\",\n \"Antinua\",\n \"Drusilia\",\n \"Felosial\",\n \"Ielenia\",\n \"Lia\",\n \"Mialee\",\n \"Qillathe\",\n \"Silaqui\",\n \"Vadania\",\n \"Valanthe\",\n \"Xanaphia\"]\n\n FAMILY_NAME = [\"Amastacia (Starflower)\",\n \"Amakiir (Gemflower)\",\n \"Galanodel (Moonwhisper)\",\n \"Holimion (Diamonddew)\",\n \"Liadon (Silverfrond)\",\n \"Meliamne (Oakenheel)\",\n \"Naïlo (Nightbreeze)\",\n \"Siannodel (Moonbrook)\",\n \"Ilphukiir (Gemblossom)\",\n \"Xiloscient (Goldpetal)\"]\n\n # Gender Base Height Height Modifier Base Weight Weight Modifier\n # Male 4' 5\" +2d6 85 lb. x (1d6) lb.\n # Female 4' 5\" +2d6 80 lb. x (1d6) lb.\n\n H_MOD = \"2d6\"\n H_UNIT = \"inch\"\n\n W_MOD = \"1d6\"\n W_UNIT = \"lbs\"\n\n class Male(Race.Male):\n H_BASE = \"4'5\\\"\"\n W_BASE = \"85lbs\"\n\n class Female(Race.Female):\n H_BASE = \"4'5\\\"\"\n W_BASE = \"80lbs\"\n\n def make_name(self):\n if self.gender.NAME == \"male\":\n first_name = random.choice(self.MALE_NAME)\n else:\n first_name = random.choice(self.FEMALE_NAME)\n family_name = random.choice(self.FAMILY_NAME)\n self.name = first_name + \" \" + family_name\n","repo_name":"chielk/dndmake","sub_path":"dndraces/elf.py","file_name":"elf.py","file_ext":"py","file_size_in_byte":2365,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"}
+{"seq_id":"11132049196","text":"import sys\nfrom osbrain import run_agent\nfrom osbrain import run_nameserver\nfrom organizerAgent import OrganizerAgent \n\n\nif __name__ == '__main__':\n if (len(sys.argv) != 3):\n print(\"You must enter only the number of couples and number of interests! (e.g.: python speedDating.py 4 4\")\n exit()\n\n ns_sock = run_nameserver()\n \n organizerAgent = run_agent('OrganizerAgent', base=OrganizerAgent)\n organizerAgent.numberOfCouples = int(sys.argv[1])\n organizerAgent.numberOfInterests = int(sys.argv[2])\n organizerAgent.initializeAgents()\n \n while organizerAgent.is_running():\n try: \n organizerAgent.startDating()\n except KeyboardInterrupt:\n ns_sock.shutdown_agents()\n ns_sock.shutdown()\n \n ns_sock.shutdown_agents()\n ns_sock.shutdown()\n","repo_name":"muratcanakcay/Agent-Systems-and-Software-Applications","sub_path":"OSBRAIN Homework/speedDating.py","file_name":"speedDating.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"21275891155","text":"import torch\n\nimport logging\n\n\nclass Tester(object):\n def __init__(self,\n model,\n test_dataloader=None,\n use_gpu=True\n ) -> None:\n self.model = model\n self.test_dataloader = test_dataloader\n self.use_gpu = use_gpu\n if self.use_gpu:\n self.device = torch.device(\n 'cuda' if torch.cuda.is_available() and use_gpu else 'cpu')\n self.model = self.model.cuda()\n\n def run(self):\n correct = 0\n total = 0\n for images, labels in self.test_dataloader:\n if self.use_gpu:\n images = images.to(self.device)\n labels = labels.to(self.device)\n outputs = self.model(images)\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += (predicted == labels).sum().item()\n logging.info('Accuracy of the network on the 10000 test images: {:.5f} '.format(\n correct / total))\n","repo_name":"p2pc/optimchan","sub_path":"pytorchan/testers/tester.py","file_name":"tester.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"}
+{"seq_id":"33990956256","text":"from cgi import print_directory\nimport string\nimport math\n\n# le format de s est [f(x0), f(x0+h), f(x0+2h), ...]\n# h = 0.1 par defaut\ndef deriver(s):\n if (s==None):\n return None\n l = len(s)\n # parcour la liste s pour verifier le type des elements\n if l < 2 :\n return None\n else :\n for item in s:\n if( type(item) != float):\n print(item)\n return False\n # calcule la derivee de s\n res = []\n if l == 2:\n res.append(round((s[1]-s[0])/0.1, 2))\n return res\n else :\n for i in range(l-1) :\n print(\"s[\",i,\"] est : \", s[i])\n print(\"s[\",i+1,\"] est : \", s[i+1])\n res.append(round((s[i+1]-s[i])/0.1, 2))\n return res\n\n\n \n\n","repo_name":"milornight/TDD2_test_logiciel","sub_path":"func2.py","file_name":"func2.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"40151214967","text":"# 產生一個隨機整數1~100\n# 讓使用者重複輸入數字去猜\n# 猜對的話 印出“猜對了”\n# 猜錯的話 要告訴他比答案大或小\n\nimport random\n\nr = random.randint(1, 100)\ncount = 0\n\nwhile True:\n\tnumber = input('please enter a number from 0~100: ')\n\tnumber = int(number)\n\tcount += 1 # count = count + 1\n\n\tif number == r: \n\t\tprint('It is correct!')\n\t\tprint('this is the', count, 'times')\n\t\tbreak\n\telif number > r:\n\t\tprint('your answer is larger than the answer.')\n\telif number < r:\n\t\tprint('your answer is smaller than the answer')\n\n\tprint('this is the', count, 'times')\n\n\n","repo_name":"JackLu1020/r1","sub_path":"r1.py","file_name":"r1.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"21297513377","text":"import pandas as pd\nimport numpy as np\n\n\npasta=\"C:/Users/ravel/Downloads/COVID-19 no Mundo, no Brasil e em Pernambuco (8).csv\"\npath_out_SUQC_mod = \"C:/Users/ravel/OneDrive/Área de Trabalho/DataScientist/sklearn/COVID-19/CasosPorEstado/suqcmod_covid19/data/data_mensured_PE/\"\n\ndf = pd.read_csv(pasta,header = 0, sep = \",\")\n\ndf_filtred_confirmed = df.query('classe == \"CONFIRMADO\"')\ndf_municipios=pd.pivot_table(df_filtred_confirmed, values = 'X', \n columns = ['mun_notificacao'],\n aggfunc=np.mean)\n\nfile_mun = \"C:/Users/ravel/OneDrive/Área de Trabalho/DataScientist/sklearn/COVID-19/CasosPorEstado/suqcmod_covid19/data/municipios_PE.csv\"\ndf_municipios.to_csv(file_mun,sep = \";\", index = False)\nmunicipios = df_municipios.columns\n\nfor mun in municipios:\n \n df_municipio = df_filtred_confirmed.query('mun_notificacao == '+'\"'+mun+'\"')\n df_municipio[\"Cases\"] = np.zeros(len(df_municipio))+1\n\n df_organizado = pd.pivot_table(df_municipio, values = 'Cases', \n index = ['dt_notificacao'],\n aggfunc=np.sum)\n\n df_organizado[\"DateRep\"] = pd.to_datetime(df_organizado.index)\n df_corrigido = pd.date_range(start = df_organizado[\"DateRep\"].values[0],\n end = df_organizado[\"DateRep\"].values[-1],\n freq='D')\n cases = np.zeros(len(df_corrigido))\n\n for i in range(len(df_organizado)):\n for j in range(len(df_corrigido)):\n if df_corrigido.values[j] == df_organizado[\"DateRep\"].values[i]:\n cases[j] = df_organizado[\"Cases\"].values[i]\n \n df_organizado_ = pd.DataFrame(df_corrigido.values, columns = [\"DateRep\"])\n df_organizado_[\"Cases\"] = np.array(cases)\n\n df_organizado_[\"cum-Cases\"] = df_organizado_[\"Cases\"].cumsum()\n df_organizado_[\"Deaths\"] = np.zeros(len(df_organizado_))\n\n for i in range(len(df_municipio)):\n for j in range(len(df_organizado_)):\n if df_municipio[\"dt_obito\"].values[i] == str(df_corrigido.values[j])[:10]:\n df_organizado_[\"Deaths\"][j]=df_organizado_[\"Deaths\"][j]+1\n\n df_organizado_[\"cum-Deaths\"] = df_organizado_[\"Deaths\"].cumsum() \n df_organizado_.to_csv(path_out_SUQC_mod+ \"COVID-19 \"+ mun + \".csv\", sep = \";\",index = False)\n\n\n","repo_name":"ravellys/suqcmod_covid19","sub_path":"script/data_PE.py","file_name":"data_PE.py","file_ext":"py","file_size_in_byte":2322,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"33948723260","text":"from functools import lru_cache\n\n\n@lru_cache(maxsize=None)\ndef Min_and_Max(Arr):\n # // returns an array where the first element is the minimum sum and the\n # second is the maximum sum .\n if len(Arr) == 2:\n power = Arr[0] ^ Arr[1]\n return power, power\n minimum = float('inf')\n maximum = 0\n for i in range(1, len(Arr)):\n val = Arr[0] ^ Arr[i]\n res = Min_and_Max(Arr[1:i] + Arr[i + 1:])\n minimum = min(res[0] + val, minimum)\n maximum = max(res[1] + val, maximum)\n return minimum, maximum\n\n\nn = int(input())\nArr = []\nfor _ in range(n):\n Arr.append(int(input()))\n\nout_ = Min_and_Max(tuple(Arr))\nprint(' '.join(map(str, out_)))\n","repo_name":"HBinhCT/Q-project","sub_path":"hackerearth/Algorithms/Integer distribution/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"}
+{"seq_id":"73341855767","text":"from flask import request\n\nfrom indico.modules.api.controllers import (RHAPIAdminKeys, RHAPIAdminSettings, RHAPIBlockKey, RHAPICreateKey,\n RHAPIDeleteKey, RHAPITogglePersistent, RHAPIUserProfile)\nfrom indico.web.flask.wrappers import IndicoBlueprint\nfrom indico.web.http_api.handlers import handler as api_handler\n\n\n_bp = IndicoBlueprint('api', __name__, template_folder='templates', virtual_template_folder='api')\n\n# HTTP API\n_bp.add_url_rule('/export/', view_func=api_handler, endpoint='httpapi', defaults={'prefix': 'export'})\n_bp.add_url_rule('/api/', view_func=api_handler, endpoint='httpapi', defaults={'prefix': 'api'},\n methods=('POST',))\n_bp.add_url_rule('/', endpoint='httpapi', build_only=True)\n\n# Administration\n_bp.add_url_rule('/admin/api/', 'admin_settings', RHAPIAdminSettings, methods=('GET', 'POST'))\n_bp.add_url_rule('/admin/api/keys', 'admin_keys', RHAPIAdminKeys)\n\n# User profile\nwith _bp.add_prefixed_rules('/user/', '/user'):\n _bp.add_url_rule('/api/', 'user_profile', RHAPIUserProfile)\n _bp.add_url_rule('/api/create', 'key_create', RHAPICreateKey, methods=('POST',))\n _bp.add_url_rule('/api/delete', 'key_delete', RHAPIDeleteKey, methods=('POST',))\n _bp.add_url_rule('/api/persistent', 'key_toggle_persistent', RHAPITogglePersistent, methods=('POST',))\n _bp.add_url_rule('/api/block', 'key_block', RHAPIBlockKey, methods=('POST',))\n\n\n@_bp.url_defaults\ndef _add_user_id(endpoint, values):\n if (endpoint == 'api.user_profile' or endpoint.startswith('api.key_')) and 'user_id' not in values:\n # Inject user id if it's present in the url\n values['user_id'] = request.view_args.get('user_id')\n","repo_name":"indico/indico","sub_path":"indico/modules/api/blueprint.py","file_name":"blueprint.py","file_ext":"py","file_size_in_byte":1764,"program_lang":"python","lang":"en","doc_type":"code","stars":1560,"dataset":"github-code","pt":"31"}
+{"seq_id":"3734560037","text":"def fill(input: str, target_length):\n result = input\n while(len(result) < target_length):\n a = [c for c in result]\n b = a.copy()\n b.reverse()\n for (idx, element) in enumerate(b):\n b[idx] = \"0\" if element == \"1\" else \"1\"\n result = \"\".join(a) + \"0\" + \"\".join(b)\n return result\n\ndef calc_checksum(input: str):\n if len(input) % 2 != 0:\n raise Exception(\"input length not dividable by 2\")\n\n while(len(input) % 2 == 0):\n pairs = []\n for i in range(0, len(input), 2):\n pairs.append(input[i:i+2])\n input = \"\"\n for p in pairs:\n if(p[0] == p[1]):\n input += \"1\"\n else:\n input += \"0\"\n return input\n\ndef fill_and_calc_checksum(input: str, target_length):\n filled = fill(input, target_length)\n if(len(filled) > target_length):\n filled = filled[:target_length]\n checksum = calc_checksum(filled)\n return checksum\n\ndef test():\n assert fill(\"1\", 3) == \"100\"\n assert fill(\"0\", 3) == \"001\"\n assert fill(\"11111\", len(\"11111000000\")) == \"11111000000\"\n assert fill(\"111100001010\", len(\"1111000010100101011110000\")) == \"1111000010100101011110000\"\n\n assert calc_checksum(\"110010110100\") == \"100\"\n\n assert fill_and_calc_checksum(\"10000\", 20) == \"01100\"\n\ndef main():\n # test()\n\n result = fill_and_calc_checksum(\"11110010111001001\", 272)\n print(f'Pt1: {result}')\n result = fill_and_calc_checksum(\"11110010111001001\", 35651584)\n print(f'Pt2: {result}')\n\nif __name__ == '__main__':\n main()\n","repo_name":"joergpichler/AdventOfCode","sub_path":"2016/Day16/Day16.py","file_name":"Day16.py","file_ext":"py","file_size_in_byte":1577,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"773273370","text":"from solcx import compile_standard, install_solc\r\nimport json\r\nfrom web3 import Web3\r\nimport os\r\nfrom dotenv import load_dotenv\r\n\r\nload_dotenv()\r\n\r\nwith open(\"./SimpleStorage.sol\", \"r\") as file:\r\n simple_storage_file = file.read()\r\n\r\ninstall_solc(\"0.6.0\")\r\n# Compile my Solidity\r\n\r\ncompiled_sol = compile_standard(\r\n {\r\n \"language\": \"Solidity\",\r\n \"sources\": {\"SimpleStorage.sol\": {\"content\": simple_storage_file}},\r\n \"settings\": {\r\n \"outputSelection\": {\r\n \"*\": {\r\n \"*\": [\"abi\", \"metadata\", \"evm.bytecode\", \"evm.bytecode.sourceMap\"]\r\n }\r\n }\r\n },\r\n },\r\n solc_version=\"0.6.0\",\r\n)\r\n\r\nwith open(\"comipiled_code.json\", \"w\") as file:\r\n json.dump(compiled_sol, file)\r\n\r\n# get bytecode\r\nbytecode = compiled_sol[\"contracts\"][\"SimpleStorage.sol\"][\"SimpleStorage\"][\"evm\"][\r\n \"bytecode\"\r\n][\"object\"]\r\n\r\n# get abi\r\nabi = compiled_sol[\"contracts\"][\"SimpleStorage.sol\"][\"SimpleStorage\"][\"abi\"]\r\n\r\n# for connecting to rinkeby\r\nw3 = Web3(\r\n Web3.HTTPProvider(\"https://rinkeby.infura.io/v3/c4755a2725794bb58a01c2d892c8f6a0\")\r\n)\r\nchain_id = 4\r\nmy_address = \"0xC1bc0195F9eCBF4E085cb847eEc03e9a266a7ED3\"\r\nprivate_key = os.getenv(\"PRIVATE_KEY\")\r\n\r\n# Creating a contract on python\r\nSimpleStorage = w3.eth.contract(abi=abi, bytecode=bytecode)\r\n# Get the latest transaction count\r\nnonce = w3.eth.getTransactionCount(my_address)\r\n# print(nonce)\r\n# 1.Build transaction\r\n# 2.Sign transaction\r\n# 3.Send transaction\r\n# transaction = SimpleStorage.constructor().buildTransaction(\r\n# {\"chainId\": chain_id, \"from\": my_address, \"nonce\": nonce}\r\n# )\r\n\r\n# build txn\r\ntransaction = SimpleStorage.constructor().buildTransaction(\r\n {\r\n \"chainId\": chain_id,\r\n \"gasPrice\": w3.eth.gas_price,\r\n \"from\": my_address,\r\n \"nonce\": nonce,\r\n }\r\n)\r\n\r\n# sign txn\r\nsigned_txn = w3.eth.account.sign_transaction(transaction, private_key=private_key)\r\n\r\n# send txn\r\nprint(\"Deploying contract...\")\r\ntx_hash = w3.eth.send_raw_transaction(signed_txn.rawTransaction)\r\ntx_reciept = w3.eth.wait_for_transaction_receipt(tx_hash)\r\nprint(\"Deployed!\")\r\n# Working with a contract you always need:\r\n# 1. Contract address\r\n# 2. Contract ABI\r\nsimple_storage = w3.eth.contract(address=tx_reciept.contractAddress, abi=abi)\r\n# Call -> Simulate making a call and getting return value\r\n# Transact -> Actually make state change\r\n\r\n# Initial value of favorite number\r\nprint(\"Initial value of favorite number:\")\r\nprint(simple_storage.functions.retrieve().call())\r\nprint(\"Creating transaction to store new favorite number\")\r\nstore_transaction = simple_storage.functions.store(15).buildTransaction(\r\n {\r\n \"chainId\": chain_id,\r\n \"gasPrice\": w3.eth.gas_price,\r\n \"from\": my_address,\r\n \"nonce\": nonce + 1,\r\n }\r\n)\r\nsigned_store_txn = w3.eth.account.sign_transaction(\r\n store_transaction, private_key=private_key\r\n)\r\nprint(\"Sending signed transaction\")\r\ntransaction_hash = w3.eth.send_raw_transaction(signed_store_txn.rawTransaction)\r\ntx_reciept = w3.eth.wait_for_transaction_receipt(transaction_hash)\r\nprint(\"New favorite number: \", simple_storage.functions.retrieve().call())\r\n","repo_name":"trekol1/EVM_SmartContracts","sub_path":"w3_py_simple_storage/w3_py_simple_storage/deploy.py","file_name":"deploy.py","file_ext":"py","file_size_in_byte":3183,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"41713384222","text":"import sys\nsys.stdin = open('input.txt', 'r')\n\n\nN = int(input())\nA = list(map(int, input().split()))\nA.sort()\n\nM = int(input())\nnumbers = list(map(int, input().split()))\nanswers = ['0'] * M\n\n\ndef binary_search(num, left, right):\n if left == right:\n return False\n mid = (left + right) // 2\n if A[mid] == num:\n return True\n elif A[mid] < num:\n return binary_search(num, mid+1, right)\n else:\n return binary_search(num, left, mid)\n\n\nfor i in range(M):\n if binary_search(numbers[i], 0, N):\n answers[i] = '1'\n\nprint('\\n'.join(answers))\n","repo_name":"heecheol1508/algorithm-problem","sub_path":"_baekjoon/1920_수 찾기.py","file_name":"1920_수 찾기.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"6903971842","text":"import pygame as pg\r\nimport sys\r\npg.init()\r\nchetan=pg.display.set_mode((400,400))\r\nchetan.fill(\"white\")\r\nFONT = pg.font.Font(pg.font.get_default_font(), 20)\r\npreviousWidth = 0\r\ndef getSurfaces(word, pos):\r\n global previousWidth\r\n \r\n surfaces = []\r\n positions = []\r\n for i in range(len(word)):\r\n surf = FONT.render(f\"{word[i]}\", True, \"black\")\r\n surfaces.append(surf)\r\n for i in range(len(surfaces)):\r\n previousWidth += surfaces[i-1].get_rect().width\r\n positions.append([previousWidth + pos[0], pos[1]])\r\n return surfaces, positions\r\nwhile True:\r\n pg.display.update()\r\n \r\n getSurfaces(\"chetan\",200 )\r\n for event in pg.event.get():\r\n if event.type==pg.QUIT:\r\n pg.quit()\r\n sys.exit()\r\n\r\n ","repo_name":"chetanrchetu/my-project","sub_path":"HANGMAN/htextsam.py","file_name":"htextsam.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"31698672761","text":"import math\nfrom PySide6.QtCore import Qt, QPointF, QRectF, QLineF\nfrom PySide6.QtWidgets import (\n QGraphicsItem,\n QGraphicsTextItem,\n QGraphicsSimpleTextItem,\n QGraphicsPathItem,\n QGraphicsEllipseItem,\n QGraphicsColorizeEffect,\n QGraphicsDropShadowEffect,\n QApplication,\n QToolTip,\n QStyle,\n)\nfrom PySide6.QtGui import (\n QColor,\n QPen,\n QBrush,\n QTextCursor,\n QPalette,\n QTextBlockFormat,\n QFont,\n QPainterPath,\n QRadialGradient,\n)\nfrom PySide6.QtSvg import QSvgRenderer\nfrom PySide6.QtSvgWidgets import QGraphicsSvgItem\nfrom spine_engine.spine_engine import ItemExecutionFinishState\nfrom .project_commands import MoveIconCommand\nfrom .helpers import LinkType, fix_lightness_color\n\n\nclass ProjectItemIcon(QGraphicsPathItem):\n \"\"\"Base class for project item icons drawn in Design View.\"\"\"\n\n ITEM_EXTENT = 64\n FONT_SIZE_PIXELS = 12 # pixel size to prevent font scaling by system\n\n def __init__(self, toolbox, icon_file, icon_color):\n \"\"\"\n Args:\n toolbox (ToolboxUI): QMainWindow instance\n icon_file (str): Path to icon resource\n icon_color (QColor): Icon's color\n \"\"\"\n super().__init__()\n self._toolbox = toolbox\n self._scene = None\n self._bumping = True\n self.bumped_rects = {} # Item rect before it was bumped\n self.icon_file = icon_file\n self._icon_color = icon_color\n self._moved_on_scene = False\n self.previous_pos = QPointF()\n self.icon_group = {self}\n self.renderer = QSvgRenderer()\n self.svg_item = QGraphicsSvgItem(self)\n self.svg_item.setZValue(100)\n self.colorizer = QGraphicsColorizeEffect()\n self._rect = QRectF(-self.ITEM_EXTENT / 2, -self.ITEM_EXTENT / 2, self.ITEM_EXTENT, self.ITEM_EXTENT)\n self.component_rect = QRectF(0, 0, self.ITEM_EXTENT / 4, self.ITEM_EXTENT / 4)\n self._selection_halo = QGraphicsPathItem(self)\n # Make exclamation, rank, and execution icons\n self.exclamation_icon = ExclamationIcon(self)\n self.execution_icon = ExecutionIcon(self)\n self.rank_icon = RankIcon(self)\n # Make item name graphics item.\n self._name = \"\"\n self.name_item = QGraphicsSimpleTextItem(self._name)\n self.name_item.setZValue(100)\n self.set_name_attributes() # Set font, size, position, etc.\n # Make connector buttons\n self.connectors = dict(\n bottom=ConnectorButton(toolbox, self, position=\"bottom\"),\n left=ConnectorButton(toolbox, self, position=\"left\"),\n right=ConnectorButton(toolbox, self, position=\"right\"),\n )\n self._setup()\n shadow_effect = QGraphicsDropShadowEffect()\n shadow_effect.setOffset(1)\n shadow_effect.setEnabled(False)\n self.setGraphicsEffect(shadow_effect)\n self._update_path()\n\n def rect(self):\n return self._rect\n\n def _update_path(self):\n rounded = self._toolbox.qsettings().value(\"appSettings/roundedItems\", defaultValue=\"false\") == \"true\"\n self._do_update_path(rounded)\n\n def update_path(self, rounded):\n self._do_update_path(rounded)\n\n def _do_update_path(self, rounded):\n radius = self.component_rect.width() / 2 if rounded else 0\n path = QPainterPath()\n path.addRoundedRect(self._rect, radius, radius)\n self.setPath(path)\n self.rank_icon.update_path(radius)\n for conn in self.connectors.values():\n conn.update_path(radius)\n # Selection halo\n pen_width = 1\n margin = 1\n path = QPainterPath()\n path.addRoundedRect(self._rect.adjusted(-margin, -margin, margin, margin), radius + margin, radius + margin)\n self._selection_halo.setPath(path)\n selection_pen = QPen(Qt.DashLine)\n selection_pen.setWidthF(pen_width)\n self._selection_halo.setPen(selection_pen)\n\n def finalize(self, name, x, y):\n \"\"\"\n Names the icon and moves it by given amount.\n\n Args:\n name (str): icon's name\n x (int): horizontal offset\n y (int): vertical offset\n \"\"\"\n self.moveBy(x, y)\n self.update_name_item(name)\n\n def _setup(self):\n \"\"\"Setup item's attributes.\"\"\"\n self.colorizer.setColor(self._icon_color)\n background_color = fix_lightness_color(self._icon_color)\n gradient = QRadialGradient(self._rect.center(), 1 * self._rect.width())\n gradient.setColorAt(0, background_color.lighter(105))\n gradient.setColorAt(1, background_color.darker(105))\n brush = QBrush(gradient)\n pen = QPen(QBrush(background_color.darker()), 1, Qt.SolidLine)\n self.setPen(pen)\n for conn in self.connectors.values():\n conn.setPen(pen)\n self.rank_icon.bg.setPen(pen)\n self.setBrush(brush)\n # Load SVG\n loading_ok = self.renderer.load(self.icon_file)\n if not loading_ok:\n self._toolbox.msg_error.emit(\"Loading SVG icon from resource:{0} failed\".format(self.icon_file))\n return\n size = self.renderer.defaultSize()\n self.svg_item.setSharedRenderer(self.renderer)\n self.svg_item.setElementId(\"\") # guess empty string loads the whole file\n dim_max = max(size.width(), size.height())\n rect_w = self.rect().width() # Parent rect width\n margin = 32\n self.svg_item.setScale((rect_w - margin) / dim_max)\n self.svg_item.setPos(self.rect().center() - self.svg_item.sceneBoundingRect().center())\n self.svg_item.setGraphicsEffect(self.colorizer)\n self.setFlag(QGraphicsItem.ItemIsMovable, enabled=True)\n self.setFlag(QGraphicsItem.ItemIsSelectable, enabled=True)\n self.setFlag(QGraphicsItem.ItemIsFocusable, enabled=True)\n self.setFlag(QGraphicsItem.ItemSendsScenePositionChanges, enabled=True)\n self.setAcceptHoverEvents(True)\n self.setCursor(Qt.PointingHandCursor)\n # Set exclamation, execution_log, and rank icons position\n self.exclamation_icon.setPos(self.rect().topRight() - self.exclamation_icon.sceneBoundingRect().topRight())\n self.execution_icon.setPos(\n self.rect().bottomRight() - 0.5 * self.execution_icon.sceneBoundingRect().bottomRight()\n )\n self.rank_icon.setPos(self.rect().topLeft())\n\n def name(self):\n \"\"\"Returns name of the item that is represented by this icon.\n\n Returns:\n str: icon's name\n \"\"\"\n return self._name\n\n def update_name_item(self, new_name):\n \"\"\"Set a new text to name item.\n\n Args:\n new_name (str): icon's name\n \"\"\"\n self._name = new_name\n self.name_item.setText(new_name)\n self._reposition_name_item()\n\n def set_name_attributes(self):\n \"\"\"Set name QGraphicsSimpleTextItem attributes (font, size, position, etc.)\"\"\"\n # Set font size and style\n font = self.name_item.font()\n font.setPixelSize(self.FONT_SIZE_PIXELS)\n font.setBold(True)\n self.name_item.setFont(font)\n\n def _reposition_name_item(self):\n \"\"\"Set name item position (centered on top of the master icon).\"\"\"\n main_rect = self.sceneBoundingRect()\n name_rect = self.name_item.sceneBoundingRect()\n self.name_item.setPos(main_rect.center().x() - name_rect.width() / 2, main_rect.y() - name_rect.height() - 4)\n\n def conn_button(self, position=\"left\"):\n \"\"\"Returns item's connector button.\n\n Args:\n position (str): \"left\", \"right\" or \"bottom\"\n\n Returns:\n QWidget: connector button\n \"\"\"\n return self.connectors.get(position, self.connectors[\"left\"])\n\n def outgoing_connection_links(self):\n \"\"\"Collects outgoing connection links.\n\n Returns:\n list of LinkBase: outgoing links\n \"\"\"\n return [l for conn in self.connectors.values() for l in conn.outgoing_links()]\n\n def incoming_links(self):\n \"\"\"Collects incoming connection links.\n\n Returns:\n list of LinkBase: outgoing links\n \"\"\"\n return [l for conn in self.connectors.values() for l in conn.incoming_links()]\n\n def _closest_connector(self, pos):\n \"\"\"Returns the closest connector button to given scene pos.\"\"\"\n connectors = list(self.connectors.values())\n distances = [(pos - connector.sceneBoundingRect().center()).manhattanLength() for connector in connectors]\n index_min = min(range(len(distances)), key=distances.__getitem__)\n return connectors[index_min]\n\n def _update_link_drawer_destination(self, pos=None):\n \"\"\"Updates link drawer destination. If pos is None, then the link drawer would have no destination.\n Otherwise, the destination would be the connector button closest to pos.\n \"\"\"\n link_drawer = self.scene().link_drawer\n if link_drawer is not None:\n if link_drawer.dst_connector is not None:\n link_drawer.dst_connector.set_normal_brush()\n if pos is not None:\n link_drawer.dst_connector = self._closest_connector(pos)\n link_drawer.dst_connector.set_hover_brush()\n else:\n link_drawer.dst_connector = None\n link_drawer.update_geometry()\n\n def hoverEnterEvent(self, event):\n \"\"\"Sets a drop shadow effect to icon when mouse enters its boundaries.\n\n Args:\n event (QGraphicsSceneMouseEvent): Event\n \"\"\"\n self.prepareGeometryChange()\n self.graphicsEffect().setEnabled(True)\n event.accept()\n self._update_link_drawer_destination(event.scenePos())\n\n def hoverMoveEvent(self, event):\n event.accept()\n self._update_link_drawer_destination(event.scenePos())\n\n def hoverLeaveEvent(self, event):\n \"\"\"Disables the drop shadow when mouse leaves icon boundaries.\n\n Args:\n event (QGraphicsSceneMouseEvent): Event\n \"\"\"\n self.prepareGeometryChange()\n self.graphicsEffect().setEnabled(False)\n event.accept()\n self._update_link_drawer_destination()\n\n def mousePressEvent(self, event):\n \"\"\"Updates scene's icon group.\"\"\"\n super().mousePressEvent(event)\n icon_group = set(x for x in self.scene().selectedItems() if isinstance(x, ProjectItemIcon)) | {self}\n for icon in icon_group:\n icon.previous_pos = icon.scenePos()\n self.scene().icon_group = icon_group\n\n def update_links_geometry(self):\n \"\"\"Updates geometry of connected links to reflect this item's most recent position.\"\"\"\n scene = self.scene()\n if not scene:\n return\n icon_group = scene.icon_group | {self}\n scene.dirty_links |= set(\n link for icon in icon_group for conn in icon.connectors.values() for link in conn.links\n )\n\n def mouseReleaseEvent(self, event):\n \"\"\"Clears pre-bump rects, and pushes a move icon command if necessary.\"\"\"\n for icon in self.scene().icon_group:\n icon.bumped_rects.clear()\n # pylint: disable=undefined-variable\n if (self.scenePos() - self.previous_pos).manhattanLength() > qApp.startDragDistance():\n self._toolbox.undo_stack.push(MoveIconCommand(self, self._toolbox.project()))\n event.ignore()\n super().mouseReleaseEvent(event)\n\n def notify_item_move(self):\n if self._moved_on_scene:\n self._moved_on_scene = False\n scene = self.scene()\n scene.item_move_finished.emit(self)\n\n def contextMenuEvent(self, event):\n \"\"\"Show item context menu.\n\n Args:\n event (QGraphicsSceneMouseEvent): Mouse event\n \"\"\"\n event.accept()\n self.scene().clearSelection()\n self.setSelected(True)\n ind = self._toolbox.project_item_model.find_item(self.name())\n self._toolbox.show_project_or_item_context_menu(event.screenPos(), ind)\n\n def itemChange(self, change, value):\n \"\"\"\n Reacts to item removal and position changes.\n\n In particular, destroys the drop shadow effect when the items is removed from a scene\n and keeps track of item's movements on the scene.\n\n Args:\n change (GraphicsItemChange): a flag signalling the type of the change\n value: a value related to the change\n\n Returns:\n Whatever super() does with the value parameter\n \"\"\"\n if change == QGraphicsItem.ItemScenePositionHasChanged:\n self._moved_on_scene = True\n self._reposition_name_item()\n self.update_links_geometry()\n self._handle_collisions()\n elif change == QGraphicsItem.GraphicsItemChange.ItemSceneChange and value is None:\n self.prepareGeometryChange()\n self.setGraphicsEffect(None)\n elif change == QGraphicsItem.GraphicsItemChange.ItemSceneHasChanged:\n scene = value\n if scene is None:\n self._scene.removeItem(self.name_item)\n else:\n self._scene = scene\n self._scene.addItem(self.name_item)\n self._reposition_name_item()\n return super().itemChange(change, value)\n\n def set_pos_without_bumping(self, pos):\n \"\"\"Sets position without bumping other items. Needed for undoing move operations.\n\n Args:\n pos (QPointF)\n \"\"\"\n self._bumping = False\n self.setPos(pos)\n self._bumping = True\n\n def _handle_collisions(self):\n \"\"\"Handles collisions with other items.\"\"\"\n prevent_overlapping = self._toolbox.qsettings().value(\"appSettings/preventOverlapping\", defaultValue=\"false\")\n if not self.scene() or not self._bumping or prevent_overlapping != \"true\":\n return\n restablished = self._restablish_bumped_items()\n for other in set(self.collidingItems()) - restablished:\n if isinstance(other, ProjectItemIcon):\n other.make_room_for_item(self)\n\n def make_room_for_item(self, other):\n \"\"\"Makes room for another item.\n\n Args:\n item (ProjectItemIcon)\n \"\"\"\n if self not in other.bumped_rects:\n other.bumped_rects[self] = self.sceneBoundingRect()\n if self not in self.scene().icon_group:\n self.scene().icon_group.add(self)\n self.previous_pos = self.scenePos()\n line = QLineF(other.sceneBoundingRect().center(), self.sceneBoundingRect().center())\n intersection = other.sceneBoundingRect() & self.sceneBoundingRect()\n delta = math.atan(line.angle()) * min(intersection.width(), intersection.height())\n unit_vector = line.unitVector()\n self.moveBy(delta * unit_vector.dx(), delta * unit_vector.dy())\n\n def _restablish_bumped_items(self):\n \"\"\"Moves bumped items back to their original position if no collision would happen anymore.\"\"\"\n restablished = set()\n try:\n for other, rect in self.bumped_rects.items():\n if not self.sceneBoundingRect().intersects(rect):\n other.setPos(rect.center())\n restablished.add(other)\n for other in restablished:\n self.bumped_rects.pop(other, None)\n except RuntimeError:\n pass\n return restablished\n\n def select_item(self):\n \"\"\"Update GUI to show the details of the selected item.\"\"\"\n ind = self._toolbox.project_item_model.find_item(self.name())\n self._toolbox.ui.treeView_project.setCurrentIndex(ind)\n\n def paint(self, painter, option, widget=None):\n \"\"\"Sets a dashed pen if selected.\"\"\"\n selected = bool(option.state & QStyle.StateFlag.State_Selected)\n self._selection_halo.setVisible(selected)\n option.state &= ~QStyle.StateFlag.State_Selected\n super().paint(painter, option, widget)\n\n\nclass ConnectorButton(QGraphicsPathItem):\n \"\"\"Connector button graphics item. Used for Link drawing between project items.\"\"\"\n\n # Regular and hover brushes\n brush = QBrush(QColor(255, 255, 255)) # Used in filling the item\n hover_brush = QBrush(QColor(50, 0, 50, 128)) # Used in filling the item while hovering\n\n def __init__(self, toolbox, parent, position=\"left\"):\n \"\"\"\n Args:\n toolbox (ToolboxUI): QMainWindow instance\n parent (ProjectItemIcon): parent graphics item\n position (str): Either \"top\", \"left\", \"bottom\", or \"right\"\n \"\"\"\n super().__init__(parent)\n self._parent = parent\n self._toolbox = toolbox\n self.position = position\n self.links = list()\n self.setBrush(self.brush)\n parent_rect = parent.rect()\n extent = 0.2 * parent_rect.width()\n self._rect = QRectF(0, 0, extent, extent)\n if position == \"top\":\n self._rect.moveCenter(QPointF(parent_rect.center().x(), parent_rect.top() + extent / 2))\n elif position == \"left\":\n self._rect.moveCenter(QPointF(parent_rect.left() + extent / 2, parent_rect.center().y()))\n elif position == \"bottom\":\n self._rect.moveCenter(QPointF(parent_rect.center().x(), parent_rect.bottom() - extent / 2))\n elif position == \"right\":\n self._rect.moveCenter(QPointF(parent_rect.right() - extent / 2, parent_rect.center().y()))\n self.setAcceptHoverEvents(True)\n self.setCursor(Qt.PointingHandCursor)\n\n def rect(self):\n return self._rect\n\n def update_path(self, parent_radius):\n radius = 0.2 * parent_radius\n path = QPainterPath()\n path.addRoundedRect(self._rect, radius, radius)\n self.setPath(path)\n\n @property\n def parent(self):\n return self._parent\n\n def outgoing_links(self):\n return [l for l in self.links if l.src_connector == self]\n\n def incoming_links(self):\n return [l for l in self.links if l.dst_connector == self]\n\n def parent_name(self):\n \"\"\"Returns project item name owning this connector button.\"\"\"\n return self._parent.name()\n\n def project_item(self):\n \"\"\"Returns the project item this connector button is attached to.\n\n Returns:\n ProjectItem: project item\n \"\"\"\n return self._toolbox.project().get_item(self._parent.name())\n\n def mousePressEvent(self, event):\n \"\"\"Connector button mouse press event.\n\n Args:\n event (QGraphicsSceneMouseEvent): Event\n \"\"\"\n if event.button() != Qt.LeftButton:\n event.accept()\n return\n self._parent.select_item()\n self._start_link(event)\n\n def _start_link(self, event):\n scene = self.scene()\n if scene.link_drawer is None:\n scene.select_link_drawer(LinkType.JUMP if event.modifiers() & Qt.AltModifier else LinkType.CONNECTION)\n scene.link_drawer.wake_up(self)\n\n def set_friend_connectors_enabled(self, enabled):\n \"\"\"Enables or disables all connectors in the parent.\n\n This is called by LinkDrawer to disable invalid connectors while drawing and reenabling them back when done.\n\n Args:\n enabled (bool): True to enable connectors, False to disable\n \"\"\"\n for conn in self._parent.connectors.values():\n conn.setEnabled(enabled)\n conn.setBrush(conn.brush) # Remove hover brush from src connector that was clicked\n\n def set_hover_brush(self):\n self.setBrush(self.hover_brush)\n\n def set_normal_brush(self):\n self.setBrush(self.brush)\n\n def hoverEnterEvent(self, event):\n \"\"\"Sets a darker shade to connector button when mouse enters its boundaries.\n\n Args:\n event (QGraphicsSceneMouseEvent): Event\n \"\"\"\n self.set_hover_brush()\n\n def hoverLeaveEvent(self, event):\n \"\"\"Restore original brush when mouse leaves connector button boundaries.\n\n Args:\n event (QGraphicsSceneMouseEvent): Event\n \"\"\"\n self.set_normal_brush()\n\n def itemChange(self, change, value):\n \"\"\"If this is being removed from the scene while it's the origin of the link drawer,\n put the latter to sleep.\"\"\"\n if change == QGraphicsItem.GraphicsItemChange.ItemSceneChange and value is None:\n link_drawer = self.scene().link_drawer\n if link_drawer is not None and link_drawer.src_connector is self:\n link_drawer.sleep()\n return super().itemChange(change, value)\n\n\nclass ExecutionIcon(QGraphicsEllipseItem):\n \"\"\"An icon to show information about the item's execution.\"\"\"\n\n _CHECK = \"\\uf00c\" # Success\n _CROSS = \"\\uf00d\" # Fail\n _CLOCK = \"\\uf017\" # Waiting\n _SKIP = \"\\uf054\" # Excluded\n\n def __init__(self, parent):\n \"\"\"\n Args:\n parent (ProjectItemIcon): the parent item\n \"\"\"\n super().__init__(parent)\n self._parent = parent\n self._execution_state = \"not started\"\n self._text_item = QGraphicsTextItem(self)\n font = QFont('Font Awesome 5 Free Solid')\n self._text_item.setFont(font)\n parent_rect = parent.rect()\n self.setRect(0, 0, 0.5 * parent_rect.width(), 0.5 * parent_rect.height())\n self.setPen(Qt.NoPen)\n # pylint: disable=undefined-variable\n self.normal_brush = qApp.palette().window()\n self.selected_brush = qApp.palette().highlight()\n self.setBrush(self.normal_brush)\n self.setAcceptHoverEvents(True)\n self.setFlag(QGraphicsItem.ItemIsSelectable, enabled=False)\n self.hide()\n\n def item_name(self):\n return self._parent.name()\n\n def _repaint(self, text, color):\n self._text_item.prepareGeometryChange()\n self._text_item.setPos(0, 0)\n self._text_item.setPlainText(text)\n self._text_item.setDefaultTextColor(color)\n size = self._text_item.boundingRect().size()\n dim_max = max(size.width(), size.height())\n rect_w = self.rect().width()\n self._text_item.setScale(rect_w / dim_max)\n self._text_item.setPos(self.sceneBoundingRect().center() - self._text_item.sceneBoundingRect().center())\n self.show()\n\n def mark_execution_waiting(self):\n self._execution_state = \"waiting for dependencies\"\n self._repaint(self._CLOCK, QColor(\"orange\"))\n\n def mark_execution_ignored(self):\n self._execution_state = \"not started\"\n self.hide()\n\n def mark_execution_started(self):\n self._execution_state = \"in progress\"\n self._repaint(self._CHECK, QColor(\"orange\"))\n\n def mark_execution_finished(self, item_finish_state):\n if item_finish_state == ItemExecutionFinishState.SUCCESS:\n self._execution_state = \"completed\"\n self._repaint(self._CHECK, QColor(\"green\"))\n elif item_finish_state == ItemExecutionFinishState.EXCLUDED:\n self._execution_state = \"excluded\"\n self._repaint(self._CHECK, QColor(\"orange\"))\n elif item_finish_state == ItemExecutionFinishState.SKIPPED:\n self._execution_state = \"skipped\"\n self._repaint(self._SKIP, QColor(\"chocolate\"))\n else:\n self._execution_state = \"failed\"\n self._repaint(self._CROSS, QColor(\"red\"))\n\n def hoverEnterEvent(self, event):\n tip = f\"
Execution {self._execution_state}. Select this item to see Console and Log messages.
\"\n QToolTip.showText(event.screenPos(), tip)\n\n def hoverLeaveEvent(self, event):\n QToolTip.hideText()\n\n\nclass ExclamationIcon(QGraphicsTextItem):\n \"\"\"An icon to notify that a ProjectItem is missing some configuration.\"\"\"\n\n FONT_SIZE_PIXELS = 14 # Use pixel size to prevent scaling by system.\n\n def __init__(self, parent):\n \"\"\"\n Args:\n parent (ProjectItemIcon): the parent item\n \"\"\"\n super().__init__(parent)\n self._parent = parent\n self._notifications = list()\n font = QFont('Font Awesome 5 Free Solid')\n font.setPixelSize(self.FONT_SIZE_PIXELS)\n self.setFont(font)\n self.setDefaultTextColor(QColor(\"red\"))\n self.setPlainText(\"\\uf06a\")\n doc = self.document()\n doc.setDocumentMargin(0)\n self.setAcceptHoverEvents(True)\n self.setFlag(QGraphicsItem.ItemIsSelectable, enabled=False)\n self.hide()\n\n def clear_notifications(self):\n \"\"\"Clear all notifications.\"\"\"\n self._notifications.clear()\n self.hide()\n\n def add_notification(self, text):\n \"\"\"Add a notification.\"\"\"\n self._notifications.append(text)\n self.show()\n\n def remove_notification(self, subtext):\n \"\"\"Remove the first notification that includes given subtext.\"\"\"\n k = next((i for i, text in enumerate(self._notifications) if subtext in text), None)\n if k is not None:\n self._notifications.pop(k)\n if not self._notifications:\n self.hide()\n\n def hoverEnterEvent(self, event):\n \"\"\"Shows notifications as tool tip.\n\n Args:\n event (QGraphicsSceneMouseEvent): Event\n \"\"\"\n if not self._notifications:\n return\n tip = \"
\" + \"
\".join(self._notifications)\n QToolTip.showText(event.screenPos(), tip)\n\n def hoverLeaveEvent(self, event):\n \"\"\"Hides tool tip.\n\n Args:\n event (QGraphicsSceneMouseEvent): Event\n \"\"\"\n QToolTip.hideText()\n\n\nclass RankIcon(QGraphicsTextItem):\n \"\"\"An icon to show the rank of a ProjectItem within its DAG.\"\"\"\n\n def __init__(self, parent):\n \"\"\"\n Args:\n parent (ProjectItemIcon): the parent item\n \"\"\"\n super().__init__(parent)\n self._parent = parent\n self._rect = parent.component_rect\n self.bg = QGraphicsPathItem(self)\n bg_brush = QApplication.palette().brush(QPalette.ToolTipBase)\n self.bg.setBrush(bg_brush)\n self.bg.setFlag(QGraphicsItem.ItemStacksBehindParent)\n self.setFlag(QGraphicsItem.ItemIsSelectable, enabled=False)\n font = self.font()\n font.setPixelSize(parent.FONT_SIZE_PIXELS)\n font.setBold(True)\n self.setFont(font)\n doc = self.document()\n doc.setDocumentMargin(0)\n\n def _make_path(self, radius):\n path = QPainterPath()\n if radius == 0:\n path.addRect(self._rect)\n return path\n path.moveTo(0, self._rect.height())\n path.lineTo(0.5 * self._rect.width(), self._rect.height())\n path.arcTo(self._rect, 270, 90)\n path.lineTo(self._rect.width(), 0)\n path.lineTo(0.5 * self._rect.width(), 0)\n path.arcTo(self._rect, 90, 90)\n path.lineTo(0, self._rect.height())\n return path\n\n def update_path(self, radius):\n path = self._make_path(radius)\n self.bg.setPath(path)\n\n def set_rank(self, rank):\n self.setPlainText(str(rank))\n self.setTextWidth(self._rect.width())\n # Align center\n fmt = QTextBlockFormat()\n fmt.setAlignment(Qt.AlignHCenter)\n cursor = self.textCursor()\n cursor.select(QTextCursor.SelectionType.Document)\n cursor.mergeBlockFormat(fmt)\n cursor.clearSelection()\n self.setTextCursor(cursor)\n","repo_name":"spine-tools/Spine-Toolbox","sub_path":"spinetoolbox/project_item_icon.py","file_name":"project_item_icon.py","file_ext":"py","file_size_in_byte":27419,"program_lang":"python","lang":"en","doc_type":"code","stars":54,"dataset":"github-code","pt":"31"}
+{"seq_id":"1746507470","text":"performances = {'Ventriloquism': '9:00am',\n 'Snake Charmer': '12:00pm',\n 'Amazing Acrobatics': '2:00pm',\n 'Enchanted Elephants': '5:00pm'}\nschedule_file = open('schedule.txt', 'w')\n\nfor key, val in performances.items():\n schedule_file.write(key + ' - ' + val + '\\n')\n\nschedule_file.close()\n","repo_name":"ps-interactive/ics_solutions","sub_path":"ic_python_using_lists_dictionaries_loops_files_and_modules/page.4-1-3.writing_the_circus_schedule/answer/circus.py","file_name":"circus.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"31"}
+{"seq_id":"34011303588","text":"# Download and save to file robots.txt\n# from wikipedia, twitter websites etc.\n\n# підвантажуємо потрібну бібліотеку\nimport requests\n\n# обираємо потрібну адресу\nurl = 'https://en.wikipedia.org/robots.txt'\n\n\ndef main():\n # перевіряємо успішність запиту\n response = requests.get(url)\n if response.status_code == 200:\n print('Success!')\n elif response.status_code == 404:\n print('Not Found.')\n\n # зберігаємо текст у файл\n with open('robots.txt', 'w', encoding='utf-8') as filename:\n filename.write(response.text)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"romanpovzyk/ba_python_tasks","sub_path":"ba_python_tasks_32/task_32_1.py","file_name":"task_32_1.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"uk","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"9428520700","text":"# Quantum teleportation emulation\n# Source: http://dataespresso.com/en/2018/07/29/Tutorial-Getting-started-with-Quantum-Teleportation-Python/\n\nfrom projectq.ops import All, H, CNOT, Measure, X, Z\nfrom projectq import MainEngine\n\ndef create_bell_pair(engine):\n # Allocate 2 qubits\n qubit_one = engine.allocate_qubit()\n qubit2 = engine.allocate_qubit()\n\n ''' \n Hadamard gate to put Qubit one in superposition\n This sets the value of a equal probability of being 1 or 0\n '''\n H | qubit_one\n\n '''\n CNOT gate to flip the second Qubit conditionally\n on the first qubit being in the state |1⟩\n '''\n CNOT | (qubit_one, qubit2)\n\n return qubit_one, qubit2\n\n\n\ndef create_message(quantum_engine='',qubit_one='', message_value = 0):\n\n qubit_to_send = quantum_engine.allocate_qubit()\n if message_value == 1:\n '''\n setting the qubit to positive if message_value is 1\n by flipping the base state with a Pauli-X gate.\n '''\n X | qubit_to_send\n\n\n # entangle the original qubit with the message qubit\n CNOT | (qubit_to_send, qubit_one)\n\n '''\n 1 - Put the message qubit in superposition \n 2 - Measure out the two values to get the classical bit value\n by collapsing the state. \n '''\n H | qubit_to_send\n Measure | qubit_to_send\n Measure | qubit_one\n\n # The qubits are now turned into normal bits we can send through classical channels\n classical_encoded_message = [int(qubit_to_send), int(qubit_one)]\n\n return classical_encoded_message\n\n\ndef message_reciever(quantum_engine, message, qubit2):\n '''\n Pauli-X and/or Pauli-Z gates are applied to the Qubit,\n conditionally on the values in the message.\n '''\n if message[1] == 1:\n X | qubit2\n if message[0] == 1:\n Z | qubit2\n\n '''\n Measuring the Qubit and collapsing the state down to either 1 or 0\n '''\n Measure | qubit2\n\n quantum_engine.flush()\n\n recieved_bit = int(qubit2)\n return recieved_bit\n\ndef send_receive(bit=0):\n\n # Create bell pair\n qubit_one, qubit_two = create_bell_pair(quantum_engine)\n\n # Entangle the bit with the first qubit\n classical_encoded_message = create_message(quantum_engine=quantum_engine, qubit_one=qubit_one, message_value=bit)\n\n # Teleport the bit and return it back\n return message_reciever(quantum_engine, classical_encoded_message, qubit_two)\n\n\ndef send_full_message(message='DataEspresso.com'):\n # Convert the string into binary values\n binary_encoded_message = [bin(ord(x))[2:].zfill(8) for x in message]\n print('Message to send: ', message)\n print('Binary message to send: ', binary_encoded_message)\n\n '''\n The binary message is divided into a list of each word represented in binary.\n We iterate through each word, and then each bit in the letter.\n Then we append the bits to an list to get back the letter representation\n '''\n received_bytes_list = []\n for letter in binary_encoded_message:\n received_bits = ''\n for bit in letter:\n received_bits = received_bits + str(send_receive(int(bit)))\n received_bytes_list.append(received_bits)\n\n binary_to_string = ''.join([chr(int(x, 2)) for x in received_bytes_list])\n print('Received Binary message: ', received_bytes_list)\n print('Received message: ', binary_to_string)\n\n\n\n# Init engine\nquantum_engine = MainEngine()\n\nmessage = 'Quantum Break'\nsend_full_message(message)\n\n","repo_name":"noff/quantum-stuff","sub_path":"teleportation.py","file_name":"teleportation.py","file_ext":"py","file_size_in_byte":3464,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"14701633374","text":"import numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\n\nL = 20\nn = 20000\nk = 1\nfreq = k / L\n\ndef findCoefficients(Function, L, res, nc):\n cof = np.zeros((nc, 2))\n x = np.linspace(0, L, res)\n dx = L / res\n for i in range(nc):\n sini = np.sin(2 * np.pi * i * x / L)\n cosi = np.cos(2 * np.pi * i * x / L)\n cof[i,0] = np.sum(Function * cosi) * dx * (2 / L)\n cof[i,1] = np.sum(Function * sini) * dx * (2 / L)\n cof[0,:] = cof[0,:] / 2\n return cof\n\ndef plotCoefficients(cof, L, res):\n nc = np.shape(cof)[0]\n x = np.linspace(0, L, res)\n func = np.zeros(res)\n for i in range(nc):\n sini = np.sin(2 * np.pi * i * x / L)\n cosi = np.cos(2 * np.pi * i * x / L)\n func += cof[i,0] * cosi + cof[i,1] * sini\n return func\n\ndef squareWave(x, A):\n length = np.shape(x)[0]\n func = np.zeros(length)\n for i in range(length // 2, length):\n func[i] = A\n return func\n\nx = np.linspace(0, L, n)\nsqrW = squareWave(x, 1)\n\ncoefs = findCoefficients(sqrW, L, n, 10000)\nApprox = plotCoefficients(coefs, L, n)\n\nplt.plot(x, sqrW)\nplt.plot(x, Approx)\nplt.show()\n","repo_name":"BirkKarlsen/TFY4240","sub_path":"Generel Fourier.py","file_name":"Generel Fourier.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}
+{"seq_id":"33899948177","text":"from test_sort import * \n\ndef insertion_sort(nums):\n n = len(nums)\n if n <= 1:\n return nums\n \n for i in range(1,n):\n # Warning: starting from i = 1 causes too many unnecessary comparisons\n temp = nums[i]\n for j in range(0, i):\n if temp < nums[j]:\n nums[j], temp = temp, nums[j]\n nums[i] = temp\n \n return\n\ndef insertion_sort_clrs(nums):\n n = len(nums)\n for j in range(1, n):\n key = nums[j]\n i = j - 1\n while i >= 0 and nums[i] > key:\n nums[i+1] = nums[i] # We know the new item is smaller so we move existing items forward by one\n i = i - 1\n nums[i+1] = key\n\ndata = gen_test(1e4)\n\nprint(\"Pre-sort: \",verify_sort(data))\ninsertion_sort(data)\nprint(\"Sort1 finished.\")\nprint(\"Sort1 success:\",verify_sort(data))\n\nrandom.shuffle(data)\ninsertion_sort_clrs(data)\nprint(\"Sort 2 success:\",verify_sort(data))\n \n","repo_name":"JasonVann/CLRS","sub_path":"S1_Foundation/C2_GettingStarted/insertion_sort.py","file_name":"insertion_sort.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"}
+{"seq_id":"21105380131","text":"#-------------------------------------------------------------------------------\n# Export debug line info from an ELF that contains GCC DWARF1 data\n#-------------------------------------------------------------------------------\nfrom __future__ import print_function\nimport io\nimport os\nimport struct\nimport sys\n\nfrom elftools.elf.elffile import ELFFile\nfrom typing import NamedTuple\nfrom dataclasses import dataclass\n\ndef formatted_read(srcdata, format, numbytes):\n\treturn struct.unpack(format, srcdata.read(numbytes))[0]\n\n@dataclass\nclass LineEntry:\n\t# the line number in the source file that corresponds to the current instruction\n\tlineNum: int\n\t# position on the line at which a statement occurs, value is 0xffff if the position doesn't need to be determined\n\tstatementPos: int\n\t# offset from this compile unit's base address to the current instruction\n\taddrDelta: int\n\n@dataclass\nclass LineSectionChunk:\n\t# the size of this compile unit's .line section\n\tsectionSize: int\n\t# the virtual address that this compile unit starts at\n\tcuStartAddress: int\n\nclass SrcinfoEntry(NamedTuple):\n\t# offset into the .line section\n\tlineEntryOffset: int\n\t# offset into the .debug_sfnames section\n\tsfNameOffset: int\n\nclass SrcinfoSectionChunk(NamedTuple):\n\t# offset to a LineSectionChunk from the beginning of the .line section\n\tcuLineOffset: int\n\t# offset into the .debug_sfnames section for this compile unit\n\tcuSfnamesOffset: int\n\t# starting offset for this compile unit's .text section\n\tcuTextStartOffset: int\n\t# ending offset for this compile unit's .text section\n\tcuTextEndOffset: int\n\t# if specified by the compiler, describes the date/time at which this compile unit was compiled\n\t# defaults to 0xffffffff otherwise\n\tcompileDateTime: int\n\t# a list of SrcinfoEntry data for this compile unit\n\tentries: list\n\tfinalLineEntryOffset: int\n\n\ndef process_file(filename, outdirectory):\n\tprint('Processing file:', filename)\n\twith open(filename, 'rb') as f:\n\t\telffile = ELFFile(f)\n\t\tsrcinfoSection = elffile.get_section_by_name(\".debug_srcinfo\")\n\t\tsrcinfoChunks = []\n\n\t\twith io.BytesIO(srcinfoSection.data()) as srcinfoData:\n\t\t\t# read each compile unit chunk in the .debug_srcinfo section\n\t\t\twhile srcinfoData.tell() < srcinfoSection.data_size:\n\t\t\t\tcuLineOffset = formatted_read(srcinfoData, \">I\", 4)\n\t\t\t\tcuSfnamesOffset = formatted_read(srcinfoData, \">I\", 4)\n\t\t\t\tcuTextStartOffset = formatted_read(srcinfoData, \">I\", 4)\n\t\t\t\tcuTextEndOffset = formatted_read(srcinfoData, \">I\", 4)\n\t\t\t\tcompileDateTime = formatted_read(srcinfoData, \">I\", 4)\n\t\t\t\tsrcInfoEntries = []\n\n\t\t\t\t# get all srcinfo entries for the current chunk\n\t\t\t\twhile True:\n\t\t\t\t\t# if this is the final entry, the value will be the offset to the final line entry for this compile unit's .line section\n\t\t\t\t\tlineEntryOffset = formatted_read(srcinfoData, \">I\", 4)\n\t\t\t\t\t# acts as a terminator with the value 0xffffffff if this is the final entry\n\t\t\t\t\tsfNameOffset = formatted_read(srcinfoData, \">I\", 4)\n\n\t\t\t\t\tif sfNameOffset == 0xffffffff:\n\t\t\t\t\t\tsrcinfoChunks.append(SrcinfoSectionChunk(cuLineOffset, cuSfnamesOffset, cuTextStartOffset, cuTextEndOffset, compileDateTime, srcInfoEntries, lineEntryOffset))\n\t\t\t\t\t\t# break out and start reading the next srcinfo chunk\n\t\t\t\t\t\tbreak\n\t\t\t\t\telse:\n\t\t\t\t\t\tsrcInfoEntries.append(SrcinfoEntry(lineEntryOffset, sfNameOffset))\n\n\t\twith open(os.path.join(outdirectory, \"debug_lines.txt\"), 'w') as outfile:\n\t\t\t# get the line data for each srcinfo chunk\n\t\t\tlineSection = elffile.get_section_by_name(\".line\")\n\t\t\twith io.BytesIO(lineSection.data()) as lineData:\n\t\t\t\tsfnamesSection = elffile.get_section_by_name(\".debug_sfnames\")\n\t\t\t\tsfnamesData = io.BytesIO(sfnamesSection.data())\n\n\t\t\t\tfor srcinfoChunk in srcinfoChunks:\n\t\t\t\t\tlineData.seek(srcinfoChunk.cuLineOffset)\n\n\t\t\t\t\tlineChunk = LineSectionChunk(0,0)\n\t\t\t\t\tlineChunk.sectionSize = formatted_read(lineData, \">I\", 4)\n\t\t\t\t\tlineChunk.cuStartAddress = formatted_read(lineData, \">I\", 4)\n\n\t\t\t\t\tfor idx, entry in enumerate(srcinfoChunk.entries):\n\t\t\t\t\t\t# jump to the entry and name offsets relative to this chunk's sections\n\t\t\t\t\t\t# comments in GCC's source code say otherwise, but this is the correct way\n\t\t\t\t\t\tlineData.seek(srcinfoChunk.cuLineOffset + entry.lineEntryOffset)\n\t\t\t\t\t\tsfnamesData.seek(srcinfoChunk.cuSfnamesOffset + entry.sfNameOffset)\n\t\t\t\t\t\tsourceFile = ''.join(iter(lambda: sfnamesData.read(1).decode('utf-8'), '\\x00'))\n\n\t\t\t\t\t\t# one srcinfo entry can (implicitly) point to multiple line entries for that source file\n\t\t\t\t\t\t# so keep reading line entries until we're at the one the next srcinfo entry points to (or we've run out of entries)\n\t\t\t\t\t\twhile True:\n\t\t\t\t\t\t\tlineEntry = LineEntry(0,0,0)\n\t\t\t\t\t\t\tlineEntry.lineNum = formatted_read(lineData, \">I\", 4)\n\t\t\t\t\t\t\tlineEntry.statementPos = formatted_read(lineData, \">H\", 2)\n\t\t\t\t\t\t\tlineEntry.addrDelta = formatted_read(lineData, \">I\", 4)\n\n\t\t\t\t\t\t\taddrString = format(lineChunk.cuStartAddress + lineEntry.addrDelta, '08X')\n\t\t\t\t\t\t\tlineNumString = str\n\t\t\t\t\t\t\tif lineEntry.statementPos != 0xffff:\n\t\t\t\t\t\t\t\tlineNumString = f\"(line {str(lineEntry.lineNum)}, column {str(lineEntry.statementPos)})\"\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tlineNumString = f\"(line {str(lineEntry.lineNum)})\"\n\n\t\t\t\t\t\t\toutLine = f\"{addrString}: {sourceFile} {lineNumString}\"\n\t\t\t\t\t\t\toutfile.write(outLine + '\\n')\n\n\t\t\t\t\t\t\tmaxEntry = len(srcinfoChunk.entries) - 1\n\t\t\t\t\t\t\tif idx == maxEntry or lineData.tell() >= srcinfoChunk.cuLineOffset + srcinfoChunk.entries[idx+1].lineEntryOffset:\n\t\t\t\t\t\t\t\tbreak\n\n\nif __name__ == '__main__':\n\tif len(sys.argv) < 3:\n\t\tprint('Expected usage: {0}